Compare commits

...

87 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
lilleman b4f9d42ff1 Answer prose round 1: 0 🔴, 15 🟡 (0 misread); fixed in the stability round 1 commit
CI / tests (pull_request) Successful in 2m17s
2026-11-11 18:16:14 +01:00
lilleman f549f8617a Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); fixed in the stability round 1 commit, with the line in --help and item 324 filed to count chunks without it 2026-11-11 18:16:14 +01:00
lilleman e7128656b2 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); ask for the Chunk items: line on resume too, split it on "and", and say on stderr why todo.md scores no item 2026-11-11 18:16:14 +01:00
lilleman 7507b3b670 Say in rule's docstring that code stamps the verdict with the chunk's items 2026-11-11 17:44:42 +01:00
lilleman 2d5ad7e895 Answer security round 1: 0 🔴, 0 🟡 (0 misread); clean 2026-11-11 17:44:27 +01:00
lilleman daa3a54b90 Have loop-claude read the items a chunk takes from the worker's Chunk items: line, and keep the judge's escalation and release-ready fields, which code misread in replays
CI / tests (pull_request) Successful in 2m7s
2026-11-11 17:43:40 +01:00
lilleman 0581a0fec4 Re-score item 297: L 4, since it adds a parsed worker line across several components that route live loops 2026-11-11 16:59:43 +01:00
lilleman e2e3fb36e7 Drop item 322: moot, since this repo's working rules sit in the decision log the judge reads
CI / tests (pull_request) Successful in 2m7s
2026-11-11 16:53:45 +01:00
lilleman d41dfd0401 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); move this repo's working rules into the decision log, which the judge reads 2026-11-11 16:53:42 +01:00
lilleman 9cf48d5337 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); fixed in the stability round 1 commit, principle 7 left as it was 2026-11-11 16:46:27 +01:00
lilleman 32b4df6985 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); fixed in the stability round 1 commit, ~/.claude sessions answered in the deploy decision 2026-11-11 16:46:27 +01:00
lilleman dcb9abf644 Answer stability round 1: 1 🔴, 3 🟡 (0 misread); keep the global rules generic, and say in one always-loaded rule of this repo where AGENTS.md's parts went 2026-11-11 16:46:27 +01:00
lilleman 9b770e4893 Fold AGENTS.md into the decision log, .claude/rules/, README and the panel's seat prompts; load CLAUDE.md once in this repo
CI / tests (pull_request) Successful in 2m7s
2026-11-11 16:32:48 +01:00
lilleman 2db7f462a9 Merge remote-tracking branch 'origin/main' into item-307
CI / tests (pull_request) Successful in 2m6s
2026-11-11 16:17:15 +01:00
lilleman b06a189c05 Finish item 307
CI / tests (pull_request) Successful in 2m7s
2026-11-11 16:14:20 +01:00
lilleman c52b5812e9 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no findings
CI / tests (pull_request) Successful in 2m6s
2026-11-11 16:08:16 +01:00
lilleman b6414655d1 Move items 302, 303, 304 and 306 to 0.9.0
CI / tests (pull_request) Successful in 2m6s
2026-11-11 16:07:52 +01:00
lilleman 6d6876fbcf Answer prose round 1: 1 🔴, 7 🟡 (0 misread); state principle 6 as the code runs it, call them project principles, ask on every principle change
CI / tests (pull_request) Successful in 2m7s
2026-11-11 16:07:06 +01:00
lilleman 84d23fa95c Answer stability round 1: 2 🔴, 3 🟡 (0 misread); check AGENTS.md's remaining titles against the log, fix the citation, the prose-reviewer move rule and the worker decision 2026-11-11 16:07:06 +01:00
lilleman 5d903b4bfd Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-11 16:00:17 +01:00
lilleman c9a2c7b704 Propose a principle when a new decision shares its rule with decisions already listed
CI / tests (pull_request) Failing after 2m6s
2026-11-11 15:59:29 +01:00
lilleman 0c2f37d284 Distil 41 decision titles in AGENTS.md into seven principles, and say so where AGENTS.md's list is described 2026-11-11 15:57:43 +01:00
lilleman 118a7d22d3 Check each new decision against the project's principles, in rules/decisions.md and larv-review 2026-11-11 15:50:13 +01:00
lilleman 56ba3b0c1a Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings
CI / tests (pull_request) Successful in 2m6s
2026-11-11 15:30:16 +01:00
lilleman b389b89e13 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); finish item 202, fix the breaches in four more files agents follow
CI / tests (pull_request) Successful in 2m3s
2026-11-11 15:24:02 +01:00
lilleman c0423e49d6 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); state the pattern once, keep in time in the example, fix three more breaches
CI / tests (pull_request) Successful in 2m9s
2026-11-11 15:22:54 +01:00
lilleman ae73be7e22 Ban a verb with nothing as its object in the prose rules, and fix the breaches in CLAUDE.md and two agents
CI / tests (pull_request) Successful in 2m4s
2026-11-11 15:20:44 +01:00
lilleman 15e31607f2 File items 314 to 321 and revise items 307 and 312 after lilleman's answers of 2026-11-11
CI / tests (pull_request) Successful in 2m6s
2026-11-11 15:15:49 +01:00
lilleman eae9a29553 Restore the code spans in items 307, 309 and 311's taglines
CI / tests (pull_request) Successful in 2m4s
2026-11-11 14:52:51 +01:00
lilleman feb15e18fa File items 305 to 313 from the token research of 2026-11-11
CI / tests (pull_request) Successful in 2m4s
2026-11-11 14:52:39 +01:00
lilleman 957ecaea77 File item 304: archive replay transcripts
CI / tests (pull_request) Successful in 2m5s
2026-11-11 14:33:10 +01:00
lilleman ed774a5fc1 Merge origin/main into item-294
CI / tests (pull_request) Successful in 2m5s
2026-11-11 14:27:20 +01:00
lilleman b99e362a8c Answer stability round 2: 0 🔴, 2 🟡 (0 misread); test the submodule filter, skip the git call for an untracked file, merge a repeated breach, cap the staged blob
CI / tests (pull_request) Successful in 2m4s
2026-11-11 14:26:49 +01:00
lilleman d183c81497 File item 303: archive the judge's prompt and reply
CI / tests (pull_request) Successful in 2m3s
2026-11-11 14:21:43 +01:00
lilleman 89bd9e86cc Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-11 14:19:48 +01:00
lilleman 0b5a41fbf9 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); markers come from the added lines, in the stability round's commit 2026-11-11 14:19:48 +01:00
lilleman 21bd753c5b Answer stability round 1: 3 🔴, 3 🟡 (0 misread); list files with diff-index, check the index blob, take override markers from the added lines 2026-11-11 14:19:48 +01:00
lilleman 47c10c4565 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); reword the help paragraph, the changelog bullet and the decision, and restore the entry's old sentence 2026-11-11 14:19:48 +01:00
lilleman 3e289c95d9 Check the files a commit would commit against rule-hook's file rules, and sort .gitignore's allowlist block
CI / tests (pull_request) Failing after 2m2s
2026-11-11 14:07:34 +01:00
82 changed files with 3291 additions and 592 deletions
@@ -0,0 +1,6 @@
# This repo keeps no `AGENTS.md`
`~/.claude` is a checkout of this repo, so an `AGENTS.md` here would load into every other project's sessions. Where a rule names a project's `AGENTS.md`, read it here as:
- the project principles, the title of each decision no project principle covers, and the working rules: the head of `docs/decisions.md`, before `# Decisions`;
- the scoring-run values: `skills/comprehension-panel/seat-prompts.md` → "claude-config's values".
+2 -1
View File
@@ -1,3 +1,4 @@
{
"model": "claude-opus-5-5"
"model": "claude-opus-5-5",
"claudeMdExcludes": ["**/.claude/CLAUDE.md"]
}
+15 -3
View File
@@ -6,7 +6,6 @@
!.gitattributes
!.gitignore
!AGENTS.md
!CHANGELOG.md
!CLAUDE.md
!README.md
@@ -15,6 +14,8 @@
!todo.md
!.claude/
!.claude/rules/
!.claude/rules/*.md
!.claude/settings.json
!.gitea/
!.gitea/workflows/
@@ -25,9 +26,9 @@
!bin/branch_chunks/
!bin/branch_chunks/*.py
!bin/chunk-pr
!bin/chunk-preflight
!bin/chunk_pr/
!bin/chunk_pr/*.py
!bin/chunk-preflight
!bin/chunk_preflight/
!bin/chunk_preflight/*.py
!bin/claude_code/
@@ -50,12 +51,12 @@
!bin/larv_review/
!bin/larv_review/*.py
!bin/loop-claude
!bin/loop-inbox
!bin/loop_claude/
!bin/loop_claude/**/
!bin/loop_claude/**/*.py
!bin/loop_effects/
!bin/loop_effects/*.py
!bin/loop-inbox
!bin/loop_inbox/
!bin/loop_inbox/*.py
!bin/loop_state/
@@ -63,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/
@@ -99,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/
@@ -111,6 +119,9 @@
!bin/transcript_archive/*.py
!docs/
!docs/*.md
!judge-field-trials/
!judge-field-trials/*.py
!judge-field-trials/README.md
!presentation/
!presentation/README.md
!presentation/build-pdf.py
@@ -138,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
-81
View File
@@ -1,81 +0,0 @@
# Working here
Decisions live in `docs/decisions.md`:
- bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release
- deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
- deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
- loop-claude: a `claude` that cannot start is a failed worker run, retried
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; it interrupts for a reserved choice those don't settle, or an ask that carries no recommendation
- loop-claude: every claude it or loop-inbox opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, so Claude Code skips its trust dialog, and neither tool writes `~/.claude.json`
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
- loop-claude: every claude it starts bypasses permissions inside its sandbox
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
- review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review
- review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none
- review: a pass gets at most two rounds per chunk, and the release review's architecture and principles passes five, with no more and no ask for more; the fixes answering a pass's last round merge once the gate passes
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
- review: a project decision may suspend the comprehension check for the plan items it names
- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
- 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: an ask no user answers leaves the PR unmerged
- review: each pass keeps a reviewer of its own
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
- 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 architecture and principles passes run only in the release review, a release's last chunk, which must land before the release is ready to cut; between releases the product-owner pass reviews changes to what consumers rely on
- review: the comprehension check records how hard a project is to read, and no score blocks a merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
- review: the premises chunk's whole review is the human's approval
- review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
- 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
- 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 only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
- 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
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
- 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: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides any rule but those `rule-hook --help` marks as taking none, and larv-review's overrides pass rules on each override before merge
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
- tests: CI runs the suite through `ci.sh` on every pull request, in a pinned Python container, and `main`'s branch protection holds a merge until it passes
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
## Working rules
- `routing-calls-raised.md` sits at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each of its lines is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its steps or the delegation rule is the human's. The chunk that settles the calls cites the latest stamp it settled in `docs/decisions.md` → `routing:`, whatever the human decided, so they are not filed again. Once a chunk that changes the ladder, its steps or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`: the figures then count only chunks finished after it, and its calls may be raised again.
- When `~/.claude/settings.json` has uncommitted changes, carry them into `~/code/claude-config` on a branch of their own and merge them through a PR: Claude Code writes that file from any session, and `deploy-release` refuses to move `~/.claude` until a release holds them. Read their diff first: `git -C ~/.claude diff HEAD -- settings.json`. An empty diff means only the model or the key order changed, which `deploy-release` takes as no change. When the diff holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
## Scoring run
The project values for `skills/comprehension-panel/seat-prompts.md`:
- `{language}`: Python
- `{kind}`: a Claude Code configuration with an agent loop and review skills
- `{domain}`: driving headless Claude Code sessions, agent review workflows
- `{domain docs}`: the Claude Code documentation
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a third time
+11 -1
View File
@@ -1,7 +1,17 @@
# 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.
- The prose reviewer now holds prose to the negation rule: write `doesn't cost anything`, never `costs nothing`, after any verb or its preposition.
- `rule-hook` now checks files at `git commit`: each file that differs from HEAD or is untracked and not ignored, even one the commit leaves out. It holds each to `action-pin`, `image-pin`, `ignorefile-sorted` and `no-ai-attribution`, so a file a Bash command wrote is checked as an Edit or Write is. A `# rule-override` line in the file or the command overrides a breach.
- `chunk-pr merge` now refuses while a scoring run the plan calls is unrecorded on the branch, and `larv-review needs-scoring-run` calls one after a release is cut with none.
## 0.7.0
+5 -5
View File
@@ -8,16 +8,16 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
- **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; open `todo.md` only for what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; open `todo.md` only for what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs.
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the row and detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item.
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
- **Open each `todo.md` item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **Open each `todo.md` item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and doesn't say anything about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
## Shared goal
@@ -42,7 +42,7 @@ Everything written — chat, commit messages, comments, docs, code — is in **E
Write the thing, not an introduction to it. State what holds and stop; name a rejected alternative only where that stops a reader choosing it.
Write negations as people say them. BANNED: `stops nothing`, `changes nothing`, `reveals nothing`, `depends on no one`. GOOD: `doesn't stop anything`, `doesn't change anything`, `doesn't reveal anything`, `doesn't depend on anyone`.
Write negations as people say them: after a verb, or after its preposition, write `doesn't <verb> anything` or `anyone`, never `<verb> nothing` or `no one`. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`.
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
@@ -81,7 +81,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line, pin a container image to its full patch version and a GitHub Action to a semver tag.
## Naming files & folders
- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`.
+12 -16
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md`, `AGENTS.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
## Goals
@@ -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:
@@ -77,7 +79,9 @@ Move `~/.claude` to the newest release:
~/code/claude-config/bin/deploy-release
```
It refuses while a file `~/.claude` tracks has an uncommitted change, such as a hook Claude Code wrote into `settings.json`: merge that per `AGENTS.md` → "Working rules", then cut a release. A model picked with `/model` is no such change. It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `deploy-release --help` says what else it checks.
It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `deploy-release --help` says what else it checks.
It refuses while a file `~/.claude` tracks has an uncommitted change, such as a hook Claude Code wrote into `settings.json`; a model picked with `/model` is no such change. Read the change first, as in `git -C ~/.claude diff HEAD -- settings.json`. When it holds a credential, such as a token in `env` or `mcpServers`, move that out of the file: a token in `env` to the shell profile, a server in `mcpServers` to `~/.claude.json` with `claude mcp add --scope user`. Then carry the change into `~/code/claude-config` on a branch of its own, merge it through a PR, and cut a release.
## Release
@@ -101,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.
@@ -113,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`.
@@ -124,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.
@@ -142,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
---
+1 -1
View File
@@ -20,7 +20,7 @@ Run them in this order. A fix for a later check never breaks an earlier one.
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
Also report a list whose order carries no meaning and is not sorted (`~/.claude/principles/technical-principles.md` → "Deterministic order"), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
+5 -5
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,14 +11,14 @@ 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; delete nothing 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).
- *Absences:* what should be in this diff but isn't — un-updated callers (grep every changed or renamed public symbol), missing migration for a model change, missing authz on a new path, missing tests, un-regenerated OpenAPI/docs, stale README/AGENTS.md, and deletions the change obsoletes but didn't make.
- Repeat a targeted pass over the riskiest files; stop only when a pass yields nothing new.
- Repeat a targeted pass over the riskiest files; stop only when a pass doesn't find anything new.
## Review Focus Areas
+2 -2
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.
@@ -127,7 +127,7 @@ You review the seams that make verification possible and the strategy that uses
- **The pyramid follows the boundaries.** Coverage is end-to-end; the pyramid decides at which layer. Each suite earns its existence by naming the failure class only it can catch and its time and determinism budget — how fast it must run and how hermetic it must be. Core logic at the bottom, real-adapter integration at the seams (the actual DB, the actual queue) in the middle, a thin hermetic e2e layer (owned clock, seeded data, faked third parties) proving the wiring on a handful of critical journeys — an e2e failure is a deployment signal, not the primary bug detector. Anything testable at a cheaper layer moves down; an inverting pyramid signals boundaries the design failed to provide. A flaky test is a missing seam and a finding, never a retry policy. Prefer sociable tests with fakes over mock-heavy solitary ones — a suite that only passes by mocking internals is pinning structure, not behavior: the missing-seam smell again.
- **Concurrency is testable or it is untested.** Name every place two flows touch shared state, the invariant that serializes each (transaction, queue, idempotency key, ordering guarantee), and how a test forces the interleaving. A race reachable only by stress-looping is a missing seam — flag the seam as the finding; probabilistic runs are scheduled, never gating.
- **The external contract is executably pinned.** Contract tests fail when a published shape breaks — the lock on that one-way door. Price them like the versioning machinery (The External Contract): zero consumers outside your control, defer; many, mandatory.
- **Load targets come from Stage 0.** Load and performance tests verify the recorded scale numbers; no recorded scale, nothing to verify — fix Stage 0 first (a rig for unrecorded load is "Hunt the imagined requirement" wearing a QA hat). Data and traffic are production-shaped — a load run against a 1000-row database measures nothing. Runs are scheduled outside the merge gate (see Delivery); determinism here means a repeatable method against fixed thresholds, not identical latencies.
- **Load targets come from Stage 0.** Load and performance tests verify the recorded scale numbers; no recorded scale, nothing to verify — fix Stage 0 first (a rig for unrecorded load is "Hunt the imagined requirement" wearing a QA hat). Data and traffic are production-shaped — a load run against a 1000-row database doesn't measure anything. Runs are scheduled outside the merge gate (see Delivery); determinism here means a repeatable method against fixed thresholds, not identical latencies.
- **Post-deploy production suites are a designed capability.** Tagged, idempotent synthetic traffic against external surfaces only (API, UI), built once and run twice: post-deploy smoke and scheduled monitoring. It asserts liveness of the deployed surface, not logic — logic determinism lives in the pre-merge suites. Self-cleaning means expendable-by-design: a synthetic tenant or TTL-tagged data reaped out-of-band, never teardown-in-the-test, and never a delete endpoint added to the contract only for tests. Side effects are sandboxed by design — a synthetic checkout must never charge a real card — and the synthetic marking propagates through every downstream sink (telemetry, billing, analytics) so real signals stay uncontaminated; a tag that dies at the API edge is a missing seam.
## Delivery (the path to production is architecture)
+10 -10
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)
@@ -123,7 +123,7 @@ class Main(unittest.TestCase):
@staticmethod
def verdict(interrupt, evidence):
output = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "release_ready": False}
output = {"answer": "", "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "release_ready": False}
return {"type": "result", "structured_output": output}
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
@@ -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("[")
+35
View File
@@ -0,0 +1,35 @@
"""The todo.md items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as todo.md scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
import re
from claude_code.entries import AssistantTurn, Entry, Text
from failure import Failure
from release_plan.todo_table import items
from claude_code.transcript import plain
from loop_claude.verdicts import TakenIn
# The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it.
CHUNK_ITEMS = "Chunk items:"
# A line the worker opens with the label, after any `-` or `>` marker or a backtick; what follows names the items.
LINE = re.compile(rf"[\s>`-]*{re.escape(CHUNK_ITEMS)}(.*)")
# What the worker says of an item in parentheses, such as its L and E + I.
SAID_OF_AN_ITEM = re.compile(r"\([^)]*\)")
# An entry of the line, the text between commas or "and": an item's ID, after an optional "item" or "#".
ITEM_ID = re.compile(r"\s*(?:item\s+)?#?(\d+)", re.IGNORECASE)
def taken_in(entries: list[Entry], todo: str | Failure) -> TakenIn:
"""The items named, with the highest L and the highest E + I that todo.md, as read when the cycle started, gives any of them. An item todo.md doesn't hold, or a todo.md that can't be read, adds no level, so the route holds."""
ids = named(entries)
found = items(todo) if isinstance(todo, str) else todo
scored = [item for item in found if item.id in ids] if isinstance(found, list) else []
return TakenIn(ids, max((item.likelihood for item in scored), default=0), max((item.escape_and_impact for item in scored), default=0))
def named(entries: list[Entry]) -> tuple[int, ...]:
"""The IDs on the worker's latest Chunk items: line, each once, in its order; empty where it wrote none. Only the worker's own text counts: a loop-claude prompt quotes the line's example, and a tool call may write the label into a file."""
lines = [line for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text) for line in part.text.splitlines()]
for line in reversed(lines):
if found := LINE.match(plain(line)):
each = re.split(r",|\band\b", SAID_OF_AN_ITEM.sub("", found[1]))
return tuple(dict.fromkeys(int(item[1]) for named_item in each if (item := ITEM_ID.match(named_item))))
return ()
+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()
+36 -62
View File
@@ -9,9 +9,7 @@ from loop_effects.effects import Effects
from claude_code.entries import Entry, structured_output
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished, Verdict
from release_plan.todo_table import LEVELS
from model_routing.route import on_its_scale
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from claude_code.transcript import plain, verbatim
from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung
@@ -69,12 +67,6 @@ JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
@dataclasses.dataclass(frozen=True)
class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Lists the chunk's items in loop-inbox: running_loops.py.
items_taken_in: list[int] = dataclasses.field(metadata={"description": "The IDs of the todo.md items the worker states this chunk takes, the item the chunk was routed on included, never an item it only filed in todo.md for later; empty when it states none."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
@@ -88,8 +80,7 @@ class Reply:
REPLY_TYPES = typing.get_type_hints(Reply)
JSON_TYPES: dict[object, dict[str, typing.Any]] = {bool: {"type": "boolean"}, int: {"type": "integer"}, str: {"type": "string"}, list[int]: {"type": "array", "items": {"type": "integer"}}}
HIGHEST_L = LEVELS["L"]
JSON_TYPES: dict[object, dict[str, typing.Any]] = {bool: {"type": "boolean"}, int: {"type": "integer"}, str: {"type": "string"}}
JUDGE_SCHEMA = {
"properties": {field.name: {**field.metadata, **JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
"required": list(REPLY_TYPES),
@@ -128,43 +119,25 @@ def verdict_from(output: object) -> Verdict | Failure:
return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items():
if not fits(output.get(name), kind):
return Failure(f"the judge's reply has no {name} of type {type_name(JSON_TYPES[kind])}")
taken_in = taken_in_from(output)
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]['type']}")
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], taken_in=taken_in, release_ready=output["release_ready"], answered_before=output["answered_before"], left_open=output["left_open"])
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], release_ready=output["release_ready"], answered_before=output["answered_before"], left_open=output["left_open"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], taken_in=taken_in)
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"])
if output["finished"]:
return Finished(output["evidence"])
return Unfinished(output["evidence"], escalation=output["escalation"], taken_in=taken_in)
def type_name(schema: dict[str, typing.Any]) -> str:
return f"array of {schema['items']['type']}s" if schema["type"] == "array" else schema["type"]
return Unfinished(output["evidence"], escalation=output["escalation"])
def fits(value: object, kind: object) -> bool:
"""Whether value, read from the judge's JSON, is of kind. type(), not isinstance(): JSON true is no integer."""
if typing.get_origin(kind) is list:
return type(value) is list and all(fits(each, typing.get_args(kind)[0]) for each in value)
return type(value) is kind
def taken_in_from(output: dict) -> TakenIn:
"""The reply's readings of the items taken in. An ID below 1 is left out, and an L or E + I off its scale counts as 0. Neither fails the reply: three failures would stop an unattended loop, and holding the rung is safe."""
likelihood = output["highest_likelihood_taken_in"]
escape_and_impact = output["highest_escape_and_impact_taken_in"]
return TakenIn(
tuple(item for item in output["items_taken_in"] if item > 0),
likelihood if 0 <= likelihood <= HIGHEST_L else 0,
escape_and_impact if on_its_scale(escape_and_impact) else 0,
)
def judge(root: str, brief: Brief, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
return retried("judge", lambda: judge_once(root, brief, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
@@ -211,13 +184,13 @@ def cost_of(reply: dict) -> float:
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
"""The verdict with each of its quotes checked against the text it must appear in, as written:
| Quote | Must be in | Where it isn't |
|---|---|---|
| the evidence | grounds.shown, the evidence's fragments in order | a Failure: run_judge rejects the reply, and judge retries it |
| an interrupt's answered_before | grounds.shown | the interrupt stands, as if no earlier answer was found |
| its left_open | answered_before and the question | the interrupt becomes an Unfinished that quotes answered_before back to the worker |
| a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried |
| the escalation | grounds.shown and grounds.after_mark | the escalation is dropped, so the worker's rung holds, as escalation_mark.checked says |
| Quote | Must be in | Where it isn't | Checked by |
|---|---|---|---|
| the evidence | grounds.shown, the evidence's fragments in order | a Failure: run_judge rejects the reply, and judge retries it | grounded |
| an interrupt's answered_before | grounds.shown | the interrupt stands, as if no earlier answer was found | re_ask_checked |
| its left_open | answered_before and the question | the interrupt becomes an Unfinished that quotes answered_before back to the worker | re_ask_checked |
| a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried | answer_checked |
| the escalation | grounds.shown and grounds.after_mark | the escalation is dropped, so the worker's rung holds | escalation_mark.checked |
Only a misquoted evidence fails. A Failure for any other would exit an unattended loop, so each changes the verdict instead.
"""
@@ -228,13 +201,18 @@ def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
return escalation_mark.checked(verdict, after=grounds.after_mark, shown=grounds.shown)
def re_ask_checked(verdict: Verdict, shown: str) -> Verdict:
"""The verdict, or an Unfinished quoting the human's earlier answer back to the worker, where it is an Interrupt that re-asks what that answer settles: its left_open isn't in both the answer and the question."""
if not isinstance(verdict, Interrupt) or not verbatim(verdict.answered_before, shown):
return verdict
if verbatim(verdict.left_open, verdict.answered_before) and verbatim(verdict.left_open, verdict.question):
return verdict
return Unfinished(verdict.answered_before, escalation=verdict.escalation, taken_in=verdict.taken_in)
def grounded(evidence: str, rendered_transcript: str) -> bool:
"""Whether the transcript holds the evidence word for word, once emphasis marks are stripped and whitespace is reflowed in both. The judge joins passages with an ellipsis though told to quote one, so each fragment between ellipses must come after the one before it."""
transcript = plain(rendered_transcript)
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
after = 0
for fragment in fragments:
at = transcript.find(fragment, after)
if at < 0:
return False
after = at + len(fragment)
return bool(fragments)
def misquoted_evidence(verdict: Verdict) -> Failure:
@@ -242,10 +220,19 @@ def misquoted_evidence(verdict: Verdict) -> Failure:
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript{asked}")
def re_ask_checked(verdict: Verdict, shown: str) -> Verdict:
"""The verdict, or an Unfinished quoting the human's earlier answer back to the worker, where it is an Interrupt that re-asks what that answer settles: its left_open isn't in both the answer and the question."""
if not isinstance(verdict, Interrupt) or not verbatim(verdict.answered_before, shown):
return verdict
if verbatim(verdict.left_open, verdict.answered_before) and verbatim(verdict.left_open, verdict.question):
return verdict
return Unfinished(verdict.answered_before, escalation=verdict.escalation)
def answer_checked(verdict: Verdict, quotable: str) -> Verdict:
"""The verdict; where it is a quoted answer that README.md and the records don't hold, an Interrupt on the same question instead."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
return Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, taken_in=verdict.taken_in)
return Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation)
return verdict
@@ -266,17 +253,4 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
after_mark=escalation_mark.after_mark(brief.entries, brief.escalated_at),
quotable=f"{brief.premises}\n\n{brief.records}",
)
return f"{head}{shown}\n\n{JUDGE_RULES}", grounds
def grounded(evidence: str, rendered_transcript: str) -> bool:
"""Whether the transcript holds the evidence word for word, once emphasis marks are stripped and whitespace is reflowed in both. The judge joins passages with an ellipsis though told to quote one, so each fragment between ellipses must come after the one before it."""
transcript = plain(rendered_transcript)
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
after = 0
for fragment in fragments:
at = transcript.find(fragment, after)
if at < 0:
return False
after = at + len(fragment)
return bool(fragments)
return f"{head}{shown}\n\n{JUDGE_RULES}", grounds
+10 -8
View File
@@ -1,5 +1,6 @@
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
from model_routing.review_choice import chosen, ReviewChoice
from loop_claude.cycle.chunk_items import CHUNK_ITEMS
from model_routing.ladder import climbed, LADDER, position, Rung
from model_routing.route import ESCALATION_MARKER, Route
from loop_claude.routing import escalation_rungs
@@ -21,6 +22,8 @@ THE_SECURITY_PASS = "the security pass's subagent"
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).
NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
@@ -30,13 +33,12 @@ def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: s
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
def routed_by(route: Route, project: Rung | None) -> str:
return " ".join((
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
f"Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.",
*rung_sentences(route, project),
))
@@ -86,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]] = {}
@@ -97,9 +99,9 @@ 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 the judge reports a taken-in item's E + I only as the cycle ends, and loop-claude routes on it from the next cycle. None where no higher E + I picks a higher rung.
"""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 []
@@ -120,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 []
@@ -142,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 []
@@ -160,7 +162,7 @@ def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
on = f" loop-claude runs you on {route.rung}." if project else ""
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}.{on}{rungs_held(route, project)}"
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}. {NAME_THE_ITEMS}{on}{rungs_held(route, project)}"
def rung_sentences(route: Route, project: Rung | None) -> list[str]:
+7 -2
View File
@@ -6,6 +6,7 @@ from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, Hu
from transcript_archive.write import archive
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
from loop_claude.cycle.judge import Brief, judge, Rejected
from loop_claude.cycle import chunk_items
from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_effects.effects import Effects, say
from failure import Failure
@@ -42,9 +43,11 @@ class Cycle:
root: str
route: Route
session: Session
# Lists in loop-inbox the items the chunk takes, given the IDs an unfinished ruling found taken in.
# Lists in loop-inbox the items the chunk takes, given the IDs on the worker's latest `Chunk items:` line.
show_taken_in: typing.Callable[[tuple[int, ...]], None]
task: str
# todo.md on the default branch as the cycle starts, which scores the items the worker names.
todo: str | Failure
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
@@ -144,13 +147,15 @@ def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step
def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop:
"""The judge's ruling. An interrupt or a quoted answer is archived as it is ruled, on the route the worker ran on until then, and then any step-up it makes, so the figures charge each stretch of work to its own rung."""
"""The judge's ruling. Unless it is Finished, code stamps it with the items the worker names on its latest `Chunk items:` line. An interrupt or a quoted answer is archived as it is ruled, on the route the worker ran on until then, and then any step-up it makes, so the figures charge each stretch of work to its own rung."""
entries = read_transcript(transcript_path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, Brief(cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at), judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
if isinstance(verdict, Stop):
return verdict
if not isinstance(verdict, Finished):
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
if not isinstance(verdict, Interrupt | QuotedAnswer):
return Ruled(verdict)
stepped = ruling_step_up(cycle, verdict)
+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)
+8 -6
View File
@@ -7,7 +7,7 @@ from git_cli.git_repo import default_ref, file_at
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.routing import first_route, kept, routed_item
from release_plan.todo_table import Item
from release_plan.todo_table import Item, items
from transcript_archive.read import latest_worker
from loop_claude.loop.this_loop import Loop
from loop_claude.cycle import prompts
@@ -20,16 +20,18 @@ from loop_state.running_loops import taken_items
ORIGIN_TIMEOUT = 60
def shown_items(loop: Loop, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
"""A function that lists in loop-inbox the items a chunk takes, given the IDs the judge found taken in. routed is the item the chunk was routed on, 0 for none. shown_items reads todo.md once, as the cycle starts, and the function shows those taglines."""
todo = fetched_todo(loop)
def shown_items(loop: Loop, todo: str | Failure, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
"""A function that lists in loop-inbox the items a chunk takes, given the IDs the worker names, with their taglines in todo, as fetched_todo read it as the cycle started. routed is the item the chunk was routed on, 0 for none."""
return lambda taken_in: loop.listed.show(taken_items(todo, routed, taken_in))
def fetched_todo(loop: Loop) -> str | Failure:
"""todo.md on the default branch, as last fetched. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which the listing doesn't need."""
"""todo.md on the default branch, as last fetched, which lists and scores the items a chunk takes. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which listing and scoring the items don't need. Where it can't be read or scored, it says why."""
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", loop.root, loop.effects.git)
todo = ref if isinstance(ref, Failure) else file_at(ref, "todo.md", loop.root, loop.effects.git)
if isinstance(scored := items(todo) if isinstance(todo, str) else todo, Failure):
say(f"the items the worker names lift no rung: {scored.reason}", loop.effects)
return todo
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
+1 -1
View File
@@ -39,7 +39,7 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route, its run of unfinished verdicts and the items it took in. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; the evidence the judge gave for the verdict and the items it found taken in; and counts the verdict."""
"""The loop run the next cycle starts from. A finished chunk drops its route, its run of unfinished verdicts and the items it took in. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; the evidence the judge gave for the verdict, and the items the worker names on its latest `Chunk items:` line; and counts the verdict."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0, items_taken_in=())
+11 -3
View File
@@ -3,7 +3,7 @@ import pathlib
import typing
from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.chunk_start import archived_route, chunk_start, routed, shown_items
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed, shown_items
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.loop.close import closed_cycle
@@ -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
@@ -80,9 +87,10 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
show_taken_in = shown_items(loop, route.item)
todo = fetched_todo(loop)
show_taken_in = shown_items(loop, todo, route.item)
show_taken_in(loop_run.items_taken_in)
return Cycle(effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)
return Cycle(effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
+3 -1
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
@@ -63,7 +65,7 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) ->
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
if unstarted:
return Stop(1, f"could not start claude for the routing calls in {loop.paths.config_clone}, the setup's development clone: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through docs/decisions.md → "Working rules", so it is not asked twice.
if unmarked := state.mark_raised(root, new, utc(loop.effects.now())):
say(f"routing figures: {unmarked.reason}", loop.effects)
return None
+7 -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.
@@ -67,9 +70,10 @@ the worker and the session /talk opens; with both set, nothing is asked.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the
worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds
in the transcript an escalation trigger that fired and the worker asked for a higher rung. The
rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
+32 -28
View File
@@ -137,6 +137,9 @@ PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 4 | 0.1.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n"
# Item 4's L of 2 steps one rung down.
CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |")
# Item 9 follows CHEAP's item 4, and a worker routed by item 4 may take it in: at L 4 it picks a higher rung for the worker, and at E + I 6 for the judge and the reviewers. At E + I 3, or at L 2, it picks the rung item 4 picks.
TAKEN_IN_AT_L_4 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 4 | 1 | 2 | 5 | 2 | 1 by 9 | 20 |\n"
TAKEN_IN_AT_E_PLUS_I_6 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 2 | 3 | 3 | 6 | 2 | 1 by 9 | 20 |\n"
# Waits for the interrupt's prompt before typing the answer, since loop-claude drops what was typed before it.
@@ -147,8 +150,8 @@ def worker(**step):
return {"role": "worker", **step}
def judge(interrupt=False, finished=False, evidence="working", question="", items_taken_in=(), highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
verdict = {"items_taken_in": list(items_taken_in), "answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready}
def judge(interrupt=False, finished=False, evidence="working", question="", escalation="", release_ready=False, **step):
verdict = {"answer": "", "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready}
return {"role": "judge", "verdict": verdict, **step}
@@ -427,11 +430,11 @@ class Cycles(unittest.TestCase):
def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP)
checkout.commit_plan(TAKEN_IN_AT_L_4)
run = checkout.run([
worker(say="one"), judge(evidence="one"),
worker(say="two"), judge(evidence="two"),
worker(say="three"), judge(evidence="three", highest_likelihood_taken_in=4),
worker(say="three\nChunk items: 4 (L 2, E + I 3), 9 (L 4, E + I 5)"), judge(evidence="three"),
worker(say="four"), judge(finished=True, evidence="four"),
worker(say="next chunk"),
])
@@ -441,14 +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. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 4.", argument(workers[0], "-p"))
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)
@@ -474,11 +478,11 @@ class Cycles(unittest.TestCase):
self.assertIn("item 6, L 4, E + I 5", prompt)
self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir())
def test_lists_itself_in_loop_inbox_with_its_routed_item_then_those_the_judge_finds_taken_in_until_the_chunk_finishes(self):
def test_lists_itself_in_loop_inbox_with_its_routed_item_then_those_the_worker_names_on_its_chunk_items_line_until_the_chunk_finishes(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(TODO)
run = checkout.run([worker(), judge(items_taken_in=[7, 4]), worker(), judge(finished=True), worker()])
run = checkout.run([worker(say="working\nChunk items: 7, 4"), judge(), worker(), judge(finished=True), worker()])
self.assertEqual(run.code, 130)
routed, taken_in = {"id": 4, "tagline": "Do it."}, {"id": 7, "tagline": ""}
self.assertEqual([call["running"] for call in run.calls], [[[routed]], [[routed]], [[routed, taken_in]], [[routed, taken_in]], [[routed]], [[routed]]])
@@ -497,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)
@@ -518,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)
@@ -540,20 +544,20 @@ class Cycles(unittest.TestCase):
def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP)
checkout.commit_plan(TAKEN_IN_AT_E_PLUS_I_6)
run = checkout.run([
worker(say="one"), judge(evidence="one", highest_escape_and_impact_taken_in=6),
worker(say="one\nChunk items: 4, 9"), judge(evidence="one"),
worker(say="two"), judge(finished=True, evidence="two"),
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)
@@ -561,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)
@@ -698,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)
+239 -151
View File
@@ -5,6 +5,7 @@ import io
import json
import os
import pathlib
import re
import shutil
import stat
import subprocess
@@ -20,6 +21,7 @@ from routing_figures import archive, state
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from routing_figures.calls import Call
from loop_claude.project import checkout, model_choice, records
from loop_claude.cycle import chunk_items
from loop_claude.loop import chunk_start, close
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed
from release_plan.release_standing import DefaultPlan, LastCut
@@ -90,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)
@@ -106,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),
@@ -121,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)
@@ -161,8 +171,8 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, items_taken_in=(), cost=None):
reply = {"items_taken_in": list(items_taken_in), "answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready}
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None):
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready}
return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})}))
@@ -238,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)),
@@ -268,7 +278,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", unfinished_evidence=unfinished_evidence)
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -284,16 +294,16 @@ class Cycles(unittest.TestCase):
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"])
self.assertIsNone(session.transcript_file(self.session))
def test_shows_the_items_each_ruling_finds_the_chunk_takes_as_the_judge_gave_them(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker], claude=[judged("unfinished", items_taken_in=(14, 3))])
def test_shows_the_items_each_ruling_finds_the_worker_names_on_its_chunk_items_line(self):
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 14 (L 2, E + I 3), 3 (L 1, E + I 2)")
fake = FakeEffects(streams=[worker], claude=[judged("unfinished")])
shown = []
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
self.assertEqual(shown, [(14, 3)])
def test_shows_no_items_for_a_finished_chunk(self):
worker = Worker(self.paths.claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker], claude=[judged("finished", items_taken_in=(3,))])
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 3")
fake = FakeEffects(streams=[worker], claude=[judged("finished")])
shown = []
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
self.assertEqual(shown, [])
@@ -493,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)]
@@ -502,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))):
@@ -544,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):
@@ -725,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"))
@@ -962,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):
@@ -1009,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):
@@ -1039,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))
@@ -1047,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)
@@ -1062,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)
@@ -1104,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)
@@ -1181,12 +1211,20 @@ class RouteSources(unittest.TestCase):
self.assertIsNone(chunk_start.plan_item(plan, FakeEffects().effects()))
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
fetched = ["origin\n", "origin/main\n", "", "todo.md\n"]
for git, said in ((fetched + [TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")], "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), ([Failure("no git")], "the items the worker names lift no rung: no git\n"), (fetched + [TODO], "")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_todo(a_loop(FakeEffects(git=git).effects()))
self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "")
def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self):
with tempfile.TemporaryDirectory() as home:
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)
@@ -1219,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,))
@@ -1228,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):
@@ -1238,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):
@@ -1252,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))
@@ -1340,9 +1378,9 @@ class WorkerArgs(unittest.TestCase):
def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self):
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed)
self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed)
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)
self.assertIn(f"before creating a new one. {prompts.READING_RULE}\n\n{self.FACTS}\n\nThe chunk's", unrouted)
self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted)
self.assertNotIn("loop-claude runs you on", unrouted)
def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self):
@@ -1372,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"whether or not it is item 3. 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"whether or not it is item 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"whether or not it is item 3. 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."
self.assertIn(f"whether or not it is item 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))
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 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}. 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"whether or not it is item 3.{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("whether or not it is item 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}\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):
@@ -1566,65 +1604,75 @@ class Grounded(unittest.TestCase):
self.assertTrue(judge.grounded("a ... b ... c", "x a b a c"))
# Item 297 scores the higher L, item 298 the higher E + I.
SCORED = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 297 | 0.8.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n| 298 | 0.8.0 | | **Do more.** | 3 | 3 | 4 | 8 | 2 | 1 by 9 | 20 |\n"
def said(*texts):
return entries.AssistantTurn(parts=tuple(entries.Text(text) for text in texts))
class ChunkItems(unittest.TestCase):
def test_names_the_items_on_the_workers_latest_chunk_items_line(self):
earlier = said("Chunk items: 297 (L 3, E + I 5)")
latest = said("Starting.\n**Chunk items:** 297 (L 4, E + I 5), item 298 (L 3, E + I 7), #12, 298\nOn to the tests.")
self.assertEqual(chunk_items.named([earlier, latest]), (297, 298, 12))
self.assertEqual(chunk_items.named([latest, earlier]), (297,))
self.assertEqual(chunk_items.named([earlier, said("Chunk items: none")]), ())
self.assertEqual(chunk_items.named([said("Chunk items: 297 and 298 (L 3, E + I 7)")]), (297, 298))
def test_reads_the_example_line_the_prompt_gives_the_worker(self):
example = re.search(r"`(Chunk items:[^`]*)`", prompts.NAME_THE_ITEMS)[1]
self.assertEqual(chunk_items.named([said(example)]), (297, 298))
def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self):
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), None))
def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self):
prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)")
written = entries.AssistantTurn(parts=(entries.ToolCall("t", "Write", {"content": "Chunk items: 9"}),))
mentioned = said("Once I know them, I write `Chunk items: 5`.")
self.assertEqual(chunk_items.named([prompt, written, mentioned]), ())
def test_takes_the_highest_l_and_e_plus_i_todo_md_scores_among_the_named_items(self):
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297 (L 1, E + I 2), 298, 400")], SCORED), TakenIn((297, 298, 400), 4, 7))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 400")], SCORED), TakenIn((400,)))
self.assertEqual(chunk_items.taken_in([], SCORED), TakenIn())
def test_names_the_items_at_no_level_where_todo_md_cannot_be_read(self):
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], Failure("no todo.md")), TakenIn((297,)))
self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], "no items table"), TakenIn((297,)))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answered_before": "", "left_open": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Finished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "release_ready": False}), Unfinished("e"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge interrupted without a question"))
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
def test_carries_the_earlier_answer_an_interrupt_names(self):
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?"}
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?"}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more"))
self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e"))
def test_takes_the_highest_l_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"items_taken_in": [], "answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Unfinished("e", taken_in=TakenIn(highest_likelihood=4)))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": True}), Failure("the judge's reply has no highest_likelihood_taken_in of type integer"))
for highest_likelihood_taken_in in (5, 13, -1):
with self.subTest(highest_likelihood_taken_in=highest_likelihood_taken_in):
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": highest_likelihood_taken_in}), Unfinished("e"))
def test_takes_the_highest_e_plus_i_taken_in_on_its_scale_and_counts_any_other_as_none(self):
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", taken_in=TakenIn(highest_escape_and_impact=6)))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", taken_in=TakenIn(highest_escape_and_impact=2)))
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": False}), Failure("the judge's reply has no highest_escape_and_impact_taken_in of type integer"))
for escape_and_impact in (1, 9, -1):
with self.subTest(escape_and_impact=escape_and_impact):
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": escape_and_impact}), Unfinished("e"))
def test_takes_the_items_taken_in_as_the_judge_gives_them_leaving_out_ids_below_1(self):
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from({**reply, "items_taken_in": [12, 14, 12]}), Unfinished("e", taken_in=TakenIn((12, 14, 12))))
self.assertEqual(verdict_from({**reply, "items_taken_in": [7, 0]}), Unfinished("e", taken_in=TakenIn((7,))))
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "interrupt": True, "question": "Which one?"}), Interrupt("e", "Which one?", taken_in=TakenIn((3,))))
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "answer": "A.", "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.", taken_in=TakenIn((3,))))
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "finished": True}), Finished("e"))
self.assertEqual(verdict_from({**reply, "items_taken_in": "3"}), Failure("the judge's reply has no items_taken_in of type array of integers"))
self.assertEqual(verdict_from({**reply, "items_taken_in": ["3"]}), Failure("the judge's reply has no items_taken_in of type array of integers"))
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
def test_takes_an_escalation_quote_on_an_interrupt(self):
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", TakenIn(highest_likelihood=4)))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
shown = "The agent: round 2: 🔴. Which one?"
@@ -1639,8 +1687,8 @@ class Verdict(unittest.TestCase):
asking = "Grant a third round? Your answer left open: a 🔴 survives it"
kept = Interrupt("[step] Round 2", asking, answered_before=answer, left_open="a 🔴 survives it")
self.assertEqual(judge.quotes_checked(kept, grounds), kept)
re_asked = Interrupt("[step] Round 2", "Grant a third round?", "Round 2: a 🔴", TakenIn((3,)), answered_before=answer, left_open="a 🔴 survives it")
self.assertEqual(judge.quotes_checked(re_asked, grounds), Unfinished(answer, "Round 2: a 🔴", TakenIn((3,))))
re_asked = Interrupt("[step] Round 2", "Grant a third round?", "Round 2: a 🔴", answered_before=answer, left_open="a 🔴 survives it")
self.assertEqual(judge.quotes_checked(re_asked, grounds), Unfinished(answer, "Round 2: a 🔴"))
self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open=""), grounds), Unfinished(answer))
self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open="a 🔴 survived"), grounds), Unfinished(answer))
invented = dataclasses.replace(re_asked, answered_before="Grant two more rounds.")
@@ -1648,10 +1696,9 @@ class Verdict(unittest.TestCase):
unnamed = Interrupt("[step] Round 2", "Grant a third round?")
self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed)
def test_takes_an_escalation_quote_and_the_highest_l_taken_in_on_a_quoted_answer(self):
reply = {"items_taken_in": [], "answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", TakenIn(highest_likelihood=4)))
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
def test_takes_an_escalation_quote_on_a_quoted_answer(self):
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
shown = "The agent: round 2: 🔴. Which one?"
@@ -1659,8 +1706,7 @@ class Verdict(unittest.TestCase):
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A."))
def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self):
self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there", taken_in=TakenIn((3,))), judge.Grounds("shown", "shown", "A.")), Interrupt("s", "q", taken_in=TakenIn((3,))))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", TakenIn(highest_likelihood=4)), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4)))
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴"), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴"))
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("s", "q"))
@@ -1694,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))
@@ -1710,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))
@@ -1728,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)
@@ -1769,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], [])
+2 -2
View File
@@ -1,10 +1,10 @@
"""The verdicts cycle.judge.verdict_from builds from the judge's reply. They sit outside cycle/, since routing reads them and cycle imports routing."""
"""The verdicts cycle.judge.verdict_from builds from the judge's reply; cycle.run.rule then stamps every verdict but Finished with the items the chunk takes. They sit outside cycle/, since routing reads them and cycle imports routing."""
import dataclasses
@dataclasses.dataclass(frozen=True)
class TakenIn:
"""What the judge read in the transcript about the todo.md items the worker took into the chunk, the item the chunk was routed on included."""
"""The todo.md items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
# Their IDs; loop-inbox lists them.
items: tuple[int, ...] = ()
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
+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,
+2 -2
View File
@@ -2,8 +2,8 @@
A running loop holds its session's lock (session_lock.py) in Paths.waiting for its whole run. Beside the lock it keeps
<session>.running, which holds the loop's checkout and each item its chunk takes, by ID and by its tagline on the default
branch as last fetched. The items are the one the chunk was routed on, then those the judge's latest ruling found the
worker took in, each listed once. loop-inbox lists a loop, and its question (waiting/), only while the loop holds its
branch as last fetched. The items are the one the chunk was routed on, then those the worker names on its latest
`Chunk items:` line, each listed once. loop-inbox lists a loop, and its question (waiting/), only while the loop holds its
lock. So a killed loop drops off the list, though its files stay until loop-inbox removes them: <session>.running
through drop_ended_loops here, and the question through waiting.listing.drop_ended.
"""
+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}
+2 -2
View File
@@ -43,7 +43,7 @@ class Route:
likelihood: int = 0
escape_and_impact: int = 0
unfinished: int = 0
# The highest E + I the judge saw the worker take in, kept only where it picks a higher review step than the item's; 0 otherwise.
# The highest E + I among the items the worker names on its `Chunk items:` line, kept only where it picks a higher review step than the item's; 0 otherwise.
escape_and_impact_taken_in: int = 0
# The escalation mark, as loop_claude/escalation_mark.py says: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any.
escalated_at: int = 0
@@ -59,7 +59,7 @@ class Route:
return levels_fit(fields.get("item", 0), fields.get("likelihood", 0), fields.get("escape_and_impact", 0), fields.get("escape_and_impact_taken_in", 0))
def taking_in(self, escape_and_impact: int) -> "Route":
"""The route after the judge saw the worker take in an item of this E + I, 0 for none: it keeps the E + I only where REVIEW_STEPS steps it further than reviewed_on, so the archive records a step-up only where REVIEW_STEPS steps the review floor further."""
"""The route after the worker takes in an item of this E + I, 0 for none: it keeps the E + I only where REVIEW_STEPS steps it further than reviewed_on, so the archive records a step-up only where REVIEW_STEPS steps the review floor further."""
return dataclasses.replace(self, escape_and_impact_taken_in=escape_and_impact) if REVIEW_STEPS.get(escape_and_impact, 0) > REVIEW_STEPS.get(self.reviewed_on(), 0) else self
def reviewed_on(self) -> int:
+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)
+8 -4
View File
@@ -50,10 +50,14 @@ class Citations(unittest.TestCase):
def test_every_folder_the_judge_reads_rules_from_exists(self):
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
def test_agents_md_lists_exactly_the_decision_titles(self):
listed = (ROOT / "AGENTS.md").read_text().split("Decisions live in `docs/decisions.md`:\n\n")[1].split("\n\n")[0]
# The two files order the titles differently, so they are compared sorted.
self.assertEqual(sorted(LISTED_TITLE.findall(listed)), sorted(DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text())))
def test_every_decision_title_the_log_lists_at_its_head_is_a_title_in_it(self):
log = (ROOT / "docs/decisions.md").read_text()
listed = LISTED_TITLE.findall(log.split("# Decisions no project principle covers\n\n")[1].split("\n\n")[0])
self.assertTrue(listed)
self.assertEqual([title for title in listed if title not in set(DECISION_TITLE.findall(log))], [])
def test_the_repo_keeps_no_agents_md_since_claude_code_would_load_the_releases_copy_into_every_project(self):
self.assertFalse((ROOT / "AGENTS.md").exists())
def test_every_todo_citation_of_a_decision_names_a_title(self):
titles = DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text())
+5 -4
View File
@@ -9,7 +9,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks import ROOT
TRIALS = ROOT / "reviewer-merge-trials"
# The trials folders whose scripts import from bin/.
TRIALS = [ROOT / "judge-field-trials", ROOT / "reviewer-merge-trials"]
def bin_imports(source: str) -> list[tuple[str, str | None]]:
@@ -39,11 +40,11 @@ def in_bin(module: str) -> bool:
class TrialsImports(unittest.TestCase):
"""docs/decisions.md says to rerun the trials' scripts when a new model joins the ladder or a reviewer's definition changes, so a refactor of bin/ must not break what they import."""
"""docs/decisions.md says when to rerun each trials folder's scripts, so a refactor of bin/ must not break what they import."""
def test_each_name_a_trials_script_imports_from_bin_exists(self):
scripts = sorted(TRIALS.glob("*.py"))
self.assertTrue(scripts)
scripts = sorted(script for folder in TRIALS for script in folder.glob("*.py"))
self.assertTrue(all(any(folder.glob("*.py")) for folder in TRIALS))
for script in scripts:
for module, name in bin_imports(script.read_text(encoding="utf-8")):
with self.subTest(script=script.name, module=module, name=name):
+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),
+1 -1
View File
@@ -1,6 +1,6 @@
"""What loop-claude keeps at the archive's root between measurements: docs/decisions.md → `routing: loop-claude measures review rounds…`.
STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as AGENTS.md says, and loop-claude reads the resets from there."""
STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as docs/decisions.md → "Working rules" says, and loop-claude reads the resets from there."""
import dataclasses
import json
import pathlib
+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"))]
+60
View File
@@ -0,0 +1,60 @@
import dataclasses
import posixpath
from rule_hook.rules import Breach, file_breaches
from failure import Failure
from git_cli import git_repo
from rule_hook.git import guarded_git
from rule_hook.file_text import read
# settings.json gives rule-hook 30 seconds; a file past this size is not source code, and reading it would use them up.
MAX_BYTES = 1_000_000
def committed_file_breaches(directory: str) -> list[Breach]:
"""The breaches of file_breaches in the files a commit in directory's checkout would commit.
A file a Bash command wrote reaches no Edit or Write check, so the commit checks the file instead. The files are those that differ from HEAD in the index or the work tree, or that are untracked and not ignored: the hook runs before a `git add` earlier in the same command, so the index alone would miss those files. A tracked file is checked as the index holds it and as the work tree does, since the commit takes the index. A deleted file, or one that is not UTF-8 text, has no added text. A breach carries the lines its file adds, so a marker among them overrides it, as in a Write; a marker the file already held doesn't."""
top = guarded_git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure):
return []
tracked = tracked_names(top)
untracked = guarded_git(top, "ls-files", "-z", "--others", "--exclude-standard")
breaches: list[Breach] = []
for name in sorted(tracked | (set() if isinstance(untracked, Failure) else names_in(untracked))):
path = posixpath.join(top, name)
# An untracked file has neither a version in HEAD nor one in the index. A tracked file costs two git calls, about 4 ms each: a commit of 3000 changed files uses 13 of the hook's 30 seconds.
before = blob(top, "HEAD", name) if name in tracked else ""
for after in dict.fromkeys([read(path) if size(path) <= MAX_BYTES else "", blob(top, "", name) if name in tracked else ""]):
known = set(before.splitlines())
added = "\n".join(line for line in after.splitlines() if line not in known)
breaches += [dataclasses.replace(breach, marked=added) for breach in file_breaches(path, before, added, after)]
# The index copy and the work-tree copy of a file can breach the same way; the first stands.
return list({(breach.rule, breach.detail): breach for breach in reversed(breaches)}.values())[::-1]
def tracked_names(top: str) -> set[str]:
"""The tracked files that differ from HEAD in the index or the work tree, deleted ones left out. It lists with diff-index, which neither hashes the work tree nor enters a submodule: either would run a clean filter that the checkout's config names, before the call is allowed."""
listings = [guarded_git(top, "diff-index", "-z", "--name-only", "--no-renames", "--diff-filter=d", "--ignore-submodules", *cached, "HEAD") for cached in ([], ["--cached"])]
if any(isinstance(listing, Failure) for listing in listings):
# A checkout with no commit has no HEAD: every file in its index is new.
listing = guarded_git(top, "ls-files", "-z")
return set() if isinstance(listing, Failure) else names_in(listing)
return {name for listing in listings if not isinstance(listing, Failure) for name in names_in(listing)}
def names_in(listing: str) -> set[str]:
return {name for name in listing.split("\0") if name}
def blob(top: str, commit: str, name: str) -> str:
"""name's text in the commit, or in the index where commit is empty; "" where there is none."""
shown = git_repo.git("show", f"{commit}:{name}", cwd=top, guarded=True)
return "" if isinstance(shown, Failure) or len(shown) > MAX_BYTES else shown
def size(path: str) -> int:
try:
return posixpath.getsize(path)
except OSError:
return 0
+12
View File
@@ -0,0 +1,12 @@
import os
import stat
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
+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"])
+11 -14
View File
@@ -8,14 +8,18 @@ subagent. The rules:
{rules}
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
A call overrides a rule with `# rule-override <rule>: <reason>`:
- anywhere in a Bash command, such as a trailing comment
- in a file, as a comment line in the text the edit writes
- in Markdown, as `<!-- rule-override <rule>: <reason> -->`
A file a Bash command writes, such as through `cat > Dockerfile`, is checked when a `git commit` runs, not when written.
The commit checks every file that differs from HEAD, in the index or the work tree, and every untracked file that is
not ignored, even one the commit leaves out. It holds each to the rules that name a file (action-pin, image-pin,
ignorefile-sorted, no-ai-attribution), judged on the lines the file adds. A marker among those lines, or in the commit
command, overrides the file's breach.
Each override that let a call through is appended to rule-overrides.tsv in the git directory of
the checkout it touched: UTC time, branch, the commit checked out, rule, reason, and the file
written or the command's first line. An override outside any git checkout is not logged.
@@ -31,7 +35,6 @@ cannot read.
"""
import json
import os
import stat
import sys
import time
import typing
@@ -39,8 +42,10 @@ import typing
from rule_hook.call import applied, Call, FILE_TOOLS, parsed_call, text
from rule_hook.rules import Breach, check, Checked, command_breaches, file_breaches, rules_help
from git_cli.git_command import commits
from rule_hook.committed_files import committed_file_breaches
from failure import Failure
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
from rule_hook.file_text import read
from rule_hook.repeat_read import read_breaches
from rule_hook.reviewer_report import report_breaches
from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches
@@ -110,14 +115,6 @@ def answer(checked: Checked, what: str, now: float) -> int:
def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
simples = simple_commands(command, cwd, home)
return command_breaches(command, simples, home) + [breach for commit in commits(simples, home) for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)]
def read(path: str) -> str:
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
try:
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
except (OSError, UnicodeDecodeError):
return ""
found = commits(simples, home)
in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)]
return command_breaches(command, simples, home) + [breach for commit in found for breach in round_cap_breaches(commit) + todo_breaches(commit.directory)] + in_files
+7 -3
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",
@@ -104,6 +104,8 @@ class Breach:
detail: str
# The checkout whose log records an override of this breach.
directory: str
# The lines a commit adds to the breach's file: its markers override this breach, as a Write's text overrides its own file's.
marked: str = ""
@dataclasses.dataclass(frozen=True)
@@ -124,7 +126,9 @@ def overrides(written: str) -> tuple[dict[str, str], list[str]]:
def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> Checked:
granted, malformed = overrides(written)
blocking = [breach for breach in breaches if breach.rule not in granted]
# A marker overrides a breach when it is in the call's own text or in the breach's file.
grants = [granted | overrides(breach.marked)[0] for breach in breaches]
blocking = [breach for breach, grant in zip(breaches, grants) if breach.rule not in grant]
messages = [f"`{marker}` names no rule below, or gives no reason." for marker in malformed] if blocking else []
where = "the command" if bash else "the text you write, as a comment line"
for rule in sorted({breach.rule for breach in blocking}):
@@ -134,7 +138,7 @@ def check(breaches: list[Breach], written: str, markdown: bool, bash: bool) -> C
continue
marker = f"<!-- rule-override {rule}: <reason> -->" if markdown else f"# rule-override {rule}: <reason>"
messages.append(f"Blocked by rule {rule}: {details}. The rule: {RULES[rule].holds}. Where it does not fit this case, add `{marker}` to {where}; larv-review rules on the reason.")
return Checked(messages, bool(blocking), [(breach, granted[breach.rule]) for breach in breaches if breach.rule in granted])
return Checked(messages, bool(blocking), [(breach, grant[breach.rule]) for breach, grant in zip(breaches, grants) if breach.rule in grant])
def command_breaches(command: str, simples: list[Simple], home: str) -> list[Breach]:
+126 -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")
@@ -913,6 +913,127 @@ class TodoRankCheck(unittest.TestCase):
self.assertNotIn("own script", " ".join(reasons))
class CommittedFiles(unittest.TestCase):
"""A git commit holds the files it would commit to the file rules, as an Edit or Write of each would be."""
UNPINNED = "jobs:\n a:\n steps:\n - uses: actions/checkout@main\n"
def setUp(self):
self.repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", self.repo])
git(self.repo, "init", "-q", "-b", "main")
git(self.repo, "commit", "-q", "--allow-empty", "-m", "base")
def write(self, name: str, content: str) -> None:
path = pathlib.Path(self.repo, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
def commit(self, command: str = "git add -A && git commit -m x") -> subprocess.CompletedProcess:
return hook({"cwd": self.repo, "tool_input": {"command": command}, "tool_name": "Bash"}, self.repo)
def test_a_file_a_command_wrote_is_checked_at_the_commit(self):
self.write(".github/workflows/ci.yml", self.UNPINNED)
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
self.write("NOTES.md", "Co-Authored-" + "By: Claude <noreply@anthropic.com>\n")
ran = self.commit()
self.assertEqual(ran.returncode, 2)
for rule in ["action-pin", "image-pin", "ignorefile-sorted", "no-ai-attribution"]:
with self.subTest(rule):
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_staged_file_is_checked_and_a_clean_tree_passes(self):
self.assertEqual(self.commit().returncode, 0)
self.write(".github/workflows/ci.yml", self.UNPINNED)
git(self.repo, "add", "-A")
self.assertEqual(self.commit("git commit -m x").returncode, 2)
def test_a_breach_the_head_already_holds_is_left_alone(self):
self.write("Dockerfile", "FROM node:24\n")
self.write(".gitignore", "b\na\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "FROM node:24\nRUN true\n")
self.write(".gitignore", "b\na\n\n# more\nc\n")
self.assertEqual(self.commit().returncode, 0)
self.write("Dockerfile", "FROM node:24\nRUN true\nFROM node:25\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_the_command_or_the_file_lets_the_commit_through(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.assertEqual(self.commit("git add -A && git commit -m x # rule-override image-pin: the vendor tags no patch versions").returncode, 0)
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
self.assertEqual(self.commit().returncode, 0)
def test_a_staged_breach_blocks_the_commit_after_the_work_tree_is_fixed(self):
self.write("Dockerfile", "FROM node:24\n")
git(self.repo, "add", "Dockerfile")
self.write("Dockerfile", "FROM node:24.18.1\n")
self.assertIn("image-pin: ", self.commit("git commit -m x").stderr)
def test_a_stat_dirty_file_runs_no_clean_filter(self):
self.write("a.txt", "a\n")
self.write(".gitattributes", "a.txt filter=planted\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
git(self.repo, "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
pathlib.Path(self.repo, "ran").unlink(missing_ok=True)
os.utime(pathlib.Path(self.repo, "a.txt"), (1, 1))
self.assertEqual(self.commit("git commit -m x").returncode, 0)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_submodule_runs_no_clean_filter(self):
inner = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", inner])
git(inner, "init", "-q", "-b", "main")
pathlib.Path(inner, "b.txt").write_text("b\n")
pathlib.Path(inner, ".gitattributes").write_text("b.txt filter=planted\n")
git(inner, "add", "-A")
git(inner, "commit", "-qm", "x", "--no-verify")
git(self.repo, "-c", "protocol.file.allow=always", "submodule", "add", "-q", inner, "sub")
git(self.repo, "commit", "-qm", "x", "--no-verify")
git(f"{self.repo}/sub", "config", "filter.planted.clean", f"touch {self.repo}/ran; cat")
os.utime(pathlib.Path(self.repo, "sub", "b.txt"), (1, 1))
self.assertEqual(self.commit("git commit -m x").returncode, 0)
self.assertFalse(pathlib.Path(self.repo, "ran").exists())
def test_a_checkout_with_no_commit_checks_its_index_and_untracked_files(self):
fresh = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", fresh])
git(fresh, "init", "-q", "-b", "main")
pathlib.Path(fresh, "Dockerfile").write_text("FROM node:24\n")
git(fresh, "add", "Dockerfile")
pathlib.Path(fresh, "NOTES.md").write_text(TRAILER + "\n")
ran = hook({"cwd": fresh, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, fresh)
for rule in ["image-pin", "no-ai-attribution"]:
self.assertIn(f"Blocked by rule {rule}: ", ran.stderr)
def test_a_change_that_only_reorders_an_ignore_file_is_checked(self):
self.write(".gitignore", "a\nb\nc\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write(".gitignore", "c\nb\na\n")
self.assertIn("ignorefile-sorted: ", self.commit().stderr)
def test_a_marker_the_head_already_holds_does_not_override_a_new_breach(self):
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n")
git(self.repo, "add", "-A")
git(self.repo, "commit", "-qm", "x", "--no-verify")
self.write("Dockerfile", "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\nFROM node:24\n")
self.assertIn("image-pin: ", self.commit().stderr)
def test_a_marker_in_another_file_does_not_override_a_breach(self):
self.write("Dockerfile", "FROM vendor/tool:2\n")
self.write("NOTES.md", "# rule-override image-pin: quoted in a note\n")
self.assertIn("Blocked by rule image-pin: ", self.commit().stderr)
def test_an_ignored_or_binary_file_is_left_alone(self):
self.write(".gitignore", "build/\n")
self.write("build/Dockerfile", "FROM node:24\n")
pathlib.Path(self.repo, "image.png").write_bytes(b"\xff\xfe\x00FROM node:24\n")
self.assertEqual(self.commit().returncode, 0)
class RuleNames(unittest.TestCase):
def test_every_rule_name_has_a_rule_and_every_rule_a_name(self):
self.assertEqual(set(RULES), set(typing.get_args(RuleName)))
+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")
+95 -13
View File
@@ -1,3 +1,51 @@
# Project principles
Each project principle states one rule that the decisions below apply; their entries hold the specifics and the evidence. The numbers name the principles, and don't rank them.
1. **Cut cost only where a measurement of archived chunks shows quality holds.** Chunk bundling, the round cap, which fixes rerun a pass, a reviewer of its own for each pass, the review a branch changing only Markdown no agent follows gets, the passes kept for the release review, review opt-outs, the security pass, compaction and the routing ladder all apply it.
2. **A measurement files or ranks work, and never blocks a merge.** The comprehension floor and check, and a reading-cost rise, apply it. A merge waits on a scoring run the plan calls for only until the run is recorded, whatever it scores.
3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is loop-claude's, `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo.
4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it.
5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `deploy-release --cut`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere.
6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude loop-claude starts bypasses permissions inside its sandbox, each claude it or loop-inbox opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried.
7. **One word names one thing, and one rule has one home.** In `bin/`, an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names. `CLAUDE.md` holds only the rules no path can scope, and each `rules/` file loads by its `paths:`.
# Decisions no project principle covers
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
- 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 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
- routing: loop-claude reads the items a chunk takes from the worker's latest `Chunk items:` line and scores them by `todo.md` as the default branch held it when the cycle started; the judge reports the escalation and whether a release is ready to cut
- 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
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
# Working rules
**Routing calls: file them in the plan.** A routing call is a change to the routing ladder, its steps or the delegation rule that loop-claude's figures call for. loop-claude puts each call to the human once, and appends it to `routing-calls-raised.md`, at the root of its archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each line of that file is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites.
When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes the new calls with their stamps. It also quotes the routed-chunks table of `routing-figures.md`, which sits in the same folder, and none of that file's other tables, since they name other projects.
Settling a call is the human's. The chunk that settles the calls cites, in `docs/decisions.md` → `routing:`, the latest stamp it settled, whatever the human decided, so the calls are not filed again. Once a chunk that changes the ladder, its steps or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`. The figures then count only chunks finished after the reset, and a call settled before it may be raised again.
# Decisions
## bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
@@ -32,6 +80,12 @@ The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same c
2026-10-29, lilleman. Serves goal 1.3 and goal 2. `~/.claude` was this repo's development checkout, so every merge reached every session on the machine at once, its unfinished work included, while other machines took only tags. Now each machine takes only releases: what a release holds is what every session runs, and cutting one is the human's step that ships it. `deploy-release` automates README → Update. It refuses an uncommitted change to a tracked file that the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, and a move that would drop commits no release holds; a model pick, which the clean filter drops, is no change. Valid while Claude Code reads its configuration from one directory per machine.
## deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
2026-11-11, lilleman through item 314. Serves goal 1.4. Claude Code loaded `~/.claude/AGENTS.md` into every other project's sessions, and each 1,000 tokens every thread starts with cost $68.60 of the $9,154 spent from 2026-09-30 to 2026-11-11: the 14.4 KB file cost about 2.1% of spend, and put this repo's rules in front of other projects. Other projects keep the name `AGENTS.md`, so the setup stays portable to other harnesses. The working rules sit there too, rather than in `.claude/rules/`, since loop-claude's judge reads the decision log and no project's `.claude/rules/`. In the clone, the release's `~/.claude/CLAUDE.md` and the clone's both loaded, about 0.9% of spend; the exclude drops the release's, so a chunk runs under the rules it is changing. A session working in `~/.claude` itself loads no `CLAUDE.md`, since there both are the same file; none works there, as the entry above says.
Valid while `~/.claude` is a checkout of this repo.
## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_plan/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
@@ -103,7 +157,7 @@ The trials: four stability rounds and five principles rounds archived on 2026-10
- A cap on tool results. Claude Code caps a Bash result at about 30k characters already. A PostToolUse hook capping it at 12k, which `updatedToolOutput` allows, left the stability reviewers 3 of 6 findings, two lost in one round. Read results, 59.9M characters in subagents' threads with 58% of their characters in results over 12k, are out of such a hook's reach. Not worth an item.
- A scout: Haiku 5.5 reading raw content, whole files or long output, and returning facts as path:line and the ranges worth reading, so the agent's own context holds the summary and the chosen lines. In session, as an agent under `agents/`, its first request writes 37k tokens, $0.005, and a read of a 38KB file costs $0.008 in 8 seconds. As a slim headless `claude -p` with its own system prompt, no setting sources and no dynamic sections, which keeps the subscription login, it starts at 6k tokens and $0.0003 in 3 to 5 seconds, its prefix cached across calls, and the same read costs $0.004 in 7 seconds; a direct API call and `claude --bare` need an API key, so they are out. Stability reviewers with the agent scout found 5 of 6 findings and read 29% fewer characters at 6% less cost and 14% more time; with the CLI scout 4 of 6, 38% fewer, 17% less and 39% more; the auditors with the agent scout 3 of 6, the 🔴 among the lost, at the same cost and twice the time. Workers offered the scout never called it.
- What a reviewer reads: the auditors read the project whole by design. Of their 🔴 and 🟡 findings since the reset, 47% named a file the chunk edited and 51% another file, so reading only the change would drop half of them (`review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies`).
- The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record.
- The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loaded as user instructions into every project's sessions until 2026-11-11, when they moved out of `~/.claude`), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record.
Quality. Under the 200k window, every figure's mean per chunk fell. Measured on 2026-11-04, the first 20 chunks whose worker started under it, from 2026-10-28, took a mean 4.0 review rounds past each pass's first against 5.8 for the 20 before them, from 2026-10-23 to 2026-10-26; 0.20 unfinished verdicts against 0.30; 1.15 🔴 against 1.90; 11.9 🟡 against 19.4; 0.11 misread findings against 0.25; $22 against $34; and 9.6 hours against 42. Only the median dollars went up, $15.17 against $11.72: the 20 before held four chunks of $94 to $167, and the 20 after none above $76. This decision weighs all spend, so the mean is the figure that counts. The two groups also differ in projects and routing, so how much of the fall the window caused is unknown. Before the window, 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading.
@@ -120,7 +174,7 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k
- loop-inbox runs the claude command the loop wrote, `bypassPermissions` included, so that claude runs in the same sandbox as the loop. Since loop-inbox runs a command read from a file, the folder is private to the user.
- Files, read by polling, need no daemon and only the standard library, and a loop with no loop-inbox running is answered on its terminal as before.
- loop-inbox lists a question only while its loop holds the session's lock file with flock, and removes a question whose lock is free. The loop holds the lock for its whole run. The kernel frees the lock however the loop ends, killed included. A process id could not tell a running loop from a killed one: on 2026-10-29 this machine's kernel handed out its 32,768 ids again every 30 to 75 minutes, so a killed loop's question came back whenever another process got its id. The lock file stays once the loop ends, one per project: removing it while another process has it open could let loop-inbox lock a file no loop holds. PR #396.
- A loop also lists itself as running, with the items its chunk takes, in `<session>.running`, under the same lock: one lock tells loop-inbox both that the loop runs and that its question stands. The judge names the items the worker took in, as an array of IDs in its reply's `items_taken_in`. PR #397.
- A loop also lists itself as running, with the items its chunk takes, in `<session>.running`, under the same lock: one lock tells loop-inbox both that the loop runs and that its question stands. The items are the one the chunk was routed on, then those the worker names on its latest `Chunk items:` line (`routing: loop-claude reads the items a chunk takes`).
A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0.
@@ -286,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.
@@ -304,7 +374,7 @@ Only chunks run below the project's rung can prove that a cheaper worker holds q
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung while it runs above the project's: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `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…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. The judge reports the highest E + I the worker states for a taken-in item. From the next cycle loop-claude routes on that E + I, and archives it with the route so a rerun keeps it.
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `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…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. loop-claude scores each item the worker names on its `Chunk items:` line by `todo.md` (`routing: loop-claude reads the items a chunk takes`), routes on their highest E + I from the next cycle, and archives it with the route so a rerun keeps it.
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
@@ -356,7 +426,7 @@ A run that asks for a higher rung may also ask a question. The judge then interr
The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell from the quote alone whether the trigger is new. So it goes by where the quoted passage sits in the transcript. When an escalation steps the worker, the route marks how many transcript entries the session held: the mark. loop-claude then accepts an escalation quote only from the worker's own lines after the mark, never from its own prompts or the human's lines, which repeat earlier passages. The judge reads a `[step]` line at the mark saying the triggers before it are spent, so it quotes a passage the check accepts. The session's transcript only grows, so the mark holds across cycles. The trigger that bought a step, and any rewording of it before the mark, cannot buy another. A trigger that fires after the step steps the worker again, in the same cycle or a later one. One risk remains: a worker on the stepped rung may restate an old trigger after the mark, and the judge may quote that. The cap two rungs above the rung the item picks limits what this costs. Before the mark, once an interrupt or a quoted answer had taken an escalation, no later ruling of that cycle carried one, so a trigger that fired after the answer was lost. lilleman chose the mark on 2026-10-18 over two alternatives: lifting that rule when a worker run ended would have let one trigger buy two steps, and telling the worker its request was dropped would still have lost the step.
The step is one rung up from the rung the worker would otherwise hold: its own, or the rung an item the judge saw it take in picks, whichever is higher. It resets the count of unfinished verdicts, so the step every second one takes counts afresh; when both steps fall on one verdict, the worker steps once. It stops at the limit escalated subagents stop at, two rungs above the rung the chunk started on. Past that limit the rung holds: loop-claude takes no yes from the human between cycles, so a worker there asks the human for an escalated subagent instead. The judge keeps its rung, as `routing: on a model judge-replay covered` says.
The step is one rung up from the rung the worker would otherwise hold: its own, or the rung an item it names on its `Chunk items:` line picks, whichever is higher. It resets the count of unfinished verdicts, so the step every second one takes counts afresh; when both steps fall on one verdict, the worker steps once. It stops at the limit escalated subagents stop at, two rungs above the rung the chunk started on. Past that limit the rung holds: loop-claude takes no yes from the human between cycles, so a worker there asks the human for an escalated subagent instead. The judge keeps its rung, as `routing: on a model judge-replay covered` says.
The archive quotes the judge's passage under `Escalation:` in the unfinished verdict, the interrupt or the quoted answer. The step an unfinished verdict causes is archived after it. The step an interrupt or a quoted answer causes is archived with it, at once: the interrupt or answer names the rung the worker ran on until then, and a step-up archived beside it names the rung it runs on from then. So the routing figures charge each stretch to its own rung, and a loop that dies while the human answers resumes on the stepped rung. Each archived worker line names the mark once there is one, so a resumed loop keeps it. `bin/routing_figures/` counts none of these steps as an escalation by trigger, which it counts only from subagent prompts.
@@ -370,6 +440,16 @@ The cost of a cheaper worker shows as extra review rounds and unfinished verdict
Since 2026-10-16 the reviewers may run above the worker's rung, on the one the highest E + I among their chunk's items picks, so chunks whose worker ran on a lower rung may take more rounds from stronger reviewers, and a call could blame the worker's rung for them; `todo.md` item 171 groups the rounds by the reviewers' rung too. Valid while loop-claude's archive holds every finished chunk's review rounds and unfinished verdicts.
## routing: loop-claude reads the items a chunk takes from the worker's latest `Chunk items:` line and scores them by `todo.md` as the default branch held it when the cycle started; the judge reports the escalation and whether a release is ready to cut
2026-11-11, claude. Serves goal 1.4 and code health. The judge's reply held three facts beside its verdict: the items the worker took into the chunk, with their highest L and E + I; whether a release was ready to cut; and any escalation the worker asked for. Routing lifts the worker's, the reviewers' and the judge's rungs by the items' levels. Code now reads the items: each chunk's first prompt, and each prompt resuming it, asks the worker for a line opening `Chunk items:`, `bin/loop_claude/cycle/chunk_items.py` reads the latest such line in the worker's own text, and `release_plan.todo_table` scores the items. So the judge's reply is smaller, and every L and E + I that routing reads comes from `todo.md`, through one module.
The judge field trials (`judge-field-trials/`) read each fact by code over the 709 archived cases. Code was wrong in each of the 39 cases where it and the judge disagreed on an escalation, and read a release ready to cut in 3 of the 31 interrupts that asked about a cut, so the judge keeps both. Workers stated an item with its L and E + I in 413 cases, but also stated items they filed, finished or only mentioned, so the worker writes the items on a line that holds only them, which code reads. Three fresh readers picked its label `Chunk items:`, 3 to 0, because it says the items are the chunk's.
An item the chunk re-scores on its branch routes on its planned levels until the branch merges; where the new L picks a higher rung, the worker cites escalation trigger 1, which the judge finds. Where the worker writes no line, loop-claude counts no item as taken in, so the route holds. Rerun `judge-field-trials/release_ready.py` when the way `chunk-preflight` detects a release review changes.
Valid while workers write the line when asked, and while `todo.md` on the default branch scores each item a chunk takes.
## routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
2026-10-15, lilleman's plan, settled by the replay below. Serves goals 1.2 and 1.4, under the ladder and steps of `routing: one ladder`.
@@ -382,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.
@@ -400,19 +480,21 @@ 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, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
## 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
2026-10-14, lilleman. Serves goal 1.4.
Because a model switch inside a session discards its prompt cache, the worker changes rung only as the chunk starts, after every second unfinished verdict, when the judge reports a taken-in item whose L picks a higher rung, or when the judge finds the escalation trigger a worker cites in asking for a higher rung (`routing: a worker whose run ends asking for a higher rung`). loop-claude routes on the first row of the next release in `todo.md`'s table that does not wait: an item waits while it is marked `question` or a blocker of it is still in the table. Since `todo.md` holds no order but its table's (`todo.md: one table`), that row is the item the worker takes. An item the worker takes in beyond that row lifts the worker's rung once the judge reports it, after the first cycle.
Because a model switch inside a session discards its prompt cache, the worker changes rung only as the chunk starts, after every second unfinished verdict, when the worker names an item on its `Chunk items:` line whose L picks a higher rung (`routing: loop-claude reads the items a chunk takes`), or when the judge finds the escalation trigger a worker cites in asking for a higher rung (`routing: a worker whose run ends asking for a higher rung`). loop-claude routes on the first row of the next release in `todo.md`'s table that does not wait: an item waits while it is marked `question` or a blocker of it is still in the table. Since `todo.md` holds no order but its table's (`todo.md: one table`), that row is the item the worker takes. An item the worker takes in beyond that row lifts the worker's rung once the cycle in which the worker names it ends.
Valid while a model switch inside a session discards its prompt cache.
## rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides any rule but those `rule-hook --help` marks as taking none, and larv-review's overrides pass rules on each override before merge
2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. 2026-10-16, lilleman, answering plan item 166: no marker overrides `reviewer-rung`. 2026-11-04, lilleman: the title points at `rule-hook --help`, which lists every rule no marker overrides from the code, so the title can't drift from it; the comment above each in `bin/rule_hook/rules.py` says why. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool.
2026-10-12, lilleman. Serves goals 1.2 and 1.3. Anthropic's best-practices page calls `CLAUDE.md` advisory and hooks deterministic, so a rule that must hold every time moves into `bin/rule-hook`, and `CLAUDE.md` keeps it only where the hook cannot check it. A Claude Code hook ties the check to one vendor ("Prefer the vendor-neutral option", `principles/technical-principles.md`), which is the target itself here: this repo configures Claude Code. What the tie buys: the hook blocks before a write lands, Edit and Write calls included, in every project with no per-repo install; a git `commit-msg` hook sees only commits, and CI sees them only after the push. The hook checks each write, so the agent fixes the line it just wrote; checking the staged diff at commit time would also cover files a Bash command writes, at the cost of later feedback. The marker's spelling was picked by a panel of three fresh readers, two to one. Each override is logged in the checkout's git directory, which is never pushed (goal 4). The plan had loop-claude's judge to rule on overrides inside a loop; lilleman approved larv-review's overrides pass in every run, because it rules before merge and an outrageous override still reaches the human through its ask. 2026-10-16, lilleman, answering plan item 166: no marker overrides `reviewer-rung`. 2026-11-04, lilleman: the title points at `rule-hook --help`, which lists every rule no marker overrides from the code, so the title can't drift from it; the comment above each in `bin/rule_hook/rules.py` says why. Valid while a PreToolUse hook that exits 2 blocks the call and hands its stderr to the model, and while an agent commits through Claude Code's Bash tool. 2026-11-11, lilleman: the hook also checks, at a `git commit`, each file the commit would commit against the rules that name a file, since a file a Bash command writes reaches no write check; the feedback comes at the commit, not at the write.
## rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
@@ -502,7 +584,7 @@ Three places carry the rule. `rules/todo-items.md` states it and loads with `tod
2026-10-13, lilleman through todo item 104, implemented by claude. Serves goals 1.4 and 1.5. Like red, green, refactor: the worker makes the item work, and the review passes raise it to the bar. A loop-claude worker loaded `CLAUDE.md` and every file under `rules/`, 4,247 words, and `CLAUDE.md` told it to read `technical-principles.md` too, 2,426 words more. The reviewers read the principles anyway, and a finding against one names it.
The worker keeps what it needs to write its own work. Each project's decision titles stay in its `AGENTS.md`, since a worker that misses a decision builds the wrong behaviour. A core of "Prose" stays in `CLAUDE.md`, since no reviewer reads the worker's chat. lilleman chose both on 2026-10-13. The rules for writing Goals and Audience, `todo.md` items and decisions stay in `rules/`, since writing those is the worker's job. `bin/rule-hook` stays: it blocks what a program can check, at no context cost. "Quality", the rules for comments and READMEs, and the examples behind "Prose" moved to `skills/larv-review/standards/`, which no path loads. loop-claude's judge and the prose reviewer read them, and the stability reviewer reads "Quality". They sit beside larv-review, whose passes apply them; `principles/` stays where it is, since the principles auditor reads it per file.
The worker keeps what it needs to write its own work. Each project's decision titles stay in its `AGENTS.md`, since a worker that misses a decision builds the wrong behaviour. 2026-11-11, lilleman: a project principle in `AGENTS.md` now stands in for the titles of the decisions it covers. A core of "Prose" stays in `CLAUDE.md`, since no reviewer reads the worker's chat. lilleman chose both on 2026-10-13. The rules for writing Goals and Audience, `todo.md` items and decisions stay in `rules/`, since writing those is the worker's job. `bin/rule-hook` stays: it blocks what a program can check, at no context cost. "Quality", the rules for comments and READMEs, and the examples behind "Prose" moved to `skills/larv-review/standards/`, which no path loads. loop-claude's judge and the prose reviewer read them, and the stability reviewer reads "Quality". They sit beside larv-review, whose passes apply them; `principles/` stays where it is, since the principles auditor reads it per file.
A finding against a principle names it, so the worker reads only that one when it fixes or declines the finding. The worker still writes a failing test first wherever a test can check the change, since no reviewer can make a test come first. On 2026-10-13 lilleman widened it from code changes to anything there is to test. A chunk that changes no code, config or test, such as one that only plans, meets no principles review; the chunk that implements its items does. The prose reviewer checks that a doc sorts a list whose order carries no meaning.
+128
View File
@@ -1536,3 +1536,131 @@ Read most (opens and searches):
Read most (opens and searches):
- `todo.md` 1
## Reading cost, chunk 4a0a495957fb, finished 2026-11-11T13:02:21Z
146184 new input tokens before the first commit.
Read most (opens and searches):
- `bin/larv_review/main.py` 9
- `bin/larv_review/plan.py` 5
- `bin/larv_review/test_larv_review.py` 5
- `bin/chunk_pr/test_chunk_pr.py` 4
- `bin/larv_review/history_commands.py` 4
- `bin/review_rules/comprehension_history.py` 4
- `bin/chunk_pr/main.py` 3
- `bin/chunk_preflight/main.py` 3
- `bin/release_plan/release_standing.py` 3
- `CHANGELOG.md` 2
## Reading cost, chunk fe37d406ce5e, finished 2026-11-11T14:48:44Z
98857 new input tokens before the first commit.
Read most (opens and searches):
- `bin/rule_hook/test_rule_hook.py` 9
- `bin/rule_hook/main.py` 6
- `todo.md` 5
- `bin/rule_hook/rules.py` 3
- `skills/larv-review/SKILL.md` 3
- `.gitignore` 2
- `README.md` 2
- `bin/rule_hook/call.py` 2
- `docs/decisions.md` 2
- `AGENTS.md` 1
## Reading cost, chunk 667832515e57, finished 2026-11-11T15:26:47Z
59123 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 5
- `todo.md` 4
- `docs/decisions.md` 2
- `AGENTS.md` 1
- `rules/decisions.md` 1
- `skills/larv-review/standards/comments.md` 1
## Reading cost, chunk 5c4df7817bc1, finished 2026-11-11T15:58:04Z
107410 new input tokens before the first commit.
Read most (opens and searches):
- `docs/decisions.md` 8
- `README.md` 7
- `rules/decisions.md` 5
- `bin/loop_claude/loop/routing_check.py` 3
- `bin/loop_claude/loop/usage.py` 3
- `skills/comprehension-panel/seat-prompts.md` 3
- `.gitignore` 2
- `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
+27
View File
@@ -0,0 +1,27 @@
# Judge field trials
These trials ask one question: which of the facts loop-claude's judge reports could code read instead?
The judge is the headless claude that rules on each worker run; its reply named the items the chunk took, whether a release was ready to cut, and any escalation the worker asked for.
They ran on 2026-11-11, over the 709 cases archived by then. `docs/decisions.md` → `routing: loop-claude reads the items a chunk takes` records what was decided from them.
## Terms
- **Case:** an outcomes file in `~/.claude/loop-claude-transcripts/`, its first verdict, and the transcript the judge read for it.
- **Final message:** the last text the worker wrote after the last prompt loop-claude or the human gave it.
## Results
| Field | What code tried | Result |
|---|---|---|
| Escalation | "higher rung", "rung up" or "one rung above" in the final message | Code is wrong in each of the 39 disagreements: 37 where only code finds a request, 2 where only the judge does. Code matched a worker asking for the human's yes at the top rung and a review report quoting "rerun one rung up", and missed requests made before the final message. The judge keeps the field. |
| Release ready to cut | The plan as the default branch and tags stood at the verdict, read by `release_plan.release_standing` | Of 240 interrupts, 31 ask about a cut, and code reads ReadyToCut for 3. Two misses are code's: in two projects a release review had merged without the `Release review of <release>` commit that code looks for. The rest asked under older rules or after the cut. The judge keeps the field, and a `todo.md` item files the fix. |
| Items the chunk takes | An item stated with its L and E + I anywhere in the worker's text | 413 of 709 cases state one, 77 of them more than one, and workers also state items they file, finish or only mention. Code reads the items from a line that holds only them, which workers write only since loop-claude asks for it, so the archive can't measure it. |
## Running
Each script reads the archive on this machine through `cases.py` and prints its counts last; run it from the checkout's root, as in `python3 judge-field-trials/escalations.py`.
The lines above the counts quote transcripts and name projects, so they stay on this machine.
- `escalations.py` prints each escalation disagreement with the words around it.
- `release_ready.py` prints each interrupt's question beside whether code reads the release ready to cut.
- `items.py` prints a few cases stating more than one item.
+41
View File
@@ -0,0 +1,41 @@
"""Each archived case: an outcomes file's first verdict, with the transcript copy the judge read for it."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin"))
from transcript_archive.outcomes import ANY_VERDICT_AT, OUTCOME_AT, task_of
from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text
from claude_code.transcript import read_transcript
from transcript_archive.location import transcript_of
ARCHIVE = pathlib.Path.home() / ".claude/loop-claude-transcripts"
def first_block(outcomes: str) -> tuple[str, str, str] | None:
"""The first verdict's stamp, its heading, such as `Verdict: interrupt`, and its whole block, up to the next outcome."""
found = ANY_VERDICT_AT.search(outcomes)
if not found:
return None
ends = [start.start() for start in OUTCOME_AT.finditer(outcomes) if start.start() > found.start()]
return found[1], found[2], outcomes[found.start():ends[0] if ends else len(outcomes)]
def cases():
"""Each outcomes file in the archive whose task and first verdict can be read, with that verdict and its transcript's entries."""
for outcomes in sorted(ARCHIVE.glob("*/*/*.outcomes.md")):
text = outcomes.read_text(encoding="utf-8")
block = first_block(text)
entries = read_transcript(str(transcript_of(outcomes)))
if block is not None and task_of(text) is not None and isinstance(entries, list):
yield outcomes, block, entries
def worker_texts(entries) -> list[str]:
return [part.text for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text)]
def last_run_text(entries) -> list[str]:
"""The worker's text after the last prompt loop-claude or the human gave it: what the judge rules on."""
at = max((index for index, entry in enumerate(entries) if isinstance(entry, LoopPrompt | HumanTurn)), default=-1)
return worker_texts(entries[at + 1:])
+20
View File
@@ -0,0 +1,20 @@
"""Could code find an escalation request where the judge did? Counts, per verdict kind, whether the worker's final message asks for a higher rung and whether the judge's verdict carried an escalation, and prints each disagreement with the words around it."""
import collections
import re
from cases import cases, last_run_text
ASKS = re.compile(r"higher rung|rung up|one rung above", re.IGNORECASE)
table = collections.Counter()
for outcomes, (stamp, kind, block), entries in cases():
texts = last_run_text(entries)
final = texts[-1] if texts else ""
found = ASKS.search(final)
escalated = "\nEscalation:\n" in block
table[(kind, bool(found), escalated)] += 1
if bool(found) != escalated:
around = final[max(0, found.start() - 200):found.end() + 150] if found else final[-300:]
print(f"## {outcomes.parent.parent.name} {stamp} {kind} code={bool(found)} judge={escalated}\n {around!r}\n")
for (kind, code, judge), count in sorted(table.items()):
print(f"{kind}: code {code}, judge {judge}: {count}")
+19
View File
@@ -0,0 +1,19 @@
"""How do workers name the items a chunk takes, unasked? Counts, per verdict kind, the cases whose worker states an item with its L and E + I, and those stating more than one, and prints a few of the latter."""
import collections
import re
from cases import cases, worker_texts
STATED = re.compile(r"item (\d+)\b[^.\n]{0,60}?\bL (\d)\b[^.\n]{0,40}?E \+ I (\d+)", re.IGNORECASE)
table = collections.Counter()
shown = 0
for outcomes, (stamp, kind, block), entries in cases():
found = [match for text in worker_texts(entries) for match in STATED.finditer(text)]
ids = sorted({int(match[1]) for match in found})
table[(kind, bool(found), len(ids) > 1)] += 1
if len(ids) > 1 and shown < 12:
shown += 1
print(outcomes.parent.parent.name, stamp, ids, [match[0][:120] for match in found[:4]])
for (kind, stated, several), count in sorted(table.items()):
print(f"{kind}: states an item {stated}, more than one {several}: {count}")
+53
View File
@@ -0,0 +1,53 @@
"""Could code find a release ready to cut where the judge did? For each archived interrupt, prints whether the plan, as the project's default branch and tags stood at the verdict's stamp, read ReadyToCut, and whether the judge's question is about a cut."""
import collections
import datetime
import pathlib
import re
from cases import cases
from transcript_archive.project_key import checkout_of
from release_plan.release_standing import chunk_item, default_plan, ReadyToCut
from git_cli.git_repo import default_ref, git
from release_plan.todo_table import items
ABOUT_CUT = re.compile(r"\bcut\b|ready to (?:cut|release|ship)|tag (?:it|v\d)|version bump", re.IGNORECASE)
def as_of(stamp: str):
"""A git runner that lists only the tags created by stamp, so a later cut doesn't count."""
def run(*args, cwd=None, **kwargs):
out = git(*args, cwd=cwd, **kwargs)
if "tag" in args and "--list" in args and isinstance(out, str):
dates = git("for-each-ref", "--format=%(refname:short) %(creatordate:iso-strict)", "refs/tags", cwd=cwd)
created = dict(line.split(" ", 1) for line in dates.splitlines()) if isinstance(dates, str) else {}
out = "\n".join(tag for tag in out.split() if utc(created.get(tag, "")) <= stamp)
return out
return run
def utc(iso: str) -> str:
"""iso in the verdict stamp's form, or "" for no date, which sorts before every stamp."""
return datetime.datetime.fromisoformat(iso).astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if iso else ""
table = collections.Counter()
for outcomes, (stamp, kind, block), entries in cases():
if kind != "Verdict: interrupt":
continue
project = outcomes.parent.parent.name
root = str(checkout_of(project, pathlib.Path.home()))
question = block.split("\n\n", 2)[1] if block.count("\n\n") >= 2 else ""
about = bool(ABOUT_CUT.search(question))
ref = default_ref(root, 10) if pathlib.Path(root).is_dir() else None
commit = git("rev-list", "-1", f"--before={stamp}", ref, cwd=root) if isinstance(ref, str) else None
if not isinstance(commit, str) or not commit.strip():
table[("no checkout or commit", about)] += 1
continue
plan = default_plan(root, commit.strip(), as_of(stamp))
found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo
pick = chunk_item(found, plan.cut) if isinstance(found, list) else found
ready = isinstance(pick, ReadyToCut)
table[(ready, about)] += 1
print(f"{'ready' if ready else 'not '} {'cut?' if about else ' '} {project} {stamp} {type(pick).__name__}: {question[:220]!r}")
for (ready, about), count in sorted(table.items(), key=str):
print(f"ReadyToCut {ready}, asks about a cut {about}: {count}")
+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
@@ -72,7 +72,7 @@
- BANNED: a CLI that refuses to run until given `--data-path` and `--seed`, when nearly every run wants the shipped data and fresh randomness. GOOD: it uses the shipped data and fresh randomness unless a flag overrides them, and `--help` names those flags.
* Deterministic order wherever order carries no meaning.
- Sort such a list, on a key that does not move: the name a line introduces, never where it came from. Exception: `id` goes first. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
- An import sorts on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group.
- An import sorts on its first binding, not its path, so moving or renaming a module doesn't reorder anything. Where lines already group by kind — type imports, host packages — the key sorts within each group.
* About seven things per level, so a reader new to the project can take in each level at once.
- A level is what a reader looks at together: the parameters of a function and its branches (cyclomatic complexity), the methods of a class, the files in a folder and the folders beside them, the sections of a document, the components of a system, the hops of a call chain. Past about seven, group the things under names a reader can follow; each group then counts as one.
- Parameters, branches and the values a function tracks act on each other, so a reader holds them in mind together, and a mind holds about four. Aim for four or five of them, and treat seven as the ceiling. Keep a function to one screen, about 24 lines of 80 characters.
+3 -1
View File
@@ -6,6 +6,8 @@ paths:
# Decisions: one home, each linked to a goal or a technical principle
**The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists every title, so a session works by the decisions without loading their background. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies.
**The decision log has one home: `docs/decisions.md`**. A title states the whole decision in one line: what holds at the commit it ships in, in words a reader finds in the code or the plan. `AGENTS.md` lists the project principles and the title of each decision no project principle covers, so a session works by the decisions without loading their background. The entry holds the background: its date, who made it, the reasoning, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies.
**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it.
**Check each new decision against the project's principles.** A project principle, listed in the project's `AGENTS.md` under `## Project principles`, states one rule that several decisions apply. Each time a decision is recorded, ask three things. Does a project principle already cover it? Then it adds no title to `AGENTS.md`, and needs no ask. Does it break one? Then either the principle or the decision is wrong. Does it apply the same rule as decisions already listed? Then that rule is a new project principle, which covers those decisions too. A break, a new project principle or a change to one is the human's: ask, with your recommendation, and leave the project principles as they are until the human answers. Once the human approves a new one, the titles it covers leave `AGENTS.md`.
+1 -1
View File
@@ -39,7 +39,7 @@
"includeCoAuthoredBy": false,
"mcpServers": {},
"modelSettings": {
"claude-fable-5-1": {
"claude-fable-5-2": {
"effortLevel": "high"
}
},
+2 -2
View File
@@ -15,7 +15,7 @@ independently, so every seat's report counts.
## What makes the result trustworthy
Hold all of these or the comparison proves nothing.
Hold all of these or the comparison doesn't prove anything.
- **One variable.** Every panelist runs the same model with the same brief and the same report
shape. Only the persona differs. A cheaper model for the juniors turns persona into a confound.
@@ -162,7 +162,7 @@ with the same four dimensions and overall as the other seven.
Every panelist ends with a comprehension score, 1 to 10, for the project as a whole. The scale is
absolute, so two panels run on two projects produce comparable numbers — a panelist scoring against
their own expectations of *this* codebase has produced a number that means nothing next to
their own expectations of *this* codebase has produced a number that doesn't mean anything next to
another. Put these anchors in every brief, verbatim.
- **1 — Spaghetti.** No boundary holds. Finding where a behaviour lives is grep archaeology;
@@ -93,3 +93,11 @@ Report, in this shape:
2. The places that decided them, most decisive first. Each opens with the names from your rulings line that it moves, joined by ", " and followed by ": ", such as `Locality, Shape: `. Then `path:line` and the unit's name, each in backticks, in the version the place is in, and one or two sentences on what reads easier or harder there than in the other version. A dimension's ruling that no place opens with counts as same, and the overall ruling does unless you name a place.
3. Where a place you name backs a worse ruling and you want a more capable reader to check that ruling, the line `Rerun one rung up`.
```
## claude-config's values
- `{language}`: Python
- `{kind}`: a Claude Code configuration with an agent loop and review skills
- `{domain}`: driving headless Claude Code sessions, agent review workflows
- `{domain docs}`: the Claude Code documentation
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a third time
+11 -6
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.
@@ -76,8 +80,8 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
**Round cap.**
- **Round.** A round is one review by a pass's reviewer: the first and each re-entry. The rerun after the architect returns Stage 0 questions ("Architecture" below) and a relaunch one rung up ("Rung up" below) stay in their round.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts, up to the cap, a round. Its count is the number of its reviews on the PR, less its reviews of a `Record the comprehension check:` commit, and `round-count` doesn't list it. A commit that answers one of its rounds takes an ordinary title, not an `Answer <pass> round` one, and a round that changed nothing gets no commit.
- **Count.** Close each round of a pass other than the auto-reviewer with one commit that holds the round's fixes. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); …`: `<pass>` is the pass's name in lower case, such as `full scan`, `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported, and `<j>` is how many of those they marked `[misread]` (review-findings.md → "Misread"); a reviewer that marks none, such as `/security-review`, adds 0. Example: `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts, up to the cap, a round. Its count is the number of its reviews on the PR, less its reviews of a `Record the comprehension check:` commit, and `round-count` doesn't list it. A commit that answers one of its rounds takes an ordinary title, not an `Answer <pass> round` one, and a round that didn't change anything gets no commit.
- **Count.** Close each round of a pass other than the auto-reviewer with one commit that holds the round's fixes. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); …`: `<pass>` is the pass's name in lower case, such as `full scan`, `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported, and `<j>` is how many of those they marked `[misread]` (review-findings.md → "Misread"); a reviewer that marks none, such as `/security-review`, adds 0. Example: `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted test`. A round that didn't change anything gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most two rounds per chunk, and the release review's architecture and principles passes five; don't ask the user for more. Answer its last round's findings per "Findings": those fixes merge once the gate passes, unreviewed by that pass. rule-hook's `round-cap` refuses a round commit that would take a pass past its cap, and no override waives it. A review the auto-reviewer posts after its second isn't a round: fix none of it and rerun no pass for it, but file a security finding it raises per `~/.claude/CLAUDE.md` → "Working loop", and any other 🔴 in `todo.md`.
@@ -92,7 +96,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
| made rule-hook log an override | Overrides |
| changes behaviour: what the code or its tests do | Stability |
A fix meets every row it fits. Prose has no row, so a comment or doc edit inside a fix reruns nothing. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
A fix meets every row it fits. Prose has no row, so a comment or doc edit inside a fix doesn't rerun any pass. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
**What a round reviews.** An agent under `~/.claude/agents/` reviews the branch in round 1. From round 2 it reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
@@ -106,6 +110,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A 🔴 is marked `defect`. A 🟡 against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". In the release review the whole project is the chunk's change, so nothing lies outside it; "Release review" → "Findings" says which of its findings are filed.
- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
- **New decision.** Each decision a fix or an answer records in `docs/decisions.md` is checked against the project principles per `~/.claude/rules/decisions.md` → "Decisions: one home, each linked to a goal or a technical principle", "Check each new decision against the project's principles", before the commit that records it.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🟡.** A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
- **🟢 and ❓.** A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
@@ -159,7 +164,7 @@ The comprehension check records how hard the project is for its contributor to r
### Security
`/security-review` over the branch diff is the pass of record, except where the full scan runs on the same change and replaces it. Where the full scan fires but does not run — skipped on a precedent, declined at its cost prompt, or unavailable — `/security-review` runs. Launch a general-purpose subagent that invokes it through the Skill tool, edits nothing, and replies with the skill's report, or that the skill is unavailable. Invoked in your own context, the skill ends your turn on that report. Open this subagent's prompt, and that of any subagent that runs the full scan, with `You are the security pass for this chunk.`: rule-hook reads that sentence as a security launch.
`/security-review` over the branch diff is the pass of record, except where the full scan runs on the same change and replaces it. Where the full scan fires but does not run — skipped on a precedent, declined at its cost prompt, or unavailable — `/security-review` runs. Launch a general-purpose subagent that invokes it through the Skill tool, doesn't edit anything, and replies with the skill's report, or that the skill is unavailable. Invoked in your own context, the skill ends your turn on that report. Open this subagent's prompt, and that of any subagent that runs the full scan, with `You are the security pass for this chunk.`: rule-hook reads that sentence as a security launch.
A verified HIGH inside this chunk's blast radius is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which.
@@ -173,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
@@ -183,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`.
+1 -1
View File
@@ -2,7 +2,7 @@
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
A reviewer reads and reports; it edits nothing. It writes no file but its report, except the scratch files that a reviewer holding Bash makes with Bash. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
A reviewer reads and reports; it doesn't edit anything. It writes no file but its report, except the scratch files that a reviewer holding Bash makes with Bash. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
## Severity
+2 -2
View File
@@ -6,7 +6,7 @@ The reader is a competent reader of THIS codebase. A comment or a paragraph earn
## Where a choice goes
**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. A choice found anywhere else — an `AGENTS.md` body, a comment away from the code it governs, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to `docs/decisions.md`, leaving its title in `AGENTS.md`'s list.
**A choice that shapes what the code does, made in one place, is a comment there, with its reason. Made in more than one place, it is a decision, and the decision log owns it.** A decision's rejected alternative, or what it deliberately does not cover, stays out of every call site. A choice found anywhere else — an `AGENTS.md` body, a comment away from the code it governs, or a README section that is neither a goal nor how one is met — moves: to a comment at its one place, or, once made in more than one place, to `docs/decisions.md`, leaving its title among `AGENTS.md`'s decision titles unless a project principle there covers it.
## Comments
@@ -22,7 +22,7 @@ Default to NO comment. Delete one that is any of:
**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate.
## Negation, history and limitations: name the action, or say nothing
## Negation, history and limitations: name the action, or leave it out
Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**.
+2 -1
View File
@@ -9,5 +9,6 @@ Everything written — chat, commit messages, comments, docs, code — is in **E
3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them.
4. **Short.** Cut whatever does not clearly help 1–3.
- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone.
- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, doesn't carry anything — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone.
- **Write negations as people say them.** After a verb, or after its preposition, write `doesn't <verb> anything` or `anyone`, never `<verb> nothing` or `no one`; each breach is a 🟡. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`.
- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader choosing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`.
+231 -97
View File
@@ -6,67 +6,235 @@
`Bar = 0.1`
`Next ID = 303`
`Next ID = 333`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 294 | 0.8.0 | | | **Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.** | 2 | 2 | 3 | 5 | 4 | 1.3 by 5 | 5.2 |
| 297 | 0.8.0 | | | **Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 2, code health by 2 | 3.7 |
| 302 | 0.8.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 |
| 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 |
| 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 |
| 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 |
| 298 | 0.8.0 | 297 | | **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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 192 | 0.9.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 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 |
| 202 | 0.9.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 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 |
| 174 | 0.9.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 0.5 |
| 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
### 294. Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.
### 331. Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.
From 2026-11-08 to 2026-11-10, workers in other projects wrote 1,266 files through Bash (a python heredoc, `sed -i`, `cat >`) against 260 through Edit and Write, and `rule-hook --help` says it doesn't check a file a Bash command writes. So `action-pin`, `image-pin`, `ignorefile-sorted` and the attribution check miss most edits. rule-hook already checks at `git commit` for `todo-rank-check`, so checking staged files there follows a pattern the repo has. Ship item 192 in the same chunk: its unsorted `.gitignore` block is one symptom of this gap.
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.
### 297. Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.
- `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.
`bin/loop_claude/cycle/judge.py` already checks quotes in code (`quotes_checked`, `grounded`, `re_ask_checked`). The `Reply` fields `items_taken_in`, `release_ready` and `escalation` state facts the plan and git already hold, so code can derive them with certainty, and the judge's prompt shrinks to what needs judgement. Before switching, recompute each field for the 668 archived verdicts offline and count where code and judge disagree; read each disagreement and keep the judge for a field where code is wrong. Seats found `quotes_checked` hard to read (PR #397's scoring run: the misquote rule is split across `judge.py` and `escalation_mark.py`); make it easier to read where the change touches it.
Recommendation: reword all four as above. They are decisions the repo held before item 292, so the rewording is lilleman's call.
### 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.
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.
`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.
The review passes need no replay: `review-replay` tests only rungs below the project's rung, which item 292 left as they were.
### 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.
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.
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.
Anthropic reports Sonnet 4.6 with an Opus 4.6 advisor scored 2.7 points more on SWE-bench Multilingual at 11.9% less cost than Sonnet alone (the vendor's own run; https://claude.com/blog/the-advisor-strategy). The docs say `/advisor` works with `-p`, but not outright that the advisor is called during a `-p` run, so probe that first. Each advisor call hands the advisor the whole conversation, so count its cost. Bench on `workflow-bench` with archived L 1 and L 2 items: Sonnet with the advisor, Sonnet alone, Opus at medium. lilleman approved on 2026-11-11.
### 315. Start each reviewer under `agents/` without `CLAUDE.md`, and hand it the vocabulary, the prose rules and the project's decision titles.
`omitClaudeMd: true` in an agent's frontmatter (Claude Code 2.1.271 or later) starts it without the user, project and local instruction files. About 77% of `CLAUDE.md` is the worker's: "Working loop", "Working with the codebase", "Git", "Handoffs", "Compact instructions". Over the archive, each 1,000 prefix tokens cost $31 across the six reviewers, so this saves about 1.9% of spend. A reviewer still needs "Vocabulary", "Prose" and the project's decision titles: put the first two in the agent bodies or a `SubagentStart` hook's `additionalContext`, and have `larv-review reviewer-header` print the titles.
Gate it per pass: keep it only where `review-replay` with the changed definition (through `--agents`) on 10 archived rounds finds what two replays of the unchanged reviewer find; the unchanged reviewer re-finds only 69 to 73% of its own findings, so one baseline doesn't show the noise. Revise the decision `rules/: CLAUDE.md holds the worker's rules that no file path can scope`. lilleman approved on 2026-11-11.
### 312. 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.
lilleman, 2026-11-11: besides an output ceiling, keep evaluating better tooling. The token research of that day found tool results carried in context cost about 21% of spend, reads by subagents the most, and that the tools themselves move fast: deferred tool loading, output saved to files, code-execution over tools, LSP and repo-map navigation, structured test output. Item 231 tried a scout, an outline script and LSP in October and none kept every finding.
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.
1. **The setup that ran.** A verdict names the worker's model, effort and item, but not the `~/.claude` tag and commit the chunk ran under. Judging any change to the setup means comparing chunks before and after a deploy, and deploys lag behind cuts, so timestamps can't tell. Add a line such as `Config: v0.7.0 (<sha>)` to each verdict, interrupt and answer.
2. **Spend in raw tokens.** Record what each cycle spent as raw token counts per model and per kind: input, cache write 5-minute, cache write 1-hour, cache read, output, thinking where known. Do it for the worker's main thread, each subagent (by agent type and description) and the judge. Dollars are derived later from model and tokens; as a secondary bonus, record the price table in force when the spend was made (from `bin/routing_figures/prices.py`), so a later price change doesn't rewrite history. The token research measured this by hand on 2026-11-11 and had to deduplicate cumulative worker snapshots by `message.id`: count each message once.
3. **Reversals.** The decision of 2026-11-08 (item 262) lets a worker take its own recommendation on an unreserved choice "while the human reverses few of the choices workers take", and no tool counts those reversals. Have the judge flag an answer the human typed that overrides a choice the worker took and recorded, and count them per chunk in `score-outcomes` beside later fixes and misread findings. This is the quality signal a cheaper setup could quietly worsen.
Build on item 303's archive layout for the judge's part.
### 318. 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.
Today a rung qualifies only if it re-finds every finding the project's rung found. The project's rung itself re-finds only 69 to 73% of its own findings on a replay (29 of 40, 27 of 39, 20 of 29), so even a reviewer exactly as good would fail, and "no pass has such a rung" says less than it seems. Qualify a rung when its share of the archived findings is no lower than the project's rung's own replay share, within a margin, over enough rounds, and it misses no 🔴 that both project-rung runs found. Then replay Opus 5.5 at low effort on the prose pass first, the pass whose misses cost least; the `effort` frontmatter key sets it per reviewer.
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, 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. 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 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.
In 0.7.0's 35 chunks, workers made 65 `tea api` calls in 26 chunks, mostly polling commit status and trying merge methods in turn, and ran 25 `until … sleep` loops that took 1,744 seconds. `chunk-pr merge` takes `--gate-passed` on the worker's word; waiting for the required checks itself makes that flag a fact, not a claim. This is the kind of step item 284 files, and can count as its first.
### 319. 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.
On SWE-bench Verified with Haiku 4.5 and Opus 4.7, handing the strong model the weak model's transcript solved 69.2% at $1.61 a task; starting the strong model fresh solved 79.2% at $0.90 (arXiv 2608.24358, The Handoff Tax). A model switch also rereads the whole context uncached (Claude Code prompt caching docs). A worker that steps from Sonnet 5.5 to Opus 5.5 by `--resume` is the raw handoff; an effort-only step within one model keeps the cache and isn't. The escalated subagent, which starts fresh with the trigger's evidence, already follows the pattern that won.
Bench it first on `workflow-bench`: resume against a fresh start with a brief. The brief is the chunk's item, its branch and diff, open findings and the trigger. lilleman approved on 2026-11-11. Revise the decision `routing: a worker whose run ends asking for a higher rung…`.
### 309. 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.
Seats cost $1,143 of the $9,154 measured from 2026-09-30 to 2026-11-11 (12.5%), scoring runs $470 of that. A scoring run today is four seats, run twice on one head: eight seat runs. Two seats on the second pass make it six, and two on both passes four.
Why it should hold quality: the seats are one model with different personas, so their errors are correlated, and a correlated extra seat adds little. `larv-review agreement` showed on 2026-11-11 that Mid A and the inherited architect voted alike in 58 of 75 paired rulings, while their scores moved alike between two runs on one commit in only 1 of 4 pairs: seats agree with each other more than a run agrees with its rerun, so the rerun carries more new information than the third and fourth seat. Nine judges from seven model families carried about two independent votes (arXiv 2605.29800), and ten with error correlation 0.21 carried 3.5 (arXiv 2609.22512).
Decide once `agreement` has its 10 commits scored twice. Keep four seats on any pass that files a floor item, since its places come from seat reports. Revise the decision `review: the comprehension check records how hard a project is to read…`, which names the four-seat run.
### 299. 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.
The judge's LLM still decides three things: the verdict kind, the escalation it quotes, and whether a release is ready to cut (`docs/decisions.md` → `routing: loop-claude reads the items a chunk takes …`). This item replays the verdict kind. No single rule found so far separates interrupts: a "?" in the worker's final message appears in 48 interrupts and misses 66. A smaller LLM already failed the replay (`docs/decisions.md` → `routing: on a model judge-replay covered, …`: Sonnet returned another kind on 3 interrupts, Haiku missed 7). Untested are combined code rules, a decision table, and a small classifier trained and run on this machine on the archived verdicts (372 finished, 234 interrupt, 42 unfinished, 20 quoted). Run each offline, nothing sent to an outside service (goal 4), and count disagreements by kind; the bar is zero missed interrupts. A hosted decision model is out of scope, since it would send transcripts to an outside service.
### 311. 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`.
Workers took 7,870 Bash results over 3,000 characters, $305 of carried context, against the reading rule in their prompt; stability reviewers another $145. `BASH_MAX_OUTPUT_LENGTH` (or `bashOutputMaxChars`) makes Claude Code save a longer result to a file and hand the model its path and the first 2,000 characters. loop-claude can hand it as it hands `CLAUDE_CODE_AUTO_COMPACT_WINDOW`. A ceiling of 6,000 characters would have removed $228 of carried output, 10,000 characters $122. Reads of old session transcripts cost $46; a rule-hook rule can refuse them.
Subagents inherit the variable, and the decision of 2026-10-27 found a 12k cap cost stability reviewers a finding (3 of 6 against 4 of 6). That cap left no file to read, and the difference is inside the noise that decision reports. So keep the ceiling only where a replay of the archived stability rounds finds what two baseline replays find, and join item 260's comparison.
### 316. 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.
Seats run as general-purpose subagents, so each starts with the skill and agent listings, about 7,500 tokens, at $9.00 per 1,000 prefix tokens over the archive measured from 2026-09-30 to 2026-11-11: about 1.3% of spend. An agent under `agents/` with Read, Grep, Glob and Bash, `omitClaudeMd: true`, and the seat's persona in its prompt drops both; a seat reads the project as a newcomer does, which is what it simulates. Keep each seat's prompt from `skills/comprehension-panel/seat-prompts.md`. Check that a scoring run's scores on one head stay within the spread two runs of today's seats show. lilleman approved on 2026-11-11.
### 310. Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.
281 worker resumes after the 1-hour cache expired rewrote a whole context, $379 of the $9,154 measured from 2026-09-30 to 2026-11-11 (4.1%). A compaction while the cache is warm reads the context at a twentieth of the input price and leaves about 20k tokens to rewrite later.
lilleman, 2026-11-11: do it on a timer, so an answer that comes in time doesn't cost anything. When loop-claude interrupts, start a timer a margin short of the cache lifetime (about 50 minutes of a 1-hour cache; read the lifetime from the session's last `cache_creation` usage). If no answer has come when it fires, compact the session, then keep waiting. Skip it below about 60k tokens of context, where the rewrite costs less than the compaction. A wait for a usage limit can't be helped this way.
Probe first that `claude -p "/compact" --resume <id>` compacts a session: the Agent SDK documents `/compact` as a prompt, the CLI pages don't show it. Claude Code compacts idle interactive sessions itself ("Compacted while idle"), but not `-p` runs. Check: the cost entries of 20 chunks with an interrupt, before and after.
### 298. 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.
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.
### 326. Let `chunk-pr ready` take the pull request's final title and set it as it marks the pull request ready.
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.
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.
Left with the model: wording the title.
### 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.
Today no judge transcript reaches loop-claude's archive. `bin/claude_code/reply.py` runs every headless reply, the judge's included, with `--no-session-persistence`, so its runs stay out of the session picker; Claude Code then writes no session file for the archive to copy. No decision chose to leave the judge out: `loop-claude: the archive keeps the raw transcript` was written for the worker's `.jsonl`. Goal 3 asks for the transcripts of unattended runs to be backed up, and the judge is one. The gap also leaves the judge's spend measurable only from the `Judge cost:` lines, which older verdicts lack ($136 recorded over 2026-09-30 to 2026-11-11), and leaves `judge-replay` rebuilding each prompt from today's records: of the 39 verdicts it replayed on 2026-10-15, 8 may rest on records that had changed since.
The judge runs with no tools and one turn (`judge_args` in `bin/loop_claude/cycle/judge.py`), so its whole transcript is the prompt it read and the json reply. Recommended: keep `--no-session-persistence`, and have the archive write the prompt and the reply beside the outcomes entry of the verdict, interrupt or rejected reply they produced, deduplicated by content hash as the worker's copies are. A failed write stops the loop, as that decision says. Persisting the session and copying its file would also work, but fills the picker and needs a cleanup. The prompt repeats the worker's transcript, which the archive already holds: measure the size per cycle first, and if it outgrows "small enough to copy whole", keep the prompt without the transcript part and name the worker copy and entry range it held. Then let `judge-replay` read the archived prompt where one exists, and price the judge from the archived reply's usage. Update that decision entry to say the judge's runs are archived too.
### 304. 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.
Today `review-replay` and `judge-replay` leave no transcript: both run claude through `claude_reply` in `bin/claude_code/reply.py`, whose `--no-session-persistence` makes Claude Code write no session file, as item 303 describes for the judge. A replay decides which rung a review pass or the judge may run on (`routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows…`, and the judge's rung on `JUDGE_REPLAYED`), so the runs behind a routing decision can't be read again, re-priced or re-scored once the decision is questioned. Goal 3 asks for the transcripts of unattended runs, the bench's included, to be backed up; `workflow-bench/bench.py` already keeps its claude stream in `logs/`.
Unlike the judge, a replayed reviewer uses tools over several turns, so its transcript is more than its prompt and reply. Recommended: have `claude_reply` take `--output-format stream-json --verbose` in place of `json`, keep `--no-session-persistence`, write the stream where the replay keeps its result, and read the reply from the stream's last `result` event. That also gives item 303 the judge's stream for free, so build on 303's archive layout and do both callers through the one runner.
### 306. 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.
Measured on 2026-11-11: loop-claude's archive is 6.3 GB (12,721 files from October alone, 0.84 GB older than 30 days), and `~/.local/state/larv-review/` is 997 MB, 984 MB of it under `code/`, with no pruning: `skills/larv-review/SKILL.md` → "Reports" keeps every folder after the merge, because `review-replay` replays rounds from them. The largest archived worker transcript, 23.4 MB, gzips to 9.1 MB at level 6. The disk holds 65 GB free today.
Write the strategy as a decision, then build it:
- **Backup.** Item 1 waits on ai-sandbox's data volume backup; check that both `~/.claude/loop-claude-transcripts` and `~/.local/state/larv-review` sit on that volume, since the review folders live outside `~/.claude`.
- **Retention.** Keep everything: the archive is the evidence every routing and replay decision rests on. Compress entries older than a threshold (such as 30 days, or once a chunk is finished and measured) with a format the tools read transparently, such as zstd. Compress, verify the round trip, then remove the original, never the reverse; a failure keeps the original and stops, as a failed archive does.
- **Readers.** `bin/transcript_archive`, `routing_figures`, `score-outcomes`, `review-replay`, `judge-replay` and `reading-cost` must read compressed entries; test each on one.
- Revise `loop-claude: the archive keeps the raw transcript`, whose validity is "while transcripts stay small enough to copy whole".
### 302. 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.
@@ -76,47 +244,13 @@ Recommendation: a floor item's tagline opens with one fixed phrase, `Reach the c
The same chunk names the phrase where a floor item is filed: `skills/larv-review/SKILL.md` → "Floor item", the `Next:` lines `floor_step` prints, and `larv-review --help` (`bin/larv_review/main.py`, lines 35 and 89). It rewords open floor item 300's tagline to open with the phrase, and updates the tests in `bin/larv_review/test_larv_review.py` that use floor taglines (lines 120, 361, 435, 537), adding one where a tagline quotes the floor mid-sentence and is due no run.
### 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.
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.
### 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.
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.
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.
### 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.
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.
### 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.
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.
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.
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/`, `AGENTS.md`, `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.
### 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.
In 0.7.0's 35 chunks, workers made 65 `tea api` calls in 26 chunks, mostly polling commit status and trying merge methods in turn, and ran 25 `until … sleep` loops that took 1,744 seconds. `chunk-pr merge` takes `--gate-passed` on the worker's word; waiting for the required checks itself makes that flag a fact, not a claim. This is the kind of step item 284 files, and can count as its first.
### 299. 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.
The judge's verdict kind is the one judge decision that item 297 leaves an LLM. No single rule found so far separates interrupts: a "?" in the worker's final message appears in 48 interrupts and misses 66. A smaller LLM already failed the replay (`docs/decisions.md` → `routing: on a model judge-replay covered, …`: Sonnet returned another kind on 3 interrupts, Haiku missed 7). Untested are combined code rules, a decision table, and a small classifier trained and run on this machine on the archived verdicts (372 finished, 234 interrupt, 42 unfinished, 20 quoted). Run each offline, nothing sent to an outside service (goal 4), and count disagreements by kind; the bar is zero missed interrupts. A hosted decision model is out of scope, since it would send transcripts to an outside service.
### 298. 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.
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. It waits for item 297, which moves the judge's factual fields into code, since that shrinks the prompt first and changes what this cut measures. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster.
### 287. 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.
Today the helpers live in two tools. `Forge` is defined in `bin/chunk_preflight/gathered.py` and imported by `bin/chunk_preflight/choices.py`, `bin/chunk_preflight/facts.py`, `bin/chunk_preflight/main.py` and `bin/chunk_pr/main.py`, and again through `choices` by `bin/deploy_release/forge.py`. `forge_of` lives in `choices.py`, which `bin/chunk_pr/main.py`, `bin/deploy_release/cut.py` and `bin/larv_review/reviewer_header.py` import. `open_pull`, `runner` and `gitea` live in `bin/deploy_release/forge.py`, which `bin/chunk_pr/main.py` and `bin/larv_review/reviewer_header.py` import. So `deploy_release` imports `chunk_preflight`, and `chunk_pr` and `larv_review` import both.
Both comprehension seats of PR #453's paired ruling (2026-11-09) named this web as a place that cost them time, and neither saw a reason for it: a second forge would need edits in `chunk_preflight`, `deploy_release`, `chunk_pr` and `larv_review`.
Put the seven helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `AGENTS.md` and `docs/decisions.md` for a mention of where a helper lives, and update it.
Put the seven helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `docs/decisions.md` for a mention of where a helper lives, and update it.
### 288. 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.
@@ -152,6 +286,10 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan
Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it.
### 321. 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.
lilleman, 2026-11-11: item 318's new bar is a risk, so check it closely a release later. Compare the first 20 chunks reviewed on each newly qualified rung with the 20 before: review rounds past the first, 🔴 and 🟡 per chunk, misread findings, and later fixes that `score-outcomes` counts (defects that escaped review). Revert a pass to the project's rung where any of those worsened beyond the spread of the 20 before.
### 273. 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.
`docs/decisions.md` → `routing: one ladder…` records why lilleman kept the steps on 2026-11-08. Of the 36 chunks it measured, 1 scored an E + I of 6 or more and none 7 or more, so the steps for 6 to 8 are untested. Start once `score-outcomes` shows 10 finished chunks with an E + I of 6 or more. Then read its rank correlation for E + I, and the routed-chunks table of `routing-figures.md` in loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Propose new steps to lilleman, whose call they are.
@@ -199,6 +337,10 @@ Scored L 4 because the refactor touches several components that hold known defec
Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. By 2026-11-10 general-purpose was the second-largest spend, $585 of about $2,385, and by transcript size about two thirds of it were seats (291 launches), then 177 security passes. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/chunk.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with.
### 323. Count a release review as landed once its pull request has merged, whatever its commits are titled.
`release_reviewed` in `bin/release_plan/release_standing.py` counts a release review only by a commit titled `Release review of <release>` on the default branch. In a replay of archived interrupts (`judge-field-trials/`), in two projects whose release review had merged, the default branch held no such commit, so `chunk-preflight` and routing read ReviewDue, and the next loop would run the release review again. `skills/larv-review/SKILL.md` opens the review's branch with an empty commit of that title, but a worker may skip it, and a rebase or squash merge, which `chunk-pr` uses where the forge allows no merge commit, may drop it. Detect the review by something every merge method keeps, and check the fix against both projects' histories. Until then the judge keeps `release_ready` (docs/decisions.md → `routing: loop-claude reads the items a chunk takes …`).
### 149. 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.
A release's capacity is a sum of its items' cost, as the formula counts it. Each project states its own; the human sets the first value per project. Nothing is deleted by score.
@@ -273,6 +415,10 @@ Weigh the widely used tmux-resurrect and tmux-continuum plugins against a script
Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading-cost` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id `docs/reading-cost.md` holds, so give it a way to match a figure written under the old name.
### 324. Count in the routing figures the finished chunks whose worker wrote no `Chunk items:` line.
`docs/decisions.md` → `routing: loop-claude reads the items a chunk takes …` holds only while workers write the line when asked, and nothing counts a chunk whose worker skipped it. There loop-claude scores no item beyond the one the chunk was routed on, so the route holds, and loop-inbox lists only that item. Count in `bin/routing_figures/`, beside the chunks counted, those whose worker's transcript holds no such line, so the human sees when the decision's premise stops holding.
### 187. 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.
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/chunk.py`), so neither sees the report reads. Found by the architecture review of PR #310.
@@ -285,10 +431,6 @@ The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09-
`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308.
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
Found by review of PR #317. The block, `.gitignore:17-142` on 2026-11-10, is out of order in several places: `!bin/chunk-preflight` sits below `!bin/chunk_pr/`, and `!bin/loop-inbox` below `!bin/loop_claude/`, though `-` sorts before `_`. `LC_ALL=C sort -c` on the block names the first one. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
### 193. 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.
Found by review of PR #317. `bin/release_plan/ranking.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.
@@ -297,10 +439,6 @@ Found by review of PR #317. `bin/release_plan/ranking.py`'s `readme_goals` write
Found by review of PR #317. The black-box test, `bin/loop_claude/test_black_box.py:609`, not the unit test of the same name in `test_loop_claude.py`, which runs on a fake clock, sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
### 202. Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.
Found by the prose review of PR #329. `prose.md` opens by calling itself the full rules that `CLAUDE.md` → "Prose" keeps a core of, yet it lacks that rule, so a prose reviewer whose bar is the standards files never sees it.
### 265. 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.
No record holds these waits today. An outcomes file holds verdicts, stops, step-ups and the judge's cost (`bin/transcript_archive/outcomes.py`), and `~/.local/state/run-heavy/` holds only the slots' lock files. loop-claude waits out a usage limit and low memory in `bin/loop_claude/cycle/retry.py`; run-heavy waits for a slot in `bin/run_heavy/`. A heavy slot's wait happens inside a worker's Bash call, so loop-claude doesn't see it; run-heavy would write it where the archive can find it.
@@ -309,10 +447,6 @@ No record holds these waits today. An outcomes file holds verdicts, stops, step-
The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file.
### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker or the judge.
### 197. 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`.
`bin/loop_effects/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. loop-claude asks two questions at its terminal. `effects.input` reads the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. `effects.input_or` reads the interrupt's answer, in `cycle/interrupt.py`'s `first_answer`, straight from stdin, since it also watches loop-inbox. Importing `readline` in `effects.py` gives `input` line editing, at two costs; `input_or` would also need to read through `input` while it watches. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
+2
View File
@@ -0,0 +1,2 @@
# mutate-changes runs mutmut from this folder, since the tests here import their modules from it.
[mutmut]