Compare commits

...

126 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
lilleman 1fa03973a3 Plan item 302: call a scoring run only for an item that targets the comprehension floor
CI / tests (pull_request) Successful in 2m2s
2026-11-11 13:59:40 +01:00
lilleman 329f0fd3a0 Record the comprehension check: PR #475 at 52da15e means 6.38 overall, run late for item 301; refresh floor item 300
CI / tests (pull_request) Successful in 2m3s
2026-11-11 13:56:30 +01:00
lilleman 52da15ea2b Answer prose round 1: 0 🔴, 3 🟡 (0 misread); reword the paragraph, keep the floor entry's body, say no ruling blocks either
CI / tests (pull_request) Successful in 2m3s
2026-11-11 13:46:27 +01:00
lilleman 09caf3576f Answer stability round 1: 0 🔴, 1 🟡 (0 misread); move the 2026-11-11 paragraph to the end of the entry 2026-11-11 13:46:27 +01:00
lilleman 7fb019914e Reword the blocks-no-merge decision titles to say no score blocks a merge
CI / tests (pull_request) Successful in 2m3s
2026-11-11 13:43:15 +01:00
lilleman 5c08bc34d6 Plan item 301: reword the blocks-no-merge decision titles, a question for the human
CI / tests (pull_request) Successful in 2m10s
2026-11-11 00:26:17 +01:00
lilleman 0fdaf926c5 Finish item 296
CI / tests (pull_request) Successful in 2m50s
2026-11-11 00:22:33 +01:00
lilleman 87273e94a4 Record the comprehension check: PR #473 at 13d1550 means 6.00 overall; file floor item 300
CI / tests (pull_request) Successful in 2m22s
2026-11-11 00:12:57 +01:00
lilleman 13d1550299 Name plan_reasons' first argument ref, since it can be a commit, and pin the emptied-release words in SKILL.md
CI / tests (pull_request) Successful in 2m7s
2026-11-11 00:11:20 +01:00
lilleman 58402083cb Name the second run's title only where two runs are owed
CI / tests (pull_request) Successful in 2m13s
2026-11-11 00:06:23 +01:00
lilleman 567ff471ec Answer stability round 2: 0 🔴, 3 🟡 (0 misread); say the gate reads the checkout's todo.md, and test main's runs, and an unreadable plan
CI / tests (pull_request) Successful in 2m20s
2026-11-11 00:05:20 +01:00
lilleman 538fbc52b9 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword the help, SKILL.md and docstrings
CI / tests (pull_request) Successful in 2m20s
2026-11-10 23:59:10 +01:00
lilleman ac98e0e4a7 Answer product-owner round 1: 0 🔴, 4 🟡 (0 misread); the merge-base fix answers the behind-main and no-table findings, the opt-out check moves into plan_reasons, and the title and AGENTS.md lines that say the check blocks no merge stay: the decision's body bars only a score from blocking 2026-11-10 23:59:10 +01:00
lilleman e69eb982bc Answer stability round 1: 1 🔴, 6 🟡 (0 misread); read the owed runs against the merge base and committed history, skip a project with no plan table, cover the surviving mutants 2026-11-10 23:59:10 +01:00
lilleman 1c6e04c8b8 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-10 23:45:35 +01:00
lilleman 92867f64cd Refuse chunk-pr merge while a scoring run the plan calls is unrecorded, and call one for a release cut with none
CI / tests (pull_request) Successful in 2m15s
2026-11-10 23:45:06 +01:00
lilleman 0301ca01c4 Move items 284 and 270 to 0.8.0
CI / tests (pull_request) Successful in 2m34s
2026-11-10 23:33:07 +01:00
lilleman 3ee136ae44 Drop item 269: answered, a verdict costs about $0.76 at every rung, and item 298 cuts the judge's cost
CI / tests (pull_request) Successful in 2m21s
2026-11-10 23:26:16 +01:00
lilleman 5b230fd013 Plan items 293 to 299 for 0.8.0: mutation tests before review, commit-time file rules, judge facts in code, a smaller judge prompt, waiting in chunk-pr, the owed scoring run and judge-verdict replays; raise 264, 268 and 270 2026-11-10 23:26:10 +01:00
lilleman d2ad46c9cb Cite the Working loop heading before its bold lead in item 292
CI / tests (pull_request) Successful in 2m22s
2026-11-10 23:08:43 +01:00
lilleman 03ee7a4a75 Answer prose round 1: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Failing after 2m15s
2026-11-10 23:04:04 +01:00
lilleman 79d764e682 Shift 0.8.0 to 0.9.0 and 0.9.0 to 0.10.0, plan the Fable 5.2 ladder for 0.8.0, and refresh ten stale details
CI / tests (pull_request) Failing after 2m34s
2026-11-10 23:03:05 +01:00
lilleman 6440824f27 Drop item 52: obsolete 2026-11-10 23:03:05 +01:00
lilleman e10e301582 Cut release 0.7.0
CI / tests (pull_request) Successful in 2m23s
2026-11-10 22:51:39 +01:00
lilleman 1bb740a47f Record the comprehension check: paired ruling better against 98b7bfd
CI / tests (pull_request) Successful in 2m17s
2026-11-10 22:39:39 +01:00
lilleman 05539e2e0d Merge origin/main
CI / tests (pull_request) Successful in 2m33s
2026-11-10 22:32:50 +01:00
lilleman 998e295ef9 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); docstrings say what the code does, and each fact sits in one place 2026-11-10 22:32:49 +01:00
lilleman f2fef1d32d Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-10 22:31:59 +01:00
lilleman 7d187d22f3 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); test that a reload refuses a route with a top-level effort 2026-11-10 22:31:59 +01:00
lilleman 493a652499 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); check the names the trials read through a module alias too 2026-11-10 22:22:27 +01:00
lilleman 12d70586ed Answer principles round 1: 0 🔴, 1 🟡 (0 misread); test the trials' imports from bin, pass one loop value through loop/, type the Exempt reasons
CI / tests (pull_request) Successful in 2m20s
2026-11-10 22:20:48 +01:00
lilleman ce941388a2 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-10 22:11:28 +01:00
lilleman b6038c4e41 Move item 291 to 0.8.0
CI / tests (pull_request) Successful in 2m13s
2026-11-10 22:06:17 +01:00
lilleman a875e11e00 Answer architecture round 2: 0 🔴, 0 🟡 (0 misread); every round 1 answer resolves its finding 2026-11-10 22:04:59 +01:00
lilleman 70a1b95086 Answer architecture round 1: 0 🔴, 4 🟡 (0 misread); move the shared loop state out of loop_claude, split ranking and routing, give the reviewer rung one rule
CI / tests (pull_request) Successful in 2m14s
2026-11-10 22:03:16 +01:00
lilleman b3d4b8fe27 File item 291: an exception in Sane defaults for a no-config library's clock and randomness
CI / tests (pull_request) Successful in 2m17s
2026-11-10 21:40:07 +01:00
lilleman 8a80d452f2 Record reading cost 2026-11-10 21:38:39 +01:00
lilleman ce126aa1aa Release review of 0.7.0
CI / tests (pull_request) Successful in 2m14s
2026-11-10 21:38:30 +01:00
lilleman 055ee752ba Move item 1 to 0.9.0, as the human chose
CI / tests (pull_request) Successful in 2m31s
2026-11-10 21:28:00 +01:00
146 changed files with 4775 additions and 1324 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"]
}
+20 -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,19 +51,30 @@
!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-inbox
!bin/loop_effects/
!bin/loop_effects/*.py
!bin/loop_inbox/
!bin/loop_inbox/*.py
!bin/loop_state/
!bin/loop_state/**/
!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/
@@ -94,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/
@@ -106,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
@@ -133,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 blocks no 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 blocks no 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
+15 -1
View File
@@ -1,6 +1,20 @@
# 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
- README's test, CI and mutation-test commands now have their own section, README → Test.
- `rule-hook overrides` now lists the chunk's overrides when a file or folder shares the branch's name. It used to exit saying it could not read the reflog.
+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/`.
+17 -20
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,25 +119,27 @@ 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/`, `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`.
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
- `judge_replay` imports `loop_claude`'s judge.
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_inbox` imports `loop_claude`'s question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), its effects and paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes loop-inbox too.
- `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.
- `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. 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.
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, which `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item` import).
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`.
- `repo_checks/` tests the repo itself.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
- `test_env.py` serves the tests.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
@@ -141,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)
+2 -2
View File
@@ -5,11 +5,11 @@ import re
import typing
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
from release_plan.todo_table import Item
from release_plan.todo_table import Exempt, Item
from review_rules.round_titles import title_counts
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
FIXES = ("defect", "security")
FIXES: tuple[Exempt, ...] = ("defect", "security")
HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@")
BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+")
+5 -5
View File
@@ -1,10 +1,10 @@
from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes
from branch_chunks.cut import BranchChunk, cut_branch, LOG, plan_revisions, shipped_by
from failure import Failure
from git_cli.git_repo import Run, text_at
from git_cli.git_repo import Git, text_at
def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
def branch_chunks(default: str, run: Git) -> list[BranchChunk] | Failure:
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
run must run git in the checkout's top: the diff names each path from the top, while blame and a pathspec read a path from the current directory."""
@@ -23,7 +23,7 @@ def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
def plans_at(revisions: list[str], run: Git) -> dict[str, str] | Failure:
"""todo.md's text at each revision, empty where the revision holds none."""
plans = {}
for revision in revisions:
@@ -34,7 +34,7 @@ def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
return plans
def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
def traces(changes: list[FixingChange], run: Git) -> list[Traced] | Failure:
"""The commits traced_to traces for each change."""
found = []
for change in changes:
@@ -45,7 +45,7 @@ def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
return found
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
def traced_to(before: str, tip: str, run: Git) -> set[str] | Failure:
"""The commits that last changed each line of a chunk's work that the change from before to tip removes or rewrites."""
# The prefixes and options keep the checkout's diff config out of the output. Only hunk headers, paths and commits are read, so a file's text that is not UTF-8 is replaced.
diff = run("diff", "-U0", "--inter-hunk-context=0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip, errors="replace")
+8 -1
View File
@@ -18,7 +18,9 @@ merge merges the pull request, and only while its head is still the commit ch
push after the gate is never merged. It takes the first method the repository allows of:
a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash.
GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the
merge gate passed on that commit; without it, chunk-pr refuses.
merge gate passed on that commit; without it, chunk-pr refuses. It also refuses where
`larv-review scoring-run-owed` exits 1, because the chunk owes a scoring run it has not
recorded; no flag waives that.
clean acts once the forge reports the branch's pull request merged at the commit checked out,
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
default branch, removes the chunk's worktree, then deletes the local branch; origin's
@@ -32,6 +34,7 @@ It prints what it did, exit 0, or why it failed, exit 1.
import dataclasses
import json
import os
import pathlib
import sys
import typing
@@ -40,6 +43,7 @@ from chunk_preflight.gathered import Forge
from chunk_preflight.choices import forge_of
from deploy_release.forge import gitea, merged_pull, open_pull, Run, runner
BIN = pathlib.Path(__file__).resolve().parents[1]
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean"
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
@@ -157,6 +161,9 @@ def merged(run: Run) -> str | Failure:
if isinstance(found, Failure):
return found
forge, number, head = found
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
method = merge_method(forge, run)
if isinstance(method, Failure):
return method
+10 -1
View File
@@ -21,6 +21,7 @@ GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid,
TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]
GH_SETTINGS = ["gh", "repo", "view", "--json", "mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed"]
TEA_SETTINGS = ["tea", "api", "repos/{owner}/{repo}"]
OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scoring-run-owed"]
class Checkout:
@@ -58,7 +59,7 @@ class Checkout:
def acted(self) -> list[list[str]]:
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS]
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED]
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
@@ -137,6 +138,14 @@ class Merge(unittest.TestCase):
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.ran, [])
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
for origin in (GITHUB, GITEA):
with self.subTest(origin=origin):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(checkout.acted(), [])
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (merge).")
+9 -12
View File
@@ -46,14 +46,11 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
class Git(typing.Protocol):
"""Runs git as `git` does."""
"""Runs git as `git` does: git itself, Effects.git, or a functools.partial of either that binds the checkout."""
def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure: ...
# Runs git with the given arguments, in the checkout and with the options its caller bound, as functools.partial(git, cwd=...) does.
Run = typing.Callable[..., str | Failure]
def top() -> str | Failure:
found = git("rev-parse", "--show-toplevel")
@@ -109,24 +106,24 @@ def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failu
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> int | Failure:
def commits_since(tag: str | None, branch: str, cwd: str | None = None, run: Git = git) -> int | Failure:
"""How many commits branch holds after tag, or holds in all where tag is None; read in cwd, else in the current directory."""
count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
count = run("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
return count if isinstance(count, Failure) else int(count)
def commit_exists(commit: str, cwd: str | None = None) -> bool:
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
def commit_exists(commit: str, cwd: str | None = None, run: Git = git) -> bool:
return not isinstance(run("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
def file_at(revision: str, path: str, cwd: str | None = None, run: Git = git) -> str | Failure:
"""A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
if not commit_exists(revision, cwd):
if not commit_exists(revision, cwd, run):
return ""
return text_at(revision, path, functools.partial(git, cwd=cwd))
return text_at(revision, path, functools.partial(run, cwd=cwd))
def text_at(revision: str, path: str, run: Run) -> str | Failure:
def text_at(revision: str, path: str, run: Git) -> str | Failure:
"""A file's text at a commit, as run reads it; empty where the commit holds no such file. ls-tree reads path from the directory run runs in, and show from the checkout's top."""
listed = run("ls-tree", "--name-only", revision, "--", path)
if isinstance(listed, Failure):
+1 -1
View File
@@ -6,6 +6,6 @@ import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from judge_replay import main
from loop_claude.effects import system_effects
from loop_effects.effects import system_effects
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
+1 -1
View File
@@ -32,7 +32,7 @@ from rung_replay.command import arguments_or_exit, down_from, failed, limited_ex
from loop_claude.cycle.judge import Brief, judge_once
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
from transcript_archive.project_key import checkout_of
from loop_claude.effects import Effects
from loop_effects.effects import Effects
from failure import Failure
from rung_replay.search import first_reply, replayed
from claude_code.reply import Limited
+11 -11
View File
@@ -11,7 +11,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
from loop_claude.effects import Effects
from loop_effects.effects import Effects
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from judge_replay import main
@@ -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("[")
+2 -2
View File
@@ -10,7 +10,7 @@ from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
from larv_review.scoring import floor_step, means, under_floor
from release_plan import ranking
from release_plan import plan_file
from records.file_writes import replace_file
@@ -70,7 +70,7 @@ def rerank() -> Failure | None:
if isinstance(checkout, Failure):
return checkout
todo = pathlib.Path(checkout, "todo.md")
ranked = ranking.rank_file(todo)
ranked = plan_file.rank_file(todo)
if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
if ranked.under_bar:
+27 -5
View File
@@ -1,8 +1,8 @@
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt.
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]
The comprehension check records how hard a project is to read, two ways, and blocks no merge. In a
The comprehension check records how hard a project is to read, two ways, and no score blocks a merge. In a
paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better,
same or worse, overall and on each dimension. In a scoring run, four seats score the project from 1
to 10. Each seat names the places it found hard.
@@ -11,7 +11,7 @@ Run it inside a project checkout or one of its worktrees. Each command but revie
record-ruling, places and agreement first fetches origin, when the checkout has that remote, and
takes origin's default branch, or else the local main or master, as the default branch. When the
fetch fails, round-count and reviewer-header read origin as last fetched and say so on stderr; the
other three exit 1.
other four exit 1.
The history is docs/comprehension-history.md in the checkout.
review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its
@@ -36,6 +36,18 @@ an item whose tagline names the comprehension floor. It is also due when the chu
with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
A chunk is also due one while no scoring run in the default branch's history is newer than the
commit of its second-newest v* tag, so a release cut unmeasured is caught up by the next chunk. A project whose
docs/decisions.md opts out of the comprehension check is never due one.
scoring-run-owed prints `No scoring run owed.` or exits 1 naming the runs the chunk owes and has
not recorded. chunk-pr merge runs it and refuses to merge on exit 1, so a due line read earlier in
the chunk can't stand in for it. It applies needs-scoring-run's rule to the checkout's todo.md and the committed history, against the
merge base with the default branch, so a default branch that has moved on adds nothing: the items
the merge base's todo.md holds and the checkout's does not count as shipped. A chunk that empties a
release owes two runs, any other due chunk one. The chunk has recorded the scoring runs that its
committed docs/comprehension-history.md holds beyond the merge base's. A project that opts out or
has no todo.md items table owes none.
A second scoring run of one head names itself `<PR or branch> rerun at <commit>`, so record-scoring
does not refuse it as a repeat of the first.
@@ -110,7 +122,7 @@ missing.
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
needs-scoring-run or record-scoring, or cannot read or write the history, todo.md or the review
needs-scoring-run, scoring-run-owed or record-scoring, or cannot read or write the history, todo.md or the review
folder.
"""
import pathlib
@@ -126,12 +138,13 @@ from larv_review.history_changes import history_changes
from review_rules.review_folder import made_review_folder
from larv_review.ruling_base import measured_commit
from larv_review.agreement import MIN_PAIRS
from larv_review.owed import owed_scoring_run
from review_rules.review_passes import PASSES, REVIEWERS
from larv_review.plan import plan_reasons
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
from larv_review.reviewer_header import reviewer_header
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]"
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]"
def main(argv: list[str]) -> int:
@@ -147,6 +160,8 @@ def main(argv: list[str]) -> int:
done = with_default_branch(round_count, stale_ok=True)
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
elif command == "scoring-run-owed" and not given:
done = with_default_branch(owed, stale_ok=False)
elif command == "record-ruling" and len(given) == 1:
done = record_ruling(pathlib.Path(given[0]))
elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]):
@@ -223,6 +238,13 @@ def cap_note(count: int, most: int) -> str:
return f", {'at' if count == most else 'past'} the cap: no more rounds"
def owed(default: str) -> Failure | None:
unrecorded = owed_scoring_run(default)
if unrecorded is None:
print("No scoring run owed.")
return unrecorded
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
reasons = plan_reasons(default, ids)
if isinstance(reasons, Failure):
+56
View File
@@ -0,0 +1,56 @@
import pathlib
from larv_review.plan import EMPTIED_WORDS, plan_reasons
from review_rules.comprehension_history import entries, HISTORY
from failure import Failure
from git_cli.git_repo import file_at, git, top
from release_plan.todo_table import items, NoItemsTable
def owed_scoring_run(default: str) -> Failure | None:
"""A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none.
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began counts for nothing. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
"""
checkout = top()
if isinstance(checkout, Failure):
return checkout
if not has_plan(checkout):
return None
base = git("merge-base", default, "HEAD", cwd=checkout)
if isinstance(base, Failure):
return base
reasons = plan_reasons(base.strip(), None)
if isinstance(reasons, Failure):
return reasons
if not reasons:
return None
before = file_at(base.strip(), HISTORY, checkout)
if isinstance(before, Failure):
return before
after = file_at("HEAD", HISTORY, checkout)
if isinstance(after, Failure):
return after
return shortfall(reasons, len(scoring_runs(after)) - len(scoring_runs(before)))
def shortfall(reasons: list[str], recorded: int) -> Failure | None:
"""Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all."""
needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1
if recorded >= needed:
return None
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
def has_plan(checkout: str) -> bool:
"""Whether the checkout has a todo.md holding an items table. A file that can't be read counts, so `plan_reasons` reports it."""
try:
return not isinstance(items(pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")), NoItemsTable)
except FileNotFoundError:
return False
except (OSError, UnicodeDecodeError):
return True
def scoring_runs(history: str) -> list[str]:
return [entry.heading for entry in entries(history) if not entry.paired]
+28 -10
View File
@@ -2,28 +2,36 @@ import pathlib
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown
from failure import Failure
from git_cli.git_repo import file_at, top
from larv_review.scoring import FLOOR_ITEM
from release_plan.todo_table import Item, items, NoItemsTable, renames
from release_plan.ranking import OPTED_OUT
from release_plan.release import Release, version
from git_cli.git_repo import top
from larv_review.unmeasured import unmeasured_cut
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release]) -> list[str] | Failure:
# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one.
EMPTIED_WORDS = "with no plan item"
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release], unmeasured: str | None = None) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not.
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none.
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none. A chunk after a release `unmeasured_cut` names is due one too, so a release cut with no scoring run is caught up.
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed_release is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed.
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed_release is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed. unmeasured is `unmeasured_cut`'s answer.
"""
plan = {item.id: item for item in before + after}
if unknown := sorted(set(ships) - set(plan)):
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
shipped = [plan[id_] for id_ in ships]
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if FLOOR_ITEM in item.tagline.lower()]
if unmeasured:
reasons.append(f"follows {unmeasured}")
for release in emptied(before, after, shipped, renamed):
if work_landed(release, shipped, landed_release):
# SKILL.md → "Second run" keys on this wording.
reasons.append(f"leaves release {version(release)} with no plan item")
reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}")
return reasons
@@ -55,12 +63,17 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
return sorted(named - {item.release for item in kept} - renamed)
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
"""Why the plan calls a scoring run, from the default branch's todo.md and the checkout's."""
def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure:
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
checkout = top()
if isinstance(checkout, Failure):
return checkout
held = default_plan(checkout, default)
decisions = file_at(ref, "docs/decisions.md", checkout)
if isinstance(decisions, Failure):
return decisions
if OPTED_OUT.search(decisions):
return []
held = default_plan(checkout, ref)
before = held.todo
if isinstance(before, Failure):
return before
@@ -73,14 +86,19 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
if isinstance(planned, NoItemsTable):
planned = []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
return Failure(f"{ref}'s todo.md: {planned.reason}")
renamed = renames(after)
if isinstance(renamed, Failure):
return Failure(f"the checkout's todo.md: {renamed.reason}")
landed_release = landed_towards(planned, held.cut)
if isinstance(landed_release, Failure):
return landed_release
return scoring_run_due(planned, chunk, ids, landed_release, renamed)
unmeasured = unmeasured_cut(ref, checkout)
if isinstance(unmeasured, Failure):
return unmeasured
if ids is None:
ids = sorted({item.id for item in planned} - {item.id for item in chunk})
return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
def checkout_plan(checkout: str) -> tuple[str, list[Item]] | Failure:
+138 -1
View File
@@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
from larv_review.plan import checkout_plan, landed_towards, plan_reasons, scoring_run_due
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from review_rules import comprehension_history
from larv_review.ruling import counted, ruling, split, surplus, votes
from larv_review.history_commands import decided
@@ -23,6 +23,7 @@ from release_plan.todo_table import Item, items, NoItemsTable
from release_plan.release_standing import LastCut
from larv_review.ruling_base import measured_commit
from larv_review.seats import score_line, scores, seats_file, SeatsFile
from larv_review.owed import shortfall
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
@@ -425,6 +426,20 @@ class LandedTowards(unittest.TestCase):
self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object"))
class Shortfall(unittest.TestCase):
def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self):
self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8"))
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
emptied = ["leaves release 0.1.0 with no plan item"]
floor = ["ships item 2, which names the comprehension floor"]
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
self.assertIn("records 0:", shortfall(floor, -1).reason)
self.assertIsNone(shortfall(emptied, 2))
self.assertIsNone(shortfall(floor, 1))
class LarvReviewTool(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
@@ -502,6 +517,128 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
def test_a_scoring_run_that_a_release_ending_chunk_owes_is_refused_until_the_branch_records_two(self):
rest = ("| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
self.commit("Ship item 1", {"todo.md": todo(*rest)})
owed = self.run_tool("scoring-run-owed")
self.assertEqual(owed.returncode, 1)
self.assertIn("leaves release 0.1.0 with no plan item", owed.stderr)
self.assertIn("records 0:", owed.stderr)
history = "# Comprehension history\n\n" + SCORING
self.commit("Record a run", {"docs/comprehension-history.md": history})
self.assertIn("records 1:", self.run_tool("scoring-run-owed").stderr)
self.commit("Record a rerun", {"docs/comprehension-history.md": history + "\n" + SCORING.replace("PR #1 at", "PR #1 rerun at")})
done = self.run_tool("scoring-run-owed")
self.assertEqual((done.returncode, done.stdout), (0, "No scoring run owed.\n"), done.stderr)
def test_a_scoring_run_the_floor_calls_is_owed_once(self):
row = "| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
other = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
self.commit("Plan the floor item", {"todo.md": todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", other)})
self.git("push", "-q", "origin", "HEAD:main")
self.commit("Ship it", {"todo.md": todo(row, other)})
self.assertIn("names the comprehension floor", self.run_tool("scoring-run-owed").stderr)
self.commit("Record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 0)
ROW = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
def ship_item_1(self):
self.commit("Ship item 1", {"todo.md": todo(self.ROW)})
def test_no_scoring_run_is_owed_where_none_is_due(self):
self.commit("Ship item 2", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", self.ROW)})
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
self.ship_item_1()
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
def test_a_run_counts_only_as_committed_and_a_ruling_is_no_run(self):
self.ship_item_1()
(self.checkout / "docs").mkdir()
(self.checkout / "docs" / "comprehension-history.md").write_text("# Comprehension history\n\n" + SCORING)
self.assertIn("records 0", self.run_tool("scoring-run-owed").stderr)
self.commit("Record a ruling", {"docs/comprehension-history.md": "# Comprehension history\n\n" + paired("2026-10-08T12:00:00Z", "better")})
self.assertIn("records 0", self.run_tool("scoring-run-owed").stderr)
def test_a_project_that_opts_out_owes_none_and_is_never_due_one_but_a_branch_cannot_opt_itself_out(self):
self.ship_item_1()
self.commit("Opt out on the branch", {"docs/decisions.md": "## review opt-out: the comprehension check\n\n2026-11-10, lilleman.\n"})
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
self.git("switch", "-q", "main")
self.commit("Opt out", {"docs/decisions.md": "## review opt-out: the comprehension check\n\n2026-11-10, lilleman.\n"})
self.git("push", "-q", "origin", "HEAD:main")
self.git("switch", "-q", "chunk")
self.git("merge", "-q", "main")
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "No scoring run due.\n")
def test_a_project_with_no_plan_or_no_items_table_owes_none(self):
self.ship_item_1()
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
self.commit("Reshape the plan", {"todo.md": "# Plan\n"})
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
self.git("rm", "-q", "todo.md")
self.commit("Drop the plan")
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
(self.checkout / "todo.md").write_bytes(b"\xff\xfe")
self.git("add", "todo.md")
self.commit("Break the plan")
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1, "a plan that can't be read is no plan the gate may skip")
def test_a_default_branch_that_moved_on_since_the_branch_began_adds_no_owed_run(self):
self.git("switch", "-q", "main")
self.commit("Plan release 0.3.0", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", self.ROW, "| 4 | 0.3.0 | | **Later.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"), "docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
self.git("push", "-q", "origin", "HEAD:main")
self.git("switch", "-q", "chunk")
self.commit("Do some work")
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
self.ship_item_1()
self.commit("Ship item 1 and record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("PR #1", "PR #7")})
self.assertIn("owes 2 scoring runs and the branch's committed history records 1:", self.run_tool("scoring-run-owed").stderr, "main's own run is no credit to the branch")
def release(self, tag, date, files=None):
"""Cut tag on the default branch at a commit dated date."""
self.env["GIT_COMMITTER_DATE"] = date
self.addCleanup(self.env.pop, "GIT_COMMITTER_DATE", None)
self.commit(f"Release {tag}", files)
self.git("tag", tag)
self.git("push", "-q", "origin", "HEAD:main")
def test_a_release_cut_with_no_scoring_run_since_the_one_before_it_calls_one_and_a_later_run_ends_that(self):
self.release("v0.0.1", "2026-10-09T12:00:00Z")
self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n")
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
self.commit("Record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING + "\n" + SCORING.replace("PR #1 at", "PR #2 at")})
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 0)
self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("2026-10-08T12", "2026-10-20T18")})
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
def test_a_run_ends_an_unmeasured_release_only_when_it_is_a_scoring_run_newer_than_the_tag_with_a_time_that_reads(self):
self.release("v0.0.1", "2026-10-09T12:00:00Z")
history = "# Comprehension history\n\n"
due = "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n"
self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": history + paired("2026-10-21T12:00:00Z", "better") + "\n" + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-09T12:00:00Z")})
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, end nothing")
self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": history + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-30")})
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse ends nothing")
def test_an_unmeasured_release_is_judged_by_the_default_branch_alone_and_names_a_release_over_its_candidate(self):
self.release("v0.0.1", "2026-10-09T12:00:00Z")
self.release("v0.0.2-rc.1", "2026-10-10T12:00:00Z")
self.release("v0.0.2", "2026-10-20T12:00:00Z")
self.git("switch", "-q", "-c", "side")
self.commit("Tag a side branch")
self.git("tag", "v0.9.0")
self.git("switch", "-q", "chunk")
self.commit("Record a run on the branch", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("2026-10-08T12", "2026-10-25T12")})
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.2-rc.1.\n")
def test_one_release_alone_calls_no_scoring_run_for_lacking_one(self):
self.release("v0.0.1", "2026-10-09T12:00:00Z")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
def test_calls_a_scoring_run_for_a_deferred_release_and_none_for_one_the_checkouts_plan_marks_renamed(self):
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
+36
View File
@@ -0,0 +1,36 @@
import datetime
from review_rules.comprehension_history import entries, HISTORY
from failure import Failure
from git_cli.git_repo import file_at, git
def unmeasured_cut(default: str, checkout: str) -> str | None | Failure:
"""Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's history is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one.
The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run.
A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse counts for nothing, so the run is asked for again.
"""
# Sorts v1.0.0-rc.1 below v1.0.0, as release.newest_tag does.
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname", cwd=checkout)
if isinstance(tags, Failure):
return tags
newest, earlier, *_ = [*tags.split(), None, None]
if earlier is None:
return None
since = git("log", "-1", "--format=%ct", earlier, cwd=checkout)
history = file_at(default, HISTORY, checkout)
if isinstance(since, Failure) or isinstance(history, Failure):
return since if isinstance(since, Failure) else history
if any(at > int(since) for at in (seconds(entry.time) for entry in entries(history) if not entry.paired)):
return None
return f"{newest}, cut with no scoring run since {earlier}"
def seconds(heading_time: str) -> float:
"""A history heading's UTC time as seconds since the epoch; 0 where it doesn't parse."""
try:
return datetime.datetime.strptime(heading_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=datetime.timezone.utc).timestamp()
except ValueError:
return 0
+2 -1
View File
@@ -6,7 +6,8 @@ import sys
LAUNCHER = pathlib.Path(__file__).resolve()
sys.path.insert(0, str(LAUNCHER.parent))
from loop_claude import effects, paths
from loop_effects import effects
from loop_claude.loop import main
from loop_state import paths
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
+1 -1
View File
@@ -1,4 +1,4 @@
"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/usage.py's help).
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, project/ reads a checkout's files, and waiting/ shows a question to loop-inbox. Each module at this level is imported by more than one package, and loop-inbox imports several. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, and project/ reads a checkout's files. The files it shares with loop-inbox live in bin/loop_state/, and its effects in bin/loop_effects/. Each module at this level is imported by more than one package, or by a module at this level that is. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
"""
+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 ()
+14 -9
View File
@@ -4,16 +4,17 @@ import sys
import typing
import uuid
from loop_claude.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
from loop_claude.effects import Effects, POLL_SECONDS, say
from loop_state.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, POLL_SECONDS, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from loop_claude.waiting.listing import listed, shown
from loop_claude.waiting.talk import make_way, TALK
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()
+37 -63
View File
@@ -5,13 +5,11 @@ import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects
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
+15 -13
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),
))
@@ -61,7 +63,7 @@ def review_launches(route: Route, project: Rung | None) -> list[str]:
if project is None:
return []
choice = chosen(project, route)
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice, project)]
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice)]
def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
@@ -74,19 +76,19 @@ def planning_launch(route: Route, project: Rung) -> list[str]:
return [f"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 {project.model} <L>` prints."] if position(route.rung) < position(project) else []
def markdown_launch(choice: ReviewChoice, project: Rung) -> list[str]:
"""Where the reviewers run above the project's rung, the sentence that a branch changing only Markdown no agent follows reviews on the project's rung, as rule-hook's reviewer-rung allows. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`"""
if position(choice.reviewers) <= position(project):
def markdown_launch(choice: ReviewChoice) -> list[str]:
"""The sentence that names choice.markdown_only, the rung a reviewer runs on where the branch changes only Markdown no agent follows. It is empty where that rung is the reviewers'. rule-hook's reviewer-rung holds a launch to the same rung. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`"""
if choice.markdown_only == choice.reviewers:
return []
files = ", ".join(f"`{name}`" for name in INSTRUCTION_FILES)
folders = listed([f"`{folder}/`" for folder in INSTRUCTION_FOLDERS], "or")
return [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {project.agent_args()}."]
return [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {choice.markdown_only.agent_args()}."]
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]:
+1 -1
View File
@@ -1,6 +1,6 @@
import typing
from loop_claude.effects import Effects, say
from loop_effects.effects import Effects, say
from failure import Failure
from claude_code.reply import Limited
from loop_claude.stop import Stop
+19 -9
View File
@@ -6,8 +6,9 @@ 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_claude.effects import Effects, say
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
@@ -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
@@ -86,10 +89,15 @@ def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop:
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
path = transcript_file(session)
failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now(), lambda text: say(text, effects)) if path else None
failure = archived(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects) if path else None
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects) -> Failure | None:
"""transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it."""
return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects))
def judge_of(cycle: Cycle) -> Rung:
"""The judge's rung, which the archive names beside each verdict."""
return judge_rung(cycle.judge_model, cycle.route)
@@ -139,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)
@@ -157,13 +167,13 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> str:
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from README.md or the records."""
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
return outcomes.answered(ruling.question, prompts.QUOTE_SOURCES, ruling.answer, ruling.evidence, ruling.escalation, str(judge_of(cycle)), cycle.route.worker_line(), ruling.judge_cost)
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judge_cost)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judge_cost)
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects.now(), lambda text: say(text, cycle.effects)):
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects):
return Stop(1, unkept.reason)
return None
@@ -183,7 +193,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
return failure
return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects)
@@ -192,7 +202,7 @@ def archived_step(project_archive: pathlib.Path, transcript_path: str, task: str
"""Archives a step-up, if there is one, as the worker line it steps to. The outcome archived before it names the route the worker ran on until then, so the figures charge each stretch of work to its own rung. Both a ruling within a cycle and an unfinished verdict between cycles archive their step-up here."""
if step_up is None:
return None
return archive(project_archive, transcript_path, task, outcomes.stepped_up(step_up.after.worker_line()), effects.now(), lambda text: say(text, effects))
return archived(project_archive, transcript_path, task, outcomes.stepped_up(step_up.after.worker_line()), effects)
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
@@ -203,7 +213,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judge_cost) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judge_cost)
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason)
+1 -1
View File
@@ -1,5 +1,5 @@
from claude_code.entries import AssistantTurn, ends_stream, entry_from, hit_limit, json_object, limit_said, rejected_until
from loop_claude.effects import Effects, say
from loop_effects.effects import Effects, say
from failure import Failure
from claude_code.reply import Limited
from claude_code.transcript import part_line
+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)
+28 -25
View File
@@ -4,31 +4,34 @@ import typing
from release_plan.release_standing import default_plan, DefaultPlan
from git_cli.git_repo import default_ref, file_at
from loop_claude.effects import Effects, say
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
from model_routing.route import Route, route_from
from model_routing.ladder import Rung
from claude_code.session import Session, session_open, transcript_file
from loop_claude.running_loops import Show, taken_items
from claude_code.session import session_open, transcript_file
from loop_state.running_loops import taken_items
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
ORIGIN_TIMEOUT = 60
def shown_items(show: Show, root: str, 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(root)
return lambda taken_in: show(taken_items(todo, routed, taken_in))
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(root: str) -> 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."""
ref = default_ref(root, ORIGIN_TIMEOUT)
return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", root)
def fetched_todo(loop: Loop) -> str | Failure:
"""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)
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:
@@ -42,37 +45,37 @@ def routed(route: Route | None, project: Rung | None, model: str, archived: typi
return route if route and kept(route, project) else first_route(project, item())
def archived_route(archive_folder: pathlib.Path, session: Session, effects: Effects) -> Route | None:
"""The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged."""
transcript = transcript_file(session)
def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
"""The route named by the latest verdict archived for the loop's open chunk; None for a chunk not yet judged."""
transcript = transcript_file(loop.session)
worker = latest_worker(archive_folder, transcript) if transcript else None
if isinstance(worker, Failure):
say(f"routing the chunk afresh: {worker.reason}", effects)
say(f"routing the chunk afresh: {worker.reason}", loop.effects)
return None
route = route_from(worker) if worker else None
if worker and route is None:
say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", effects)
say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", loop.effects)
return route
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
facts = "" if session_open(session) else chunk_facts(preflight, root, effects)
return facts, lambda: plan_item(fetched_plan(root), effects)
facts = "" if session_open(loop.session) else chunk_facts(loop)
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
def chunk_facts(loop: Loop) -> str:
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
done = effects.python([str(preflight), "--worktree"], root)
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
if done.returncode:
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
return prompts.preflight_facts(done.stdout.strip())
def fetched_plan(root: str) -> DefaultPlan | Failure:
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing."""
ref = default_ref(root, ORIGIN_TIMEOUT)
return ref if isinstance(ref, Failure) else default_plan(root, ref)
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
return ref if isinstance(ref, Failure) else default_plan(loop.root, ref, loop.effects.git)
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
+7 -7
View File
@@ -3,31 +3,31 @@ import dataclasses
import pathlib
from loop_claude.cycle.run import archived_step, archived_stop, Concluded
from loop_claude.effects import Effects
from loop_claude.verdicts import Finished
from loop_claude.loop.this_loop import Loop
from loop_claude.loop.reload import LoopRun
from loop_claude.stop import needs_human, Stop
from loop_claude.routing import next_route, step_up
from model_routing.ladder import Rung
from claude_code.session import Session, transcript_file
from claude_code.session import transcript_file
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
UNFINISHED_LIMIT = 6
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop:
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
after = after_verdict(loop_run, project, concluded)
# A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
if after.route is None:
return after
# The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on.
path = transcript_file(session)
if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), effects)):
path = transcript_file(loop.session)
if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), loop.effects)):
return Stop(1, failure.reason)
if limit := reached_limit(after):
# Archived with the route the next cycle would run on, so a rerun resumes there.
return archived_stop(archive_folder, session, after.task, after.route, limit, limit.reason, effects)
return archived_stop(archive_folder, loop.session, after.task, after.route, limit, limit.reason, loop.effects)
return after
@@ -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=())
+29 -19
View File
@@ -3,24 +3,26 @@ 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
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from loop_claude.effects import Effects, say
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.project.model_choice import get_or_ask_models
from loop_claude.loop.usage import HELP
from loop_claude.running_loops import Listed, shown_running
from loop_claude.paths import Paths
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from model_routing.ladder import project_rung
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from claude_code.session import Session, session_named
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
@@ -29,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
@@ -42,45 +50,47 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
# "A " is the human's cue in the session picker that the session is the loop's.
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed:
loop = Loop(root=loop_run.root, session=session, listed=listed, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
if stop := exec_if_edited(loop, baseline, loop_run):
return stop
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
cycle = next_cycle(loop_run, session, listed, paths, env, launcher, effects)
cycle = next_cycle(loop_run, loop)
if isinstance(cycle, Stop):
return cycle
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, session, effects)
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
if isinstance(closed, Stop):
return closed
loop_run = closed
# Off the ladder the worker runs on the project's model itself, which its route names.
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), cycle.project or cycle.route.rung, paths, listed.folder, effects):
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
return stop
def next_cycle(loop_run: LoopRun, session: Session, listed: Listed, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> Cycle | Stop:
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
"""The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
premises = read_premises(loop_run.root)
premises = read_premises(loop.root)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
records = read_records(loop_run.root, paths.claude_dir)
records = read_records(loop.root, loop.paths.claude_dir)
if isinstance(records, Failure):
return Stop(1, records.reason)
models = get_or_ask_models(project_key(loop_run.root, paths.home), paths, env, effects)
models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects)
if isinstance(models, Stop):
return models
archive_folder = project_archive(loop_run.root, paths.home, env)
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
facts, item = chunk_start(loop)
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
show_taken_in = shown_items(listed.show, loop_run.root, route.item)
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)
todo = fetched_todo(loop)
show_taken_in = shown_items(loop, todo, route.item)
show_taken_in(loop_run.items_taken_in)
return Cycle(effects=effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=listed.folder, records=records, root=loop_run.root, route=route, session=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:
+16 -19
View File
@@ -5,9 +5,9 @@ import pathlib
import sys
import typing
from loop_claude.effects import Effects, say
from model_routing.route import Route
from model_routing.ladder import Rung
from loop_claude.loop.this_loop import Loop
from model_routing.route import Route, route_of
from loop_effects.effects import say
from loop_claude.stop import Stop
RELOAD_FLAG = "--reloaded"
@@ -67,23 +67,20 @@ def decoded_ids(value: object) -> tuple[int, ...]:
return tuple(exactly(int)(each) for each in value)
def decoded_rung(value: object) -> Rung:
return Rung(**decoded_fields(value, {"model": exactly(str), "effort": exactly(str)}, "model"))
def decoded_route(value: object) -> Route | None:
"""The Route the JSON holds; None for null, or for a route holding a key Route.RETIRED names, so the chunk routes afresh."""
if value is None or (isinstance(value, dict) and value.keys() & Route.RETIRED):
"""The Route the JSON holds; None for null. dataclasses.asdict wrote it as a worker line's fields, with the rung nested and the unfinished count added. route_of reads it once the rung's model and effort are lifted to the top and the count is set aside."""
if value is None:
return None
fields = decoded_fields(value, ROUTE_FIELDS, "rung")
if not Route.fits(fields):
if not isinstance(value, dict) or not isinstance(value.get("rung"), dict) or not value["rung"].keys() <= {"model", "effort"} or value.keys() & {"model", "effort"}:
raise Unreadable
return Route(**fields)
route = route_of({**{name: field for name, field in value.items() if name not in ("rung", "unfinished")}, **value["rung"]})
if route is None:
raise Unreadable
return dataclasses.replace(route, unfinished=exactly(int)(value.get("unfinished", 0)))
# One decoder per field of LoopRun and of Route, which tests hold to those dataclasses' fields: a field missing here stops a loop at the reload after it joined.
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "items_taken_in": decoded_ids}
ROUTE_FIELDS = {"rung": decoded_rung, **{name: exactly(int) for name in ("item", "likelihood", "escape_and_impact", "unfinished", "escape_and_impact_taken_in", "escalated_at")}}
def fingerprint(launcher: pathlib.Path) -> str:
@@ -98,15 +95,15 @@ def fingerprint(launcher: pathlib.Path) -> str:
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to loop-claude to use without the human rerunning it.
def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None:
if fingerprint(launcher) == baseline:
def exec_if_edited(loop: Loop, baseline: str, loop_run: LoopRun) -> Stop | None:
if fingerprint(loop.launcher) == baseline:
return None
trial = effects.python([str(launcher), "--help"], loop_run.root)
trial = loop.effects.python([str(loop.launcher), "--help"], loop.root)
if trial.returncode != 0:
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects)
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", loop.effects)
return None
try:
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
loop.effects.execv(sys.executable, [sys.executable, str(loop.launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
except OSError as failure:
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
return None
+24 -21
View File
@@ -2,28 +2,30 @@
import pathlib
from routing_figures import archive
from loop_claude.waiting.ask import Ask, OpenOnTerminal
from loop_state.waiting.ask import Ask, OpenOnTerminal
from routing_figures.calls import Call, calls, totals
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
from loop_claude.effects import Effects, say
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.waiting.listing import listed
from loop_claude.paths import Paths
from loop_state.waiting.listing import listed
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
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
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, session is its worker's session id, which loop-inbox lists the calls under, and rung is the rung of the claude that puts the calls to the human."""
def check_routing(root: pathlib.Path, rung: Rung, loop: Loop) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. root is the archive's, and rung is the rung of the claude that puts the calls to the human."""
with archive.locked(root) as held:
new = new_calls(root, paths, effects) if held else []
new = new_calls(root, loop.paths, loop.effects) if held else []
if isinstance(new, Failure):
say(f"routing figures: {new.reason}", effects)
say(f"routing figures: {new.reason}", loop.effects)
return None
return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None
return raise_calls(root, new, rung, loop) if new else None
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
@@ -48,21 +50,22 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
return [call for call in found if call not in raised.calls]
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[Call], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
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}", effects)
if not effects.on_terminal():
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
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
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal())
with listed(questions, ask, effects):
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.config_clone), {}), effects)
ask = Ask(loop.effects.new_id(), str(loop.session.id), loop.root, question, loop.effects.now(), OpenOnTerminal())
with listed(loop.listed.folder, ask, loop.effects):
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 {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.
if unmarked := state.mark_raised(root, new, utc(effects.now())):
say(f"routing figures: {unmarked.reason}", effects)
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 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
+23
View File
@@ -0,0 +1,23 @@
import dataclasses
import pathlib
import typing
from loop_effects.effects import Effects
from loop_state.running_loops import Listed
from loop_state.paths import Paths
from claude_code.session import Session
@dataclasses.dataclass(frozen=True)
class Loop:
"""What stays the same through one run of loop-claude; run_loop builds it once per process, so a reload builds it afresh."""
# The checkout the loop runs in. LoopRun.root names it too, since a reload hands it on there.
root: str
# The worker's session, under whose id loop-inbox lists the loop and its questions.
session: Session
listed: Listed
paths: Paths
env: typing.Mapping[str, str]
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
launcher: pathlib.Path
effects: Effects
+8 -4
View File
@@ -33,9 +33,12 @@ 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_claude/running_loops.py describes.
as bin/loop_state/running_loops.py describes.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
@@ -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
+1 -1
View File
@@ -2,7 +2,7 @@ import pathlib
from failure import Failure
from loop_claude.effects import Effects
from loop_effects.effects import Effects
from loop_claude.stop import Stop
+2 -2
View File
@@ -5,10 +5,10 @@ import sys
import typing
from claude_code.model_catalog import catalog_models
from loop_claude.effects import Effects, say
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from loop_state.paths import Paths
from records.file_writes import replace_json
+38 -14
View File
@@ -4,7 +4,7 @@ The worker, and the session /talk opens, run on a Route (model_routing/route.py)
- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item.
- Rerun. kept decides whether a rerun resumes the route its archive last names.
- Step-up. next_route raises the route after an unfinished verdict, or an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule. step_up names the change where it changes the worker line, which the archive records.
- Step-up. next_route raises the route after an unfinished verdict (unfinished_route), or an interrupt or a quoted answer that carries an escalation (escalated_route); escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule. step_up names the change where it changes the worker line, which the archive records.
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
"""
import dataclasses
@@ -82,25 +82,49 @@ class StepUp:
def next_route(project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds.
The rung never falls. It first rises to floor_rung, which the verdict's highest L taken in may raise. From there it steps one rung up on an escalation while below escalation_cap, and moves the mark, as loop_claude/escalation_mark.py says.
An unfinished verdict also counts towards UNFINISHED_PER_STEP, and the second such verdict steps the rung once, keeping the mark; where both fall on one verdict, it steps once. Last, it takes in the verdict's highest E + I, as Route.taking_in does.
An interrupt or a quoted answer without an escalation leaves the route as it is, since neither is an unfinished verdict.
"""
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds. The rung never falls."""
if project is None:
return route
if isinstance(verdict, Unfinished):
return unfinished_route(project, route, verdict)
return escalated_route(project, route, verdict)
def unfinished_route(project: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route after an unfinished verdict. The rung rises to floor_rung, which the verdict's highest L taken in may raise.
The verdict counts towards UNFINISHED_PER_STEP. Where steps says so, the rung steps once from the floor, and the mark moves only where the verdict escalates. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
"""
mark = escalation_mark.moved_to(verdict)
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
escalated_at = route.escalated_at if mark is None else mark
escalates = mark is not None and position(floor) < position(escalation_cap(project, route))
if isinstance(verdict, Unfinished):
counted = route.unfinished + 1
after = one_rung_up(route, floor, escalated_at) if counted >= UNFINISHED_PER_STEP or escalates else dataclasses.replace(route, rung=floor, unfinished=counted)
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
counted = route.unfinished + 1
if steps(counted, mark is not None and below_cap(project, route, floor)):
after = one_rung_up(route, floor, route.escalated_at if mark is None else mark)
else:
after = dataclasses.replace(route, rung=floor, unfinished=counted)
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
"""The route after an interrupt or a quoted answer. Without an escalation it holds, since neither is an unfinished verdict.
With one, the rung rises to floor_rung, which the verdict's highest L taken in may raise. Where floor_rung lies below escalation_cap, the rung steps one up from it and the mark moves, as loop_claude/escalation_mark.py says; at the cap the rung stays on floor_rung and the mark holds.
"""
mark = escalation_mark.moved_to(verdict)
if mark is None:
return route
return one_rung_up(route, floor, escalated_at) if escalates else dataclasses.replace(route, rung=floor)
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
return one_rung_up(route, floor, mark) if below_cap(project, route, floor) else dataclasses.replace(route, rung=floor)
def steps(counted: int, escalates: bool) -> bool:
"""Whether an unfinished verdict steps the rung: it is the UNFINISHED_PER_STEP-th since the last step, or it escalates below escalation_cap. Where both hold, the rung still steps once."""
return counted >= UNFINISHED_PER_STEP or escalates
def below_cap(project: Rung, route: Route, floor: Rung) -> bool:
"""Whether an escalation from floor may step the rung: floor lies below escalation_cap."""
return position(floor) < position(escalation_cap(project, route))
def step_up(before: Route, after: Route) -> StepUp | None:
+35 -31
View File
@@ -18,9 +18,9 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
from loop_claude.waiting.answers import send, Typed
from loop_claude import session_lock
from loop_claude.waiting.listing import waiting
from loop_state.waiting.answers import send, Typed
from loop_state import session_lock
from loop_state.waiting.listing import waiting
BIN = pathlib.Path(__file__).resolve().parents[1]
TASK = "Do the next chunk."
@@ -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)
File diff suppressed because it is too large Load Diff
+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.
View File
@@ -1,6 +1,10 @@
"""The effects loop-claude reaches the world through, such as its terminal, clock, processes, git and the machine's memory. loop-inbox runs on them too, so a change here, such as to how input reads a line, changes both tools."""
"""The effects a tool reaches the world through, such as its terminal, clock, processes, git and the machine's memory.
A change here, such as to how input reads a line, changes every tool that runs on them.
"""
import dataclasses
import os
import pathlib
import select
import signal
import subprocess
@@ -10,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
@@ -41,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]
@@ -77,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,
+117
View File
@@ -0,0 +1,117 @@
import contextlib
import dataclasses
import io
import os
import pathlib
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 loop_effects.effects import run_python, say, system_effects
NOW = 1790000000
# How a line said at NOW opens, with clocked's local_time.
STAMP = f"<{NOW}>"
def clocked():
"""The system's effects on a clock stopped at NOW, which renders a time as <seconds>."""
return dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW)
class Said(unittest.TestCase):
def test_opens_a_line_with_the_local_time_of_the_effects_clock(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
say("hello", clocked())
self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", ""))
def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
say("\nWhich one?\n\nA or B?", clocked())
self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n")
def test_says_on_stdout_where_asked(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
say("\n=== cycle 2 ===", clocked(), stdout=True)
self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n"))
def test_keeps_the_indent_of_the_first_line_after_the_time(self):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
say("\n indented", clocked())
self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n")
def test_flushes_so_piped_lines_arrive_when_said(self):
flushes = []
class Counting(io.StringIO):
def flush(self):
flushes.append(self.getvalue())
with contextlib.redirect_stderr(Counting()):
say("hello", clocked())
self.assertEqual(flushes, [f"{STAMP} hello\n"])
class LocalTime(unittest.TestCase):
def test_renders_seconds_in_the_machines_zone(self):
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
self.addCleanup(time.tzset)
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
zone.start()
self.addCleanup(zone.stop)
time.tzset()
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
class Alive(unittest.TestCase):
def test_a_process_that_runs_is_alive_and_one_that_ended_is_not(self):
ended = subprocess.Popen([sys.executable, "-c", "pass"])
ended.wait()
# Unless this process runs as root, it may not signal pid 1, which still runs.
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
class ClaudeOnTerminal(unittest.TestCase):
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
caught = []
self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number)))
before = signal.getsignal(signal.SIGINT)
with tempfile.TemporaryDirectory() as folder:
claude = pathlib.Path(folder, "claude")
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
claude.chmod(0o755)
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
class PythonEffect(unittest.TestCase):
def test_runs_a_script_in_the_given_directory(self):
with tempfile.TemporaryDirectory() as cwd:
self.assertEqual(run_python(["-c", "import os; print(os.getcwd())"], cwd, 60).stdout.strip(), os.path.realpath(cwd))
def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self):
done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5)
self.assertEqual(done.returncode, 1)
self.assertIn("0.5 s", done.stderr)
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
with tempfile.TemporaryDirectory() as cwd:
self.assertEqual(run_python(["-c", "import sys; sys.stdout.buffer.write(b'caf\\xe9')"], cwd, 60).stdout, "caf�")
def test_reads_a_script_that_cannot_start_as_exit_1_saying_why(self):
with tempfile.TemporaryDirectory() as temp:
gone = str(pathlib.Path(temp, "gone"))
done = run_python(["-c", "pass"], gone, 60)
self.assertEqual(done.returncode, 1)
self.assertIn(gone, done.stderr)
+3 -3
View File
@@ -10,9 +10,9 @@ import dataclasses
import textwrap
import typing
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_claude.running_loops import RunningLoop, Taken
from loop_claude.waiting.talk import TALK
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_state.running_loops import RunningLoop, Taken
from loop_state.waiting.talk import TALK
ENTER = "enter"
BACKSPACE = "backspace"
+11 -11
View File
@@ -26,8 +26,8 @@ above where it waits for an answer, and a line per todo.md item its chunk takes,
tagline on the default branch. A loop whose process is gone drops off this list too.
The loops' questions are files in ~/.local/state/loop-claude, read and written as
bin/loop_claude/waiting/ describes; the running loops are files beside them, as
bin/loop_claude/running_loops.py describes.
bin/loop_state/waiting/ describes; the running loops are files beside them, as
bin/loop_state/running_loops.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
@@ -39,16 +39,16 @@ import sys
import typing
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_claude.waiting.ask import Ask, Asking, read_ask
from loop_claude.waiting.listing import ask_file, drop_ended, waiting
from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_claude.waiting.answers import ClaudeEnded, send, Typed
from loop_claude.running_loops import drop_ended_loops, running_loops
from loop_claude.effects import Effects, system_effects
from loop_state.waiting.ask import Ask, Asking, read_ask
from loop_state.waiting.listing import ask_file, drop_ended, waiting
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_state.waiting.answers import ClaudeEnded, send, Typed
from loop_state.running_loops import drop_ended_loops, running_loops
from loop_effects.effects import Effects, system_effects
from failure import Failure
from loop_claude.hand_over import hand_over
from loop_claude.paths import Paths, paths_from
from loop_claude.session_lock import running
from loop_state.hand_over import hand_over
from loop_state.paths import Paths, paths_from
from loop_state.session_lock import running
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
+9 -9
View File
@@ -12,18 +12,18 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed
from loop_state.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask
from loop_claude.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw
from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_claude.hand_over import ClaudeCommand
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask
from loop_state.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_state.hand_over import ClaudeCommand
from failure import Failure
from loop_inbox import inbox, main
from loop_claude.paths import paths_from
from loop_claude import running_loops, session_lock
from loop_claude.running_loops import RunningLoop, Taken
from loop_claude.effects import system_effects
from loop_state.paths import paths_from
from loop_state import running_loops, session_lock
from loop_state.running_loops import RunningLoop, Taken
from loop_effects.effects import system_effects
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
# The pid of this loop-inbox.
+4
View File
@@ -0,0 +1,4 @@
"""The files loop-claude and loop-inbox share: a running loop lists itself (running_loops.py, session_lock.py) and its question (waiting/), and both read the same paths (paths.py) and open claude for the human the same way (hand_over.py).
A change here changes both tools. It imports nothing from loop_claude/.
"""
@@ -1,7 +1,7 @@
"""Opens claude on the terminal for the human. It sits outside cycle/, since loop-inbox's /talk and the loop's routing calls open claude too."""
"""Opens claude on the terminal for the human."""
import dataclasses
from loop_claude.effects import Effects
from loop_effects.effects import Effects
from failure import Failure
from model_routing.ladder import Rung
@@ -11,7 +11,7 @@ class Paths:
home: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
# Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting/).
# Where a loop shows its interrupt to loop-inbox (bin/loop_state/waiting/).
waiting: pathlib.Path
@@ -2,12 +2,10 @@
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.
This module, waiting/ and session_lock.py hold loop-claude's state, which loop-inbox reads. They stay in loop_claude/ because they import its effects.py and hand_over.py: a package of their own would import loop_claude, and loop_claude would import it, a cycle.
"""
import contextlib
import dataclasses
@@ -16,8 +14,8 @@ import pathlib
import shutil
import typing
from loop_claude.effects import Effects, say
from loop_claude.session_lock import ended, held, running
from loop_effects.effects import Effects, say
from loop_state.session_lock import ended, held, running
from failure import Failure
from release_plan.todo_table import items
from records.file_writes import replace_json
+41
View File
@@ -0,0 +1,41 @@
import errno
import pathlib
import shutil
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from loop_state import session_lock
class SessionLock(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
self.path = session_lock.lock_file(self.folder, "s1")
def test_a_held_lock_refuses_a_second_taker_and_reads_as_running_until_let_go(self):
self.assertFalse(session_lock.running(self.folder, "s1"))
with session_lock.held(self.folder, "s1") as first:
self.assertIsNone(first)
with session_lock.held(self.folder, "s1") as second:
self.assertEqual(second, Failure(f"another process holds {self.path}"))
self.assertTrue(session_lock.running(self.folder, "s1"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_that_cannot_be_opened_is_a_failure_and_no_loop_running(self):
self.path.mkdir()
with session_lock.held(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot open {self.path}: Is a directory"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_the_kernel_refuses_is_a_failure_and_no_loop_running(self):
self.path.touch()
with unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
with session_lock.held(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot lock {self.path}: No locks available"))
self.assertFalse(session_lock.running(self.folder, "s1"))
@@ -5,7 +5,7 @@ import dataclasses
import json
import pathlib
from loop_claude.waiting.ask import Ask, tagged
from loop_state.waiting.ask import Ask, tagged
from failure import Failure
from records.file_writes import replace_json
@@ -6,7 +6,7 @@ import json
import pathlib
import typing
from loop_claude.hand_over import ClaudeCommand
from loop_state.hand_over import ClaudeCommand
from records.utc_stamp import seconds, utc
if typing.TYPE_CHECKING:
@@ -3,10 +3,10 @@ import contextlib
import pathlib
import typing
from loop_claude.waiting.answers import answer_file
from loop_claude.waiting.ask import Ask, ask_fields, read_ask
from loop_claude.effects import Effects, say
from loop_claude.session_lock import ended, running
from loop_state.waiting.answers import answer_file
from loop_state.waiting.ask import Ask, ask_fields, read_ask
from loop_effects.effects import Effects, say
from loop_state.session_lock import ended, running
from failure import Failure
from records.file_writes import make_private, replace_json
@@ -9,10 +9,10 @@ import dataclasses
import pathlib
import typing
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, read_ask
from loop_claude.waiting.listing import ask_file, shown
from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send
from loop_claude.effects import Effects, POLL_SECONDS
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, read_ask
from loop_state.waiting.listing import ask_file, shown
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send
from loop_effects.effects import Effects, POLL_SECONDS
from failure import Failure
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
+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()
+13 -9
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}
@@ -92,17 +93,20 @@ def stepped_up(rung: Rung) -> Rung:
return climbed(rung, 1)
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind) -> Rung:
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I.
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay …`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact)
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's."""
return highest(worker, review_floor(project, escape_and_impact))
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
"""
return project if markdown_only else highest(worker, review_floor(project, escape_and_impact))
def highest(*rungs: Rung) -> Rung:
+5 -3
View File
@@ -2,13 +2,15 @@
import dataclasses
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
from model_routing.ladder import reviewers_rung, Rung
from model_routing.ladder import review_rung, reviewers_rung, Rung
@dataclasses.dataclass(frozen=True)
class ReviewChoice:
# The rung of each pass's reviewer.
reviewers: Rung
# The rung of each pass's reviewer where the branch changes only Markdown no agent follows.
markdown_only: Rung
seat: Rung
security: Rung
# Each rung a higher E + I than the route's picks for the reviewers, with the lowest E + I that picks it, in rising order.
@@ -22,5 +24,5 @@ def chosen(project: Rung, route: Route) -> ReviewChoice:
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
higher.setdefault(rung, escape_and_impact)
# A seat and the security pass run on the project's rung, as ladder.review_rung says.
return ReviewChoice(reviewers, project, project, higher)
markdown_only = reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
return ReviewChoice(reviewers, markdown_only, review_rung(project, route.rung, route.reviewed_on(), "seat"), review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
+12 -15
View File
@@ -38,20 +38,18 @@ class Route:
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
"""
# Each field below but rung and unfinished is a key of the archive's worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
rung: Rung
item: int = 0
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
def __post_init__(self) -> None:
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route.
# Raises on a programming error only, so nothing catches it: route_of checks fits before it builds a route.
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
@@ -61,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:
@@ -80,19 +78,18 @@ WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if
def route_from(worker: str) -> Route | None:
"""The route an archived worker line names; None for a line Route.worker_line could not have written, such as text that isn't JSON."""
fields = json_fields(worker)
if fields is None or not Route.fits(fields):
return None
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
def json_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a line Route.worker_line wrote; None for any other text."""
try:
fields = json.loads(line)
fields = json.loads(worker)
except ValueError:
return None
return route_of(fields)
def route_of(fields: object) -> Route | None:
"""The route these fields of a worker line name, with an unfinished count of 0; None for fields Route.worker_line could not have written. A reload decodes its route through it too (loop_claude/loop/reload.py), so Route has one decoder."""
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}):
return None
# type(), not isinstance(): JSON true is no integer.
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
if not all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) or not Route.fits(fields):
return None
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
+12 -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,13 @@ 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])
def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self):
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
self.assertEqual(review_rung(OPUS, LADDER[0], 4, "stability", markdown_only=True), OPUS)
+5 -1
View File
@@ -5,9 +5,13 @@ 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):
def test_names_no_higher_rung_on_the_top_one(self):
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
def test_reviews_a_branch_changing_only_markdown_on_the_projects_rung_and_the_seats_and_security_pass_there_always(self):
choice = chosen(OPUS, Route(FABLE, 3, 4, 5))
self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS))
+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)
+3 -3
View File
@@ -89,7 +89,7 @@ import pathlib
import sys
from failure import Failure
from release_plan import ranking
from release_plan import plan_file
def main(argv: list[str]) -> int:
@@ -101,11 +101,11 @@ def main(argv: list[str]) -> int:
return fail(args)
check, todo = args
if check:
failures = ranking.check_failures(todo)
failures = plan_file.check_failures(todo)
for line in failures:
print(line, file=sys.stderr)
return 1 if failures else 0
ranked = ranking.rank_file(todo)
ranked = plan_file.rank_file(todo)
if isinstance(ranked, Failure):
return fail(ranked)
return 1 if ranked.under_bar else 0
+53
View File
@@ -0,0 +1,53 @@
"""The order blockers impose on the ranked items: each blocker above every item it blocks, no blocker in a later release than an item it blocks, and no blockers in a loop."""
import dataclasses
import graphlib
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release import version
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
"""scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped from the Blocked by cells."""
held = {item.id: (item, value) for item, value in scored}
position = {item.id: index for index, (item, _) in enumerate(scored)}
for item, _ in scored:
for blocker in item.blocked_by:
if blocker in held and held[blocker][0].release > item.release:
later, earlier = version(held[blocker][0].release), version(item.release)
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
if loop := blocking_loop(held):
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
placed: set[int] = set()
return [entry for item, _ in scored for entry in place(item.id, held, position, placed)]
def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None:
"""The IDs of items that block each other in a loop, sorted; None where there is no loop."""
graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()}
try:
graphlib.TopologicalSorter(graph).prepare()
except graphlib.CycleError as cycle:
return sorted(set(cycle.args[1]))
return None
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]:
"""id_'s item, preceded by each of its blockers not yet in placed, in score order, each of them preceded in turn by its own blockers; empty where placed already holds id_. Each item returned joins placed. blocking_loop has ruled out a loop, so the recursion ends."""
if id_ in placed:
return []
placed.add(id_)
item, value = held[id_]
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)]
return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
def blocked_through(id_: int, items: list[Item]) -> set[int]:
"""The IDs of the items id_ blocks, and of those they block in turn."""
found: set[int] = set()
reached = {id_}
while reached:
reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found
found |= reached
return found
+65
View File
@@ -0,0 +1,65 @@
"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can hold nothing else, and evaluated to a float."""
import ast
import math
from failure import Failure
# The most parts and characters a formula may hold.
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
if isinstance(source, Failure):
return source
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
if len(source) > LONGEST_FORMULA:
return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters")
try:
tree = ast.parse(source, mode="eval")
except (SyntaxError, ValueError):
return Failure(f"the formula {source!r} does not parse")
nodes = list(ast.walk(tree))
if len(nodes) > LARGEST_FORMULA:
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
for node in nodes:
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
return tree
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
match node:
case ast.Expression(body):
return evaluate(body, values)
case ast.Constant(value) if isinstance(value, (int, float)):
return float(value)
case ast.Name(name):
return values[name]
case ast.UnaryOp(ast.USub(), operand):
return -evaluate(operand, values)
case ast.UnaryOp(ast.UAdd(), operand):
return evaluate(operand, values)
case ast.BinOp(left, ast.Add(), right):
return evaluate(left, values) + evaluate(right, values)
case ast.BinOp(left, ast.Sub(), right):
return evaluate(left, values) - evaluate(right, values)
case ast.BinOp(left, ast.Mult(), right):
return evaluate(left, values) * evaluate(right, values)
case ast.BinOp(left, ast.Div(), right):
divisor = evaluate(right, values)
return evaluate(left, values) / divisor if divisor else math.nan
case ast.BinOp(left, ast.Pow(), right):
base, exponent = evaluate(left, values), evaluate(right, values)
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
if math.isnan(base) or math.isnan(exponent):
return math.nan
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
try:
return math.pow(base, exponent)
except (OverflowError, ValueError):
return math.nan
return math.nan
+62
View File
@@ -0,0 +1,62 @@
"""todo.md on disk: read it with the project files ranking reads, then rank or check it, write it back, and print what ranking reports."""
import pathlib
import sys
from failure import Failure
from review_rules.comprehension_history import HISTORY
from release_plan.ranking import rank, Ranked
from records.file_writes import replace_file
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
texts = read_all(todo)
if isinstance(texts, Failure):
return texts
ranked = rank(*texts)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
return unwritten
print_report(todo, ranked)
return ranked
def print_report(todo: pathlib.Path, ranked: Ranked) -> None:
"""Print ranking's notes and under-bar lines on stderr, each prefixed with todo's path."""
for line in ranked.notes + ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
def check_failures(todo: pathlib.Path) -> list[str]:
"""Why --check fails on todo, empty when it passes."""
texts = read_all(todo)
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md. The last two are empty when missing; a missing todo.md or README.md is a Failure."""
texts = []
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
try:
texts.append(path.read_text(encoding="utf-8"))
except FileNotFoundError:
if missing:
return Failure(f"{path}: not found; {missing}")
texts.append("")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
return texts[0], texts[1], texts[2], texts[3]
def write(path: pathlib.Path, text: str) -> Failure | None:
unwritten = replace_file(path.resolve(), text.encode("utf-8"))
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
+7 -161
View File
@@ -1,19 +1,18 @@
"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules."""
"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules.
"""
import ast
import dataclasses
import decimal
import graphlib
import math
import pathlib
import re
import sys
import typing
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
from release_plan.blockers import blocked_through, blockers_first
from release_plan.formula import evaluate, parse_formula
from failure import Failure
from review_rules.comprehension_history import FLOOR, HISTORY, latest_overall
from review_rules.comprehension_history import FLOOR, latest_overall
from records.markdown_text import listed, sections
from records.file_writes import replace_file
from release_plan.release import version
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
@@ -26,12 +25,9 @@ MAINTAIN_WEIGHT = 0.5
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
LARGEST_FORMULA = 200
LONGEST_FORMULA = 4 * LARGEST_FORMULA
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
WEIGHTS_HEADER = "| Goal | W |"
# The Exempt reasons that rank ahead of the rest of their release, in this order: a question first, since its answer may change other items, then a security finding.
FIRST = {"question": 0, "security": 1}
FIRST: dict[Exempt, int] = {"question": 0, "security": 1}
# How README.md marks a goal; None where it marks it neither way.
Mark = typing.Literal["Maintain", "Achieve"] | None
RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, score its L, E and I in place of C, and set the bar below the score of every item to keep"
@@ -57,55 +53,6 @@ class Ranked:
notes: list[str]
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
texts = read_all(todo)
if isinstance(texts, Failure):
return texts
ranked = rank(*texts)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
return unwritten
for line in ranked.notes + ranked.under_bar:
print(f"{todo}: {line}", file=sys.stderr)
return ranked
def check_failures(todo: pathlib.Path) -> list[str]:
"""Why --check fails on todo, empty when it passes."""
texts = read_all(todo)
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none."""
texts = []
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
try:
texts.append(path.read_text(encoding="utf-8"))
except FileNotFoundError:
if missing:
return Failure(f"{path}: not found; {missing}")
texts.append("")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
return texts[0], texts[1], texts[2], texts[3]
def write(path: pathlib.Path, text: str) -> Failure | None:
unwritten = replace_file(path.resolve(), text.encode("utf-8"))
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure:
lines = text.split("\n")
table = read_table(lines)
@@ -156,16 +103,6 @@ def notes(items: list[Item], scoring: Scoring) -> list[str]:
return unweighed + dropped
def blocked_through(id_: int, items: list[Item]) -> set[int]:
"""The IDs of the items id_ blocks, and of those they block in turn."""
found: set[int] = set()
reached = {id_}
while reached:
reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found
found |= reached
return found
def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | Failure:
"""Each item with its score, by release, then questions and security findings first, then by score from highest, then by ID; then each blocker above every item it blocks."""
by_score = []
@@ -298,42 +235,6 @@ def outside_items(lines: list[str], table: Table) -> Failure | None:
return None
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
"""scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped."""
held = {item.id: (item, value) for item, value in scored}
position = {item.id: index for index, (item, _) in enumerate(scored)}
for item, _ in scored:
for blocker in item.blocked_by:
if blocker in held and held[blocker][0].release > item.release:
later, earlier = version(held[blocker][0].release), version(item.release)
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
if loop := blocking_loop(held):
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
placed: set[int] = set()
return [entry for item, _ in scored for entry in place(item.id, held, position, placed)]
def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None:
"""The IDs of items that block each other in a loop, sorted; None where there is no loop."""
graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()}
try:
graphlib.TopologicalSorter(graph).prepare()
except graphlib.CycleError as cycle:
return sorted(set(cycle.args[1]))
return None
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]:
"""The item id_, unless placed holds it, preceded by those of its blockers placed doesn't hold yet, each in score order, and theirs before them. Each item it returns joins placed. blocking_loop has ruled out a loop."""
if id_ in placed:
return []
placed.add(id_)
item, value = held[id_]
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)]
return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
def check_citations(items: list[Item], decisions: str) -> Failure | None:
"""Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited."""
cited = set(cited_items(decisions))
@@ -390,61 +291,6 @@ def stated(text: str, name: str) -> str | Failure:
return found[0]
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
if isinstance(source, Failure):
return source
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
if len(source) > LONGEST_FORMULA:
return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters")
try:
tree = ast.parse(source, mode="eval")
except (SyntaxError, ValueError):
return Failure(f"the formula {source!r} does not parse")
nodes = list(ast.walk(tree))
if len(nodes) > LARGEST_FORMULA:
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
for node in nodes:
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
return tree
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
match node:
case ast.Expression(body):
return evaluate(body, values)
case ast.Constant(value) if isinstance(value, (int, float)):
return float(value)
case ast.Name(name):
return values[name]
case ast.UnaryOp(ast.USub(), operand):
return -evaluate(operand, values)
case ast.UnaryOp(ast.UAdd(), operand):
return evaluate(operand, values)
case ast.BinOp(left, ast.Add(), right):
return evaluate(left, values) + evaluate(right, values)
case ast.BinOp(left, ast.Sub(), right):
return evaluate(left, values) - evaluate(right, values)
case ast.BinOp(left, ast.Mult(), right):
return evaluate(left, values) * evaluate(right, values)
case ast.BinOp(left, ast.Div(), right):
divisor = evaluate(right, values)
return evaluate(left, values) / divisor if divisor else math.nan
case ast.BinOp(left, ast.Pow(), right):
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
base, exponent = evaluate(left, values), evaluate(right, values)
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
if math.isnan(base) or math.isnan(exponent):
return math.nan
try:
return math.pow(base, exponent)
except (OverflowError, ValueError):
return math.nan
return math.nan
def goal_term(shape: Shape) -> str:
"""The name of the formula's goal term, which score builds: W in OLD_SHAPE, V in the current shape."""
return "W" if shape is OLD_SHAPE else "V"
+2 -2
View File
@@ -45,9 +45,9 @@ def dated_heading_pattern(release: Release) -> str:
return "^## " + re.escape(version(release)) + " - " + "-".join("[0-9]" * digits for digits in DATE_DIGITS) + "$"
def newest_tag(cwd: str | None = None, merged_into: str | None = None) -> str | None | Failure:
def newest_tag(cwd: str | None = None, merged_into: str | None = None, run: git_repo.Git = git_repo.git) -> str | None | Failure:
"""The newest `v*` tag, read in cwd, else in the current directory, and merged into merged_into where it is given; None when there is none."""
# Sorts v1.0.0-rc.1 below v1.0.0.
merged = ["--merged", merged_into] if merged_into else []
tags = git_repo.git("-c", "versionsort.suffix=-", "tag", "--list", "v*", *merged, "--sort=-v:refname", cwd=cwd)
tags = run("-c", "versionsort.suffix=-", "tag", "--list", "v*", *merged, "--sort=-v:refname", cwd=cwd)
return tags if isinstance(tags, Failure) else next(iter(tags.split()), None)
+16 -16
View File
@@ -1,7 +1,7 @@
"""How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick."""
import dataclasses
from git_cli.git_repo import commits_since, file_at, git
from git_cli.git_repo import commits_since, file_at, git, Git
from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged
from failure import Failure
from release_plan.todo_table import Item, items, next_item, renames
@@ -90,46 +90,46 @@ class DefaultPlan:
cut: LastCut
def default_plan(root: str, ref: str) -> DefaultPlan:
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root."""
tag = newest_tag(root, merged_into=ref)
changelog = file_at(ref, "CHANGELOG.md", root)
def default_plan(root: str, ref: str, run: Git = git) -> DefaultPlan:
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run."""
tag = newest_tag(root, merged_into=ref, run=run)
changelog = file_at(ref, "CHANGELOG.md", root, run)
after = dated_cut(tag, changelog)
since = tag if after is None else heading_commit(after, ref, root)
commits = since if isinstance(since, Failure) else commits_since(since, ref, root)
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after)
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, changelog, commits, todos_since(tag, ref, root), reviewed))
since = tag if after is None else heading_commit(after, ref, root, run)
commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run)
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after, run)
return DefaultPlan(file_at(ref, "todo.md", root, run), LastCut(tag, changelog, commits, todos_since(tag, ref, root, run), reviewed))
def heading_commit(release: Release, ref: str, cwd: str) -> str | None | Failure:
def heading_commit(release: Release, ref: str, cwd: str, run: Git = git) -> str | None | Failure:
"""The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none."""
# -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count.
added = git("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", "CHANGELOG.md", cwd=cwd)
added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", "CHANGELOG.md", cwd=cwd)
return added if isinstance(added, Failure) else next(iter(added.split()), None)
def release_reviewed(tag: str | None, ref: str, cwd: str, after: Release | None = None) -> bool | Failure:
def release_reviewed(tag: str | None, ref: str, cwd: str, after: Release | None = None, run: Git = git) -> bool | Failure:
"""Whether ref holds a commit titled as a release review opens, `Release review of <release>`: after tag, or anywhere where tag is None.
after is the version a branch with no tag counts as cut, or None. Where it is given, a title counts only where its release is later than after.
"""
titles = git("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
titles = run("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
if isinstance(titles, Failure):
return titles
reviews = [title.removeprefix("Release review of ") for title in titles.splitlines() if title.startswith("Release review of ")]
return any(after is None or ((named := parsed(review)) is not None and named > after) for review in reviews)
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure:
def todos_since(tag: str | None | Failure, ref: str, cwd: str, run: Git = git) -> list[str] | Failure:
"""LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent."""
if isinstance(tag, Failure):
return []
changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd)
changed = run("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd)
if isinstance(changed, Failure):
return changed
texts = []
for commit in [*([tag] if tag else []), *changed.split()]:
text = file_at(commit, "todo.md", cwd)
text = file_at(commit, "todo.md", cwd, run)
if isinstance(text, Failure):
return text
texts.append(text)
+115
View File
@@ -0,0 +1,115 @@
import pathlib
import re
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from failure import Failure
from release_plan import ranking, todo_table
class Blockers(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
""", ranked.text)
self.assertEqual(self.ranked(ranked.text), ranked)
def test_ranks_an_items_blockers_in_score_order(self):
rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"])
def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self):
chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |")
rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"])
def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self):
# Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release.
waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |"))
self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), [])
answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |"))
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5])
def test_ships_an_item_above_r_5_alone(self):
# Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins.
found = todo_table.items(TODO)
self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), [])
# At R 6, item 3 ships alone too.
riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))])
# Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6.
unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))])
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
ranked = self.ranked(finished)
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
self.assertEqual(self.ranked(ranked.text).notes, [])
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
cases = {
"| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later",
"| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by",
"| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held",
"| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held",
}
for cell, reason in cases.items():
with self.subTest(cell=cell):
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason))
looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")
self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers"))
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \""))
def test_adds_the_column_to_a_table_without_it(self):
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
self.assertEqual(self.ranked(without), self.ranked(TODO))
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self):
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it"))
self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5])
with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|")
with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c)
self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows"))
def test_refuses_text_under_items_beside_the_table(self):
last = TODO.split("\n## Details")[0] + "\n"
self.assertIsInstance(self.ranked(last), ranking.Ranked)
beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail")
for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"):
with self.subTest(ordered=ordered[-60:]):
self.assertEqual(self.ranked(ordered), beside)
def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self):
self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n")
self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items")
table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n"
above = table + "\n" + TODO.replace(table, "")
self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items")
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table"))
repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one"))
def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self):
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |"
self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), [])
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
+24
View File
@@ -0,0 +1,24 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from failure import Failure
from release_plan import ranking
class Formula(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
with self.subTest(formula=formula):
self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure)
self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text)
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
+2 -117
View File
@@ -9,7 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from release_plan import ranking
from release_plan import plan_file, ranking
from repo_checks import ROOT
from release_plan import todo_table
@@ -207,16 +207,6 @@ class Rank(unittest.TestCase):
weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n")
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says"))
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
with self.subTest(formula=formula):
self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure)
self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text)
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
def test_refuses_a_file_off_the_format(self):
row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |"
broken = {
@@ -351,7 +341,7 @@ class CodeHealth(unittest.TestCase):
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = ranking.rank_file(todo)
ranked = plan_file.rank_file(todo)
self.assertIsInstance(ranked, ranking.Ranked)
self.assertEqual(ranked.under_bar, [])
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
@@ -451,111 +441,6 @@ class OldShape(unittest.TestCase):
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
class Blockers(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
""", ranked.text)
self.assertEqual(self.ranked(ranked.text), ranked)
def test_ranks_an_items_blockers_in_score_order(self):
rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"])
def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self):
chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |")
rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"])
def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self):
# Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release.
waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |"))
self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), [])
answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |"))
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5])
def test_ships_an_item_above_r_5_alone(self):
# Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins.
found = todo_table.items(TODO)
self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), [])
# At R 6, item 3 ships alone too.
riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))])
# Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6.
unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |"))
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))])
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
ranked = self.ranked(finished)
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
self.assertEqual(self.ranked(ranked.text).notes, [])
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
cases = {
"| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later",
"| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by",
"| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held",
"| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held",
}
for cell, reason in cases.items():
with self.subTest(cell=cell):
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason))
looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")
self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers"))
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \""))
def test_adds_the_column_to_a_table_without_it(self):
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
self.assertEqual(self.ranked(without), self.ranked(TODO))
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self):
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it"))
self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5])
with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|")
with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c)
self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows"))
def test_refuses_text_under_items_beside_the_table(self):
last = TODO.split("\n## Details")[0] + "\n"
self.assertIsInstance(self.ranked(last), ranking.Ranked)
beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail")
for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"):
with self.subTest(ordered=ordered[-60:]):
self.assertEqual(self.ranked(ordered), beside)
def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self):
self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n")
self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items")
table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n"
above = table + "\n" + TODO.replace(table, "")
self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items")
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table"))
repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one"))
def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self):
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |"
self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), [])
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
class Renamed(unittest.TestCase):
def test_reads_the_releases_the_renamed_section_names(self):
self.assertEqual(todo_table.renames("## Items\n\n## Details\n"), set())
+16 -9
View File
@@ -13,7 +13,9 @@ LEVELS = {"L": 4, "E": 3, "I": 5}
RISK_FLOOR = {4: 5, 5: 7}
# The highest R an item may have and still share a chunk; `docs/decisions.md` → `chunks:` says why 5.
BUNDLE_MAX_R = 5
EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "security")
# What an Exempt cell may hold: empty, or a reason ~/.claude/rules/todo-items.md defines.
Exempt = typing.Literal["", "decision", "defect", "owner", "principle", "question", "security"]
EXEMPTIONS: tuple[Exempt, ...] = typing.get_args(Exempt)
# The column naming the items that block an item: each must be done before the item starts.
BLOCKED_BY = "Blocked by"
# The column naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`.
@@ -94,7 +96,7 @@ OLD_SHAPE = Shape(("R", "S", "C", "A", "G"), (BLOCKED_BY, "C", "Score"), (), (),
class Item:
id: int
release: Release
exempt: str
exempt: Exempt
tagline: str
scores: dict[str, int]
moves: Moves
@@ -263,8 +265,9 @@ def parse_row(row: str, table: Table) -> Item | Failure:
if isinstance(found, Failure):
return found
named = dict(zip(table.columns, found))
if misformed := check_cells(row, named):
return misformed
exempt = check_cells(row, named)
if isinstance(exempt, Failure):
return exempt
shape = shape_of(table.columns)
scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns)
if isinstance(scores, Failure):
@@ -275,21 +278,25 @@ def parse_row(row: str, table: Table) -> Item | Failure:
moves = shape.read_goals(named["ID"], named[shape.goals_column])
if isinstance(moves, Failure):
return moves
return Item(int(named["ID"]), release_of(named["Release"]), named["Exempt"], named["Item"], scores, moves, blocked_by)
return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by)
def check_cells(row: str, named: dict[str, str]) -> Failure | None:
"""Holds the row's ID, Release, Exempt and Item cells to the format: why one breaks it, None when none does."""
def is_exempt(cell: str) -> typing.TypeGuard[Exempt]:
return cell in EXEMPTIONS
def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure:
"""Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it."""
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if parsed(release) is None:
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if exempt not in EXEMPTIONS:
if not is_exempt(exempt):
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
return None
return exempt
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
+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())
+60
View File
@@ -0,0 +1,60 @@
import ast
import importlib
import importlib.util
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from repo_checks import ROOT
# 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]]:
"""Each module the source imports from bin/, with each name it takes from that module or reads through a name bound to it, or None for the module itself."""
tree = ast.parse(source)
found: list[tuple[str, str | None]] = []
# A name the source binds to a module, such as rm in `from review_replay import main as rm`.
modules: dict[str, str] = {}
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
found += [(node.module, alias.name) for alias in node.names]
modules |= {alias.asname or alias.name: f"{node.module}.{alias.name}" for alias in node.names if is_module(f"{node.module}.{alias.name}")}
elif isinstance(node, ast.Import):
found += [(alias.name, None) for alias in node.names]
modules |= {alias.asname: alias.name for alias in node.names if alias.asname}
found += [(modules[node.value.id], node.attr) for node in ast.walk(tree) if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in modules]
return [(module, name) for module, name in found if in_bin(module)]
def is_module(dotted: str) -> bool:
path = ROOT / "bin" / dotted.replace(".", "/")
return path.is_dir() or path.with_suffix(".py").is_file()
def in_bin(module: str) -> bool:
return is_module(module.split(".")[0])
class TrialsImports(unittest.TestCase):
"""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(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):
imported = importlib.import_module(module)
if name is not None:
self.assertTrue(hasattr(imported, name) or importlib.util.find_spec(f"{module}.{name}"))
def test_an_import_of_a_bin_module_is_found_and_a_stdlib_one_is_not(self):
self.assertEqual(bin_imports("import json\nfrom failure import Failure\nimport review_replay.main as rm\n"), [("failure", "Failure"), ("review_replay.main", None)])
def test_a_name_read_through_a_module_alias_is_found(self):
source = "from review_replay import main as rm\nimport review_replay.rounds as rr\nrm.code_of(rr.Round)\n"
self.assertEqual(bin_imports(source), [("review_replay", "main"), ("review_replay.rounds", None), ("review_replay.main", "code_of"), ("review_replay.rounds", "Round")])
+1 -1
View File
@@ -6,6 +6,6 @@ import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from review_replay import main
from loop_claude.effects import system_effects
from loop_effects.effects import system_effects
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))

Some files were not shown because too many files have changed in this diff Show More