Compare commits

..

178 Commits

Author SHA1 Message Date
lilleman 2ab0954a08 Probe: a second push cancels the first run
CI / tests (pull_request) Has been cancelled
2026-11-18 13:46:49 +01:00
lilleman 5bc69f1689 Cancel a pull request's older CI runs when it gets a new push
CI / tests (pull_request) Has been cancelled
2026-11-18 13:46:43 +01:00
lilleman 58f6505851 File items 420, 421 and 422
CI / tests (pull_request) Successful in 4m3s
2026-11-18 13:27:57 +01:00
lilleman f444dca67a Finish item 404 in the plan
CI / tests (pull_request) Successful in 3m25s
2026-11-18 12:47:22 +01:00
lilleman 1c14caf494 Merge remote-tracking branch 'origin/main' into item-404
CI / tests (pull_request) Successful in 3m25s
# Conflicts:
#	.gitignore
#	README.md
#	docs/reading-cost.md
2026-11-18 12:43:31 +01:00
lilleman aabbefaad5 Kill the mutants of do_epic/config.py that its tests missed
CI / tests (pull_request) Successful in 3m2s
2026-11-18 12:41:51 +01:00
lilleman b5033abacc Answer stability round 1: refuse an env-file only inside a config's folder or the clone folder, and split the tests
CI / tests (pull_request) Successful in 2m49s
2026-11-18 12:40:04 +01:00
lilleman 3f50f0389f Finish item 402 in the plan
CI / tests (pull_request) Successful in 3m33s
2026-11-18 11:48:24 +01:00
lilleman 7bc2586831 Merge remote-tracking branch 'origin/main' into item-402
CI / tests (pull_request) Successful in 5m5s
# Conflicts:
#	.gitignore
2026-11-18 11:48:10 +01:00
lilleman 1c8c071582 File item 419: run the external auto-reviewer until its review of the head has no findings
CI / tests (pull_request) Successful in 3m41s
2026-11-18 11:25:47 +01:00
lilleman 30648af4d3 Merge remote-tracking branch 'origin/main' into add-license
CI / tests (pull_request) Successful in 3m26s
2026-11-18 10:56:32 +01:00
lilleman 94a6a0f8c8 Merge remote-tracking branch 'origin/main' into item-402
CI / tests (pull_request) Successful in 3m13s
2026-11-18 10:54:09 +01:00
lilleman ea22530878 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); refuse a write that repeats a section
CI / tests (pull_request) Successful in 2m52s
2026-11-18 10:54:03 +01:00
lilleman 0018508657 Add MIT license for Larv IT AB
CI / tests (pull_request) Successful in 2m51s
2026-11-18 10:50:47 +01:00
lilleman 8072382dbc Finish item 403 in the plan
CI / tests (pull_request) Successful in 3m25s
2026-11-18 10:49:42 +01:00
lilleman d9fb8b0d97 Merge remote-tracking branch 'origin/main' into item-403
CI / tests (pull_request) Successful in 3m29s
2026-11-18 10:49:08 +01:00
lilleman 3f5fd41226 Answer prose round 1: 0 🔴, 10 🟡 (0 misread); reworded the help, README, docstrings and error text 2026-11-18 10:48:47 +01:00
lilleman c10dd996aa Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); the refusal names the Jira edit, README and help state the markdown rewrite, CLAUDE.md corrected 2026-11-18 10:48:47 +01:00
lilleman b163dadbbd Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword the searched docstring, the store's docstrings and the tests' names 2026-11-18 10:46:07 +01:00
lilleman a29d2a2315 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); check every field a read takes, ask for a parent by its key, and sort labels 2026-11-18 10:46:07 +01:00
lilleman 5d4c6b3237 Kill the mutants of the digest-based version 2026-11-18 10:44:06 +01:00
lilleman fe351d3ed4 Answer stability round 1: 1 🔴, 4 🟡 (0 misread); check Goals and Audience on the document that is sent, report an unknown section as a Failure, refuse a section body that holds a heading, correct the stale read-only text 2026-11-18 10:39:22 +01:00
lilleman 080a6a8693 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-18 10:30:48 +01:00
lilleman b93d3799c3 Answer round 1: check the model against the ladder, keep faults together, fix prose
CI / tests (pull_request) Successful in 2m36s
2026-11-18 10:28:39 +01:00
lilleman 9d1d25218f Test the Jira backend against answers of another kind and a filing's endless search 2026-11-18 10:28:31 +01:00
lilleman 0755291112 Kill the mutants of the epic description write
CI / tests (pull_request) Successful in 2m48s
2026-11-18 10:26:23 +01:00
lilleman 9e47b0d566 Write a Jira epic's description by section, and change its Goals and Audience only once the human approves 2026-11-18 10:21:21 +01:00
lilleman 61ed465e99 Hold the Jira backend's fake to credentials, JQL, fields and issue types, and test its failures 2026-11-18 10:17:45 +01:00
lilleman aa968b9662 Finish item 398 in the plan
CI / tests (pull_request) Successful in 2m51s
2026-11-18 10:14:50 +01:00
lilleman f901ba091d Merge remote-tracking branch 'origin/main' into item-398 2026-11-18 10:14:49 +01:00
lilleman 848f40f0c6 Finish item 399 in the plan
CI / tests (pull_request) Successful in 2m46s
2026-11-18 10:05:41 +01:00
lilleman 13a70bfb49 Answer stability round 2: 2 🔴, 0 🟡 (0 misread); cite the bullet's full lead, ship the plan file by pull request
CI / tests (pull_request) Successful in 2m46s
2026-11-18 10:02:59 +01:00
lilleman b34d1087ca Sort do_epic/config.py's imports as the repo check requires
CI / tests (pull_request) Successful in 2m37s
2026-11-18 09:59:53 +01:00
lilleman e2977b4946 Track the do_epic package, which the gitignore allowlist left out 2026-11-18 09:56:02 +01:00
lilleman 34694d321e Answer stability round 2: 0 🔴, 1 🟡 (0 misread); require the clean run for the mutant exemption
CI / tests (pull_request) Successful in 2m53s
2026-11-18 09:55:55 +01:00
lilleman ed3a66e085 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); fixed in the stability answer above 2026-11-18 09:55:28 +01:00
lilleman 02e950dbc2 Answer stability round 1: 1 🔴, 2 🟡 (0 misread); file the setup item from a worktree of claude-config, name claude-config's places 2026-11-18 09:55:28 +01:00
lilleman 3525366485 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); cite the right audit and cut wording 2026-11-18 09:54:41 +01:00
lilleman c20ef6e81a Answer stability round 1: 1 🔴, 2 🟡 (0 misread); exclude mutant-killing fixes and narrow the test-change row 2026-11-18 09:54:41 +01:00
lilleman 4678ac6798 Name do-epic's env-file among the credentials rule-hook guards
CI / tests (pull_request) Successful in 3m15s
2026-11-18 09:54:39 +01:00
lilleman 6b07e19c34 Read and file an epic's child issues and sub-tasks through a do-epic backend interface
CI / tests (pull_request) Failing after 3m21s
2026-11-18 09:54:35 +01:00
lilleman 31b8edb4c9 Read do-epic's machine-wide settings and repo rule, and refuse to start while either is missing or misspelt 2026-11-18 09:51:12 +01:00
lilleman 6c52766a27 Rerun the pass that raised a 🟡 when its fix changes what a test asserts or whether it runs
CI / tests (pull_request) Successful in 3m2s
2026-11-18 09:49:26 +01:00
lilleman 43dfd375b8 Append one reading-cost figure 2026-11-18 09:49:26 +01:00
lilleman 232327d893 Reflect on each outside reviewer's fix and change the setup so review would have caught it
CI / tests (pull_request) Successful in 3m10s
2026-11-18 09:49:13 +01:00
lilleman fbdc6124df Drop item 405: answered, the sandbox is larvit.atlassian.net's SCRUM project
CI / tests (pull_request) Successful in 2m47s
2026-11-18 09:37:57 +01:00
lilleman 53b9602982 Plan do-epic into release 0.12.0 as items 401 to 418, and record its design
CI / tests (pull_request) Successful in 2m52s
2026-11-18 09:34:41 +01:00
lilleman dd72667c1f Move items 339, 341 and 298 to release 0.13.0
CI / tests (pull_request) Successful in 2m58s
2026-11-18 08:28:27 +01:00
lilleman 0f1ee8767c File items 398, 399 and 400 2026-11-18 08:28:21 +01:00
lilleman 0aec288e75 Append two reading-cost figures
CI / tests (pull_request) Successful in 3m29s
2026-11-17 12:42:10 +01:00
lilleman d615a53fa1 Block item 341 on item 311, whose chunk builds the replay's Change 2026-11-17 12:42:10 +01:00
lilleman c40f16ba5d Finish item 396 in the plan
CI / tests (pull_request) Successful in 3m27s
2026-11-17 12:32:08 +01:00
lilleman 7446b7199b Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 3m28s
2026-11-17 12:10:45 +01:00
lilleman fd9215ac9c Kill markdown-section's help and end-of-section mutants 2026-11-17 12:09:15 +01:00
lilleman 7460454d93 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); reject an empty fragment 2026-11-17 11:52:41 +01:00
lilleman eddfd743e9 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword the help, split CLAUDE.md's sentence, give the packages their own heading 2026-11-17 11:52:41 +01:00
lilleman 4cdc1c4be9 Answer stability round 1: 1 🔴, 3 🟡 (0 misread); reuse the markdown reader, list rival headings, test by table 2026-11-17 11:52:36 +01:00
lilleman 1a9df179a8 Test markdown-section's main in process, and the end of a section 2026-11-17 09:27:00 +01:00
lilleman d051c4ffe8 Print one section of a markdown file, picked by a fragment of its heading, with markdown-section
CI / tests (pull_request) Successful in 4m23s
2026-11-17 09:16:46 +01:00
lilleman 641645c081 Finish item 338 in the plan
CI / tests (pull_request) Successful in 3m52s
2026-11-17 09:05:18 +01:00
lilleman b3c95c2c3d Audit 0.9.0's chunks: file 1 scripted step, and the audit again for 0.15.0
CI / tests (pull_request) Successful in 3m46s
2026-11-17 09:05:11 +01:00
lilleman a25b603766 Finish item 387 in the plan
CI / tests (pull_request) Successful in 3m52s
2026-11-17 08:55:06 +01:00
lilleman 49d1a6cb97 Finish item 393 in the plan 2026-11-17 08:55:06 +01:00
lilleman 4faf6f386e Merge remote-tracking branch 'origin/main' into item-387 2026-11-17 08:55:05 +01:00
lilleman 51fe0cea96 Finish item 327 in the plan
CI / tests (pull_request) Successful in 3m25s
2026-11-17 08:43:54 +01:00
lilleman 697872368a Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 3m45s
2026-11-17 08:41:37 +01:00
lilleman bfde3ffecb Answer prose round 1: 0 🔴, 6 🟡 (0 misread); the comments, the presentation and the routing decision state the new steps
CI / tests (pull_request) Failing after 3m51s
2026-11-17 08:41:04 +01:00
lilleman 7b9e43e2bd Answer stability round 1: 0 🔴, 3 🟡 (0 misread); the prompt tests route on rungs the new steps reach, and pin the rung the human must agree to 2026-11-17 08:41:04 +01:00
lilleman 12e57372cd Test that a report counts a 🔴 beside a 🟡, and that BLOCK after a blank line still blocks
CI / tests (pull_request) Successful in 3m49s
2026-11-17 08:39:50 +01:00
lilleman cb6dd6d3a7 Answer stability round 1: 1 🔴, 1 🟡 (0 misread); refuse to count a report whose headings hold a mark in another form, and test the hook's report lookup
CI / tests (pull_request) Successful in 3m12s
2026-11-17 08:30:22 +01:00
lilleman b43f2242c5 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); refuse to count a blocking report with no finding headings, and say to count by hand 2026-11-17 08:26:17 +01:00
lilleman 8fa05d9551 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); reword the round-title help, Count rule, refusal and docstrings 2026-11-17 08:25:45 +01:00
lilleman 3f0d5f0017 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-17 08:18:27 +01:00
lilleman 548c4ea125 Test that an unreadable round report is named 2026-11-17 08:16:54 +01:00
lilleman 64ab847b0a Bind a project's rung to its ladder in ProjectRung, and step an L 3 worker one rung up and an L 4 worker two up
CI / tests (pull_request) Failing after 3m48s
2026-11-17 08:12:16 +01:00
lilleman 7c4bef6332 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-17 08:02:50 +01:00
lilleman 351bbc022f Sort the new modules' imports by their first binding
CI / tests (pull_request) Successful in 4m16s
2026-11-17 07:52:33 +01:00
lilleman 934a398be0 Have larv-review round-title print a round commit's counts from its report, and rule-hook refuse a title that differs 2026-11-17 07:47:45 +01:00
lilleman 3543d9e964 Merge remote-tracking branch 'origin/main' into item-309
CI / tests (pull_request) Successful in 4m6s
# Conflicts:
#	docs/reading-cost.md
#	todo.md
2026-11-17 07:31:42 +01:00
lilleman d57ce9b1be Answer prose round 1: 0 🔴, 3 🟡 (0 misread); item 309's detail says once which verdict decides it and when it moved
CI / tests (pull_request) Successful in 4m20s
2026-11-17 07:17:33 +01:00
lilleman 268046a6ab Merge remote-tracking branch 'origin/main' into item-319
CI / tests (pull_request) Successful in 3m56s
2026-11-17 07:15:37 +01:00
lilleman a7dbe00c89 Move item 309 to 0.13.0, since agreement has 6 of the 10 commits it needs scored twice
CI / tests (pull_request) Successful in 3m41s
2026-11-17 07:15:20 +01:00
lilleman 9db706946d Answer prose round 1: 0 🔴, 2 🟡 (0 misread); the bullet counts six chunks and the five that went on
CI / tests (pull_request) Successful in 3m53s
2026-11-17 07:15:03 +01:00
lilleman b1c31f93bc Drop item 319: its bench did not favour a fresh session over resuming, and lilleman dropped it
CI / tests (pull_request) Successful in 4m6s
2026-11-17 07:13:20 +01:00
lilleman 53496587be Move item 395 to release 0.13.0, as lilleman chose
CI / tests (pull_request) Successful in 4m6s
2026-11-17 07:11:14 +01:00
lilleman e6d4321f6c Finish item 389 in the plan
CI / tests (pull_request) Successful in 4m19s
2026-11-17 06:46:29 +01:00
lilleman 58c0e64fb9 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); the round 1 fix stands
CI / tests (pull_request) Successful in 3m41s
2026-11-17 06:46:19 +01:00
lilleman c1b278d2ea Kill the surviving mutants of the blocking-loop check
CI / tests (pull_request) Successful in 3m32s
2026-11-17 06:43:21 +01:00
lilleman 461b88d4ee Clear item 389's decision exemption, since this chunk revised the decision that cited it 2026-11-17 06:37:55 +01:00
lilleman 89fb819fbe Answer stability round 1: 0 🔴, 1 🟡 (0 misread); refuse a blocker loop and link a blocker named twice once
CI / tests (pull_request) Failing after 3m48s
2026-11-17 06:28:17 +01:00
lilleman c988bd61b4 Kill the two surviving mutants of the link edit 2026-11-17 05:54:31 +01:00
lilleman 8581aba41f Answer prose round 1: 3 🔴, 4 🟡 (0 misread); fold the link rule into the edit decision and correct three claims 2026-11-17 05:12:53 +01:00
lilleman 5a757bae1f Answer product-owner round 1: 1 🔴, 0 🟡 (0 misread); delete only the links to open items, and leave other links as they are 2026-11-17 05:12:53 +01:00
lilleman 72b8dd3263 Set a Jira issue's blocked-by links from todo-item edit --blocked-by on an issue the loop filed 2026-11-17 04:51:04 +01:00
lilleman 6eea7e5522 Record the reading cost of item 389's chunk 2026-11-17 04:51:04 +01:00
lilleman 1cdfda168a Finish item 331 in the plan
CI / tests (pull_request) Successful in 4m59s
2026-11-17 04:37:01 +01:00
lilleman 9dae3d9dd5 Finish item 288 in the plan 2026-11-17 04:37:00 +01:00
lilleman edbeefe99c Finish item 381 in the plan 2026-11-17 04:36:59 +01:00
lilleman 176e5b7a66 Merge remote-tracking branch 'origin/main' into item-381
CI / tests (pull_request) Successful in 4m34s
# Conflicts:
#	docs/reading-cost.md
2026-11-17 04:27:37 +01:00
lilleman 8a6c5102df Answer stability round 1: 0 🔴, 0 🟡 (0 misread); a comment records that a name opening and ending in a space isn't read back from Jira 2026-11-17 04:27:12 +01:00
lilleman a87b9a4d16 Fold the blank-text and length guards of code_span into one padding rule, which the hand mutants of its lines all fail 2026-11-17 04:23:01 +01:00
lilleman 242be1db34 Merge remote-tracking branch 'origin/main' into item-319
CI / tests (pull_request) Successful in 3m24s
# Conflicts:
#	todo.md
2026-11-17 04:01:42 +01:00
lilleman 376a5a8323 Ask whether item 319 is dropped after its bench 2026-11-17 04:01:29 +01:00
lilleman 07674b2c20 Answer prose round 1: 1 🔴, 3 🟡 (0 misread); the decision states what the judge saw, what the brief held and why five items ran 2026-11-17 03:58:52 +01:00
lilleman 4875e07f98 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); refuse a failed compaction and count the starts' turns as claude does 2026-11-17 03:58:52 +01:00
lilleman b4490b4a8c Refuse a compact arm whose compaction failed, and state the bench as it ran 2026-11-17 03:56:25 +01:00
lilleman 2e44ec95ca Answer prose round 1: 0 🔴, 7 🟡 (0 misread); the codec pads on a space at both ends too, and the Valid lines name the event that expires them 2026-11-17 03:51:51 +01:00
lilleman 24800c156b Assert that the start's saved diff holds an untracked file 2026-11-17 03:51:01 +01:00
lilleman 7da82b4748 Hold the handoff bench's prompts, saved change and steps to their tests 2026-11-17 03:48:46 +01:00
lilleman f56962cd8d Test that a longer run keeps a space at one end only 2026-11-17 03:48:21 +01:00
lilleman a924cd2647 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-17 03:46:06 +01:00
lilleman 20edbcdd21 Record that a stepped worker keeps resuming its session, after the handoff bench
CI / tests (pull_request) Failing after 2m47s
2026-11-17 03:45:08 +01:00
lilleman 1bc2ce89e7 Net a resumed arm's cost of the start it resumes 2026-11-17 03:44:53 +01:00
lilleman 7e7bc4a20c Finish item 391 in the plan
CI / tests (pull_request) Successful in 2m52s
2026-11-17 03:37:14 +01:00
lilleman 7931f8c9d3 Merge remote-tracking branch 'origin/main' into item-391
CI / tests (pull_request) Successful in 2m51s
2026-11-17 03:35:38 +01:00
lilleman 2a24488a37 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); the change delivers item 391, and item 395's release is the human's call 2026-11-17 03:35:37 +01:00
lilleman 48c65b9ba4 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); both answers hold 2026-11-17 03:35:37 +01:00
lilleman 0090f87351 Assert the whole refusal of a save over a teammate's version, and the version read before an unedited save 2026-11-17 03:23:50 +01:00
lilleman 7e3204a089 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); the codec's docstring and the decision say which pair the loop uses and why, the entry sits in order, and item 395 names its parts once 2026-11-17 03:12:16 +01:00
lilleman a1e72d98f1 Sort the new import in the touch-predictions tests 2026-11-17 03:11:26 +01:00
lilleman 432b62aa08 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); an unedited save over a version a teammate moved refuses, and a test asserts the PUT rather than the token 2026-11-17 03:11:17 +01:00
lilleman c3745ca03f Read a Touches list from a Jira description, as the codec spells it, and reword four decisions' expiry and two reading-cost goal citations
CI / tests (pull_request) Failing after 3m8s
2026-11-17 03:01:46 +01:00
lilleman e42eb5b288 Bench a model step's handoff: resume, compact or a fresh session with a brief 2026-11-17 02:57:22 +01:00
lilleman 51917dfd6c Answer security round 1: 0 🔴, 0 🟡 (0 misread); clean 2026-11-17 02:54:05 +01:00
lilleman b7ec782282 Leave a Jira description or a Confluence page as it is where a save hands back the text a read showed
CI / tests (pull_request) Successful in 3m1s
2026-11-17 02:53:28 +01:00
lilleman 75ae8639ab Record the reading cost before item 391's first commit 2026-11-17 02:53:28 +01:00
lilleman ed9ab534f8 Finish item 306 in the plan
CI / tests (pull_request) Successful in 2m59s
2026-11-17 02:52:33 +01:00
lilleman 879dae4960 Merge remote-tracking branch 'origin/main' into item-306
CI / tests (pull_request) Successful in 3m6s
2026-11-17 02:50:24 +01:00
lilleman 192b9feda2 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); the copied-today test gives the file an mtime a month old, so it fails where age reads mtime alone 2026-11-17 02:50:20 +01:00
lilleman 3a77ebdb0d Re-score item 319 to L 4, S 5 after counting its size 2026-11-17 02:46:41 +01:00
lilleman 74d69fedfb Walk the test's mocked tree past a gzip and a link, killing the walk's break mutant 2026-11-17 02:40:20 +01:00
lilleman 97af00ef35 Finish item 304 in the plan
CI / tests (pull_request) Successful in 2m45s
2026-11-17 02:35:27 +01:00
lilleman 47c8fd2963 Merge remote-tracking branch 'origin/main' into item-304
CI / tests (pull_request) Successful in 2m42s
2026-11-17 02:33:49 +01:00
lilleman b8a1a13ad0 Answer prose round 1: 0 🔴, 8 🟡 (0 misread); the help texts say where the runs go, the decision gets its own dated paragraph, and the comments reread 2026-11-17 02:33:40 +01:00
lilleman eb64154384 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); name the transcripts and review files the tool takes, scope the readers' claim, and rewrite the flagged comments
CI / tests (pull_request) Successful in 2m59s
2026-11-17 02:33:15 +01:00
lilleman 6d1a4a05c9 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); age a file by when it landed too, log every cron run with its date, and say when cron needs PATH or LOOP_CLAUDE_TRANSCRIPTS set 2026-11-17 02:33:15 +01:00
lilleman 04904180d5 Answer stability round 1: 1 🔴, 3 🟡 (0 misread); sort the new files' imports, sync the gzip before removing the file, read the plain file then its gzip without a check between, and age a file by the later of its mtime and ctime 2026-11-17 02:33:15 +01:00
lilleman 48e69063b8 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); a kept run's header records claude's exit code and stderr 2026-11-17 02:33:12 +01:00
lilleman c7248165db Answer stability round 1: 0 🔴, 1 🟡 (0 misread); the comment on a usage limit's reset time says the stream holds it, and the no-json message quotes the last line only 2026-11-17 02:33:04 +01:00
lilleman 5d10871ab5 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-17 02:18:36 +01:00
lilleman 4f766f7ab2 Kill the report folder's mode mutant 2026-11-17 02:17:50 +01:00
lilleman abe30ab893 Make the vanished-file test reach the stat it fails on, killing the walk's break mutant 2026-11-17 02:16:18 +01:00
lilleman 4c0378c2d0 Kill the archive's mode, encoding and report-failure mutants 2026-11-17 02:09:27 +01:00
lilleman f0bd187cd7 Kill the surviving mutants of the compressor, its CLI and the report copy's time bounds 2026-11-17 02:09:08 +01:00
lilleman 62a2df4545 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-17 02:01:19 +01:00
lilleman b9876c17fe Gzip loop-claude's archive and the review folders 30 days after each file was last written, and read gzipped files by their plain name
CI / tests (pull_request) Failing after 2m59s
2026-11-17 02:00:32 +01:00
lilleman 7b0e4d013e Record the reading cost of item 306's chunk 2026-11-17 02:00:32 +01:00
lilleman cc51901717 Sort the test's imports and type the archiving run 2026-11-17 01:52:05 +01:00
lilleman 5aabbc87bf Archive each review-replay and judge-replay run's transcript beside its result
CI / tests (pull_request) Failing after 2m52s
2026-11-17 01:49:49 +01:00
lilleman c3a3a9a82f Merge remote-tracking branch 'origin/main' into predict-touches
CI / tests (pull_request) Successful in 2m59s
2026-11-17 01:37:44 +01:00
lilleman f2a4347d78 Finish item 303 in the plan
CI / tests (pull_request) Successful in 2m54s
2026-11-17 01:31:56 +01:00
lilleman afd7abaa5e Merge remote-tracking branch 'origin/main' into item-303
CI / tests (pull_request) Successful in 2m53s
2026-11-17 01:30:19 +01:00
lilleman e1e9d03df1 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the report names the prompt each missed verdict was replayed on, the help says where records change the kind, and the decision drops pricing from usage 2026-11-17 01:30:15 +01:00
lilleman b067d8cda8 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); the run-pairing test holds each prompt with its reply again, and the task heading test now kills its mutant 2026-11-17 01:30:15 +01:00
lilleman d9fd60a714 Predict touches for release 0.12.0 items
CI / tests (pull_request) Successful in 3m29s
2026-11-17 01:27:26 +01:00
lilleman 38544dd2d3 Kill the task heading mutant of the archived prompt's split 2026-11-17 01:25:07 +01:00
lilleman 2f0708f390 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); the decision entry and the help text reworded with the measurement redone, the title names the judge runs, and the hash comments say prompt and reply 2026-11-17 01:15:35 +01:00
lilleman 2600fbb254 Answer stability round 1: 1 🔴, 5 🟡 (0 misread); imports sorted, the replay cuts the task and the rules from its grounds and fails on a missing heading, outcome parameters keyword-only, the mtime order dropped 2026-11-17 01:13:39 +01:00
lilleman b5afb4c36a Kill the mutants of the judge run archive that its tests missed 2026-11-17 00:51:39 +01:00
lilleman 27a4f838e5 Finish item 287 in the plan
CI / tests (pull_request) Successful in 2m59s
2026-11-17 00:11:53 +01:00
lilleman c0f3b2fc10 Merge remote-tracking branch 'origin/main' into item-287
CI / tests (pull_request) Successful in 2m58s
2026-11-17 00:10:11 +01:00
lilleman d0dd62c998 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); the README's package list matches the imports 2026-11-17 00:10:10 +01:00
lilleman fe7e05da5a Answer stability round 1: 0 🔴, 0 🟡 (0 misread); the duplicate import and the head-pinning claims went with the prose answer 2026-11-17 00:10:10 +01:00
lilleman 92ffec7949 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); the docstrings claim head-pinning only where a call takes head, and the wait comments name the forge each covers 2026-11-17 00:10:10 +01:00
lilleman e4529bee9c Finish item 394 in the plan
CI / tests (pull_request) Successful in 3m7s
2026-11-17 00:02:47 +01:00
lilleman 8c17462321 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); the error text now names Jira
CI / tests (pull_request) Failing after 3m5s
2026-11-17 00:01:09 +01:00
lilleman 315b4da925 Answer stability round 1: 0 🔴, 0 🟡 (0 misread); the Otherwise nit and the preflight count are answered in the summary 2026-11-17 00:01:09 +01:00
lilleman 2c504133b8 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); the Jira sentence moves after the finish sentence, the help and error text name Jira, and the test names lose the negation 2026-11-17 00:01:09 +01:00
lilleman 1c031866a4 Answer security round 1: 0 🔴, 0 🟡 (0 misread); the indentation note was fixed as a style change 2026-11-16 23:58:50 +01:00
lilleman 1598b6178e Indent the Jira finish call as its case's other bodies 2026-11-16 23:58:40 +01:00
lilleman 9f4ccbe111 Pin the forge helpers' failure reasons and the give-up's read count in tests 2026-11-16 23:52:55 +01:00
lilleman ac9566510c Test that a failing finish in a Jira plan says not finished 2026-11-16 23:49:16 +01:00
lilleman d6226070db Answer security round 1: 0 🔴, 0 🟡 (0 misread); the move adds no attack surface 2026-11-16 23:44:02 +01:00
lilleman e1d2eae7f4 Archive each judge run's prompt and json reply beside the verdict it gave, and replay from the archived prompt
CI / tests (pull_request) Failing after 2m45s
2026-11-16 23:42:36 +01:00
lilleman 73600d7288 Move the forge helpers into bin/forge/, which chunk_preflight, chunk_pr, deploy_release and larv_review import
CI / tests (pull_request) Successful in 3m9s
2026-11-16 23:42:01 +01:00
lilleman 3afbb55451 Write no changelog bullet for a plan kept in Jira: todo-item finish there needs no changelog flag and refuses --changelog
CI / tests (pull_request) Successful in 3m17s
2026-11-16 23:40:13 +01:00
lilleman 4b5086153a Make the Touches lists of items 303, 306, 287 and 387 readable: mark only named parts small
CI / tests (pull_request) Successful in 3m14s
2026-11-16 23:33:26 +01:00
lilleman 5bb49dc623 File item 394 and move items 303, 306, 304, 287, 387, 338 and 288 into 0.12.0
CI / tests (pull_request) Successful in 3m21s
2026-11-16 23:23:24 +01:00
129 changed files with 5151 additions and 871 deletions
+6
View File
@@ -1,6 +1,12 @@
name: CI name: CI
on: pull_request on: pull_request
# A push to a pull request cancels that pull request's older runs; the merge gate reads only the head commit's status.
# The group is per pull request, so pull requests never cancel each other's runs.
concurrency:
group: ci-pr-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs: jobs:
tests: tests:
runs-on: docker-host runs-on: docker-host
+17
View File
@@ -8,6 +8,7 @@
!.gitignore !.gitignore
!CHANGELOG.md !CHANGELOG.md
!CLAUDE.md !CLAUDE.md
!LICENSE.md
!README.md !README.md
!ci.sh !ci.sh
!settings.json !settings.json
@@ -47,10 +48,19 @@
!bin/command_lines/*.py !bin/command_lines/*.py
!bin/command_patterns/ !bin/command_patterns/
!bin/command_patterns/*.py !bin/command_patterns/*.py
!bin/compress-archives
!bin/compress_archives/
!bin/compress_archives/*.py
!bin/deploy-release !bin/deploy-release
!bin/deploy_release/ !bin/deploy_release/
!bin/deploy_release/*.py !bin/deploy_release/*.py
!bin/do_epic/
!bin/do_epic/*.py
!bin/do_epic/backend/
!bin/do_epic/backend/*.py
!bin/failure.py !bin/failure.py
!bin/forge/
!bin/forge/*.py
!bin/git_cli/ !bin/git_cli/
!bin/git_cli/*.py !bin/git_cli/*.py
!bin/judge-replay !bin/judge-replay
@@ -69,6 +79,9 @@
!bin/loop_state/*.py !bin/loop_state/*.py
!bin/machine_load/ !bin/machine_load/
!bin/machine_load/*.py !bin/machine_load/*.py
!bin/markdown-section
!bin/markdown_section/
!bin/markdown_section/*.py
!bin/metric-bench !bin/metric-bench
!bin/metric_bench/ !bin/metric_bench/
!bin/metric_bench/*.py !bin/metric_bench/*.py
@@ -182,9 +195,13 @@
!workflow-bench/bench.py !workflow-bench/bench.py
!workflow-bench/compare-prompt.md !workflow-bench/compare-prompt.md
!workflow-bench/compare.py !workflow-bench/compare.py
!workflow-bench/handoff-brief-prompt.md
!workflow-bench/handoff-resume-prompt.md
!workflow-bench/handoff_bench.py
!workflow-bench/review_git.py !workflow-bench/review_git.py
!workflow-bench/run-prompt.md !workflow-bench/run-prompt.md
!workflow-bench/setup.cfg !workflow-bench/setup.cfg
!workflow-bench/test_advisor_bench.py !workflow-bench/test_advisor_bench.py
!workflow-bench/test_bench.py !workflow-bench/test_bench.py
!workflow-bench/test_handoff_bench.py
!workflow-bench/test_review_git.py !workflow-bench/test_review_git.py
+19
View File
@@ -1,5 +1,24 @@
# Changelog # Changelog
## Unreleased
- do-epic reads its machine-wide settings from ~/.claude-projects/do-epic/config.toml and its repo rule from repo-rule.md beside it, and refuses to start while either is missing or misspelt.
- `project-record save` now writes a goals file kept as a Jira epic's description, except a change to `## Goals` or `## Audience`, which stays an edit in Jira.
- Add do-epic's epic backend: one interface that reads a Jira epic's child issues and their sub-tasks, with labels, assignee, status and parent, and files new ones, met by a Jira backend and an in-memory fake that pass the same contract tests.
- Fix for an outside reviewer's comment on a PR now ends with a change to the setup that would have caught it, in claude-config first, then the principles and standards, then the project.
- larv-review reruns the pass that raised a 🟡 when the fix removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test. Other 🟡 fixes still rerun no pass.
- Add `markdown-section <file> <fragment>`, which prints the section of a markdown file under the heading the fragment picks, to the next heading of its level or a higher one. It fails, listing the headings, where several hold the fragment.
- loop-claude and subagent-rung run an L 3 task one rung above the project's rung and an L 4 task two above it: on an Opus 5.5 project, Fable 5.2 at low and at medium.
- Add `larv-review round-title <pass>`, which prints a review round commit's title prefix with the 🔴, 🟡 and misread counts taken from the round's report. rule-hook refuses a round commit whose counts differ from that report, where the report exists and can be counted; a report must head each finding `### 🔴` or `### 🟡`, optionally followed by ` [misread]`.
- Add `workflow-bench/handoff_bench.py`, a bench of how a worker's step to a stronger model hands over the chunk, on six archived L 3 chunks. Sonnet 5.5 left five unfinished at its budget. On those, Opus 5.5 resuming Sonnet 5.5's session passed two and was partial on three, for a mean $0.68; a fresh session with a brief passed one and was partial on four, for $0.78. So a stepped worker still resumes its session.
- todo-item edit --blocked-by sets the "is blocked by" links of a Jira issue the loop filed.
- A `Touches:` list in the description of a Jira issue is read as one in `todo.md` is, a path or name that holds a backtick included: the Jira description spells it in backticks with no padding spaces, and the prediction reader takes that spelling too.
- `todo-item edit --detail` and `project-record save` leave a Jira description or a Confluence page exactly as it is, with its block ids and spacing paragraphs, where the text saved is the text a read showed. An unedited save over a page a teammate saved since still refuses.
- Add `compress-archives`, which gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them. The tools that read those folders read a gzipped file by its plain name. A new crontab line in the README's Install section runs it daily.
- review-replay and judge-replay keep each run, with its prompt, claude's exit code and stream, and the report they print, in a `replays/<tool>-<arguments>-<UTC stamp>/` folder of loop-claude's archive, so a replay that decided a rung can be checked and re-priced later; claude's json replies are now stream-json, whose last line is the reply.
- loop-claude's archive keeps each judge run's prompt and json reply in a judge/ folder beside its chunk's transcripts, and names the run on a `Judge run:` line of the outcome it produced; judge-replay replays a verdict on its archived prompt where the archive holds one.
- A plan kept as a Jira epic takes no changelog bullet: `todo-item finish` there needs neither `--changelog` nor `--no-changelog`, and refuses `--changelog`, since the issues' history is the changelog.
## 0.11.0 ## 0.11.0
- `adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet. - `adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet.
+9 -3
View File
@@ -13,12 +13,18 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **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. - **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.
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice. - **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
- **Read the goals file'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 goals file'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; run `todo-item` only for what they leave out. Otherwise run `~/.claude/bin/todo-item list`, which prints every item's row in the plan's order, without details. Then read the details of only the items the chunk takes, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `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. - **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; run `todo-item` only for what they leave out. Otherwise run `~/.claude/bin/todo-item list`, which prints every item's row in the plan's order, without details. Then read the details of only the items the chunk takes, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `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. Print one entry with `~/.claude/bin/markdown-section <file> <fragment of its title>`, where `<file>` is what `~/.claude/bin/project-record open decisions` prints.
- **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 the plan, 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 the plan before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`. - **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 the plan, 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 the plan 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 the goals file, 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 goals file, and record as a choice only what the goal leaves open. - **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 the goals file, 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 goals file, 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 goals file's `## Audience`, picks it. - **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 goals file'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 in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding. - **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 in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding.
- **Remove a finished item from the plan, 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 item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5). - **Change the setup for each reasonable fix an outside reviewer asked for on a PR.** An outside reviewer is a forge's auto-reviewer or a human, not one of larv-review's reviewer agents. When you fix a comment of theirs, ask why our review didn't catch the fault first, and change the setup so it would; a fix that only answers the comment leaves the same gap open for the next chunk. Put the change in the first place that fits:
1. claude-config's core: the reviewers' agents, `larv-review`, the hooks and tools, so every project gains.
2. claude-config's technical principles or review standards, where a rule was missing or too vague.
3. The project's own settings, principles folder or `AGENTS.md`, only where the gap is that project's alone. A client repo's `AGENTS.md` changes by a proposal of its own, per "A client project's `CLAUDE.md` and `AGENTS.md`" above.
In claude-config, the change is a fix of the chunk. In another project, places 1 and 2 are an item in claude-config's plan: start a worktree of claude-config off `origin/main`, run `todo-item add` in it, commit the plan file, and ship it as a pull request of its own with `chunk-pr`, since claude-config's default branch may not take a direct push. Describe the gap without the client's name, code or comment text. File a change too big for the chunk as its own item. Where no place holds the gap, say so in the chunk's summary rather than inventing a change.
- **Remove a finished item from the plan, 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 item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item. A plan kept in Jira takes no bullet, since the issues' history is its changelog: `finish` there refuses `--changelog`. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5).
- **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. - **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 plan 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`. - **Open each plan 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. - **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.
@@ -128,7 +134,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. - **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records. - **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges. - **gate** — the merge gate: the checks a PR passes before it merges.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, which the loop only reads. - **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, whose `## Goals` and `## Audience` the loop only reads.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed. - **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/`, then those in the project's review standards. - **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/`, then those in the project's review standards.
+21
View File
@@ -0,0 +1,21 @@
# MIT License
Copyright (c) 2026 Larv IT AB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+24 -11
View File
@@ -73,6 +73,14 @@ Then pick a model with `/model`.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. loop-claude runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later. Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. loop-claude runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later.
Back up two folders: `~/.claude/loop-claude-transcripts`, where loop-claude keeps every transcript, and `~/.local/state/larv-review`, where larv-review keeps each chunk's reports. To keep them small, add a crontab line that gzips each transcript and review file 30 days after it last changed, and logs each run with its date:
```sh
17 4 * * * { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/compress-archives.log 2>&1
```
Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `LOOP_CLAUDE_TRANSCRIPTS`, set `PATH` or that variable in the crontab too.
To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes. To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
### Set up a project ### Set up a project
@@ -124,9 +132,9 @@ A read fails, naming the issue, where a child is in another Jira project or name
The loop reads such a plan and files items into it, each as a Task under the epic. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. The config states the formula and the bar that a todo.md states under `## Scoring`, such as `jira-score-formula = "100 * V / (2**S + 8)"` and `jira-score-bar = 1`, and fails to load without them. `todo-item add` refuses an item that scores under the bar, unless it is exempt. It ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep the rank the team gave them, and `rank_todo.py` doesn't rank the plan. The loop reads such a plan and files items into it, each as a Task under the epic. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. The config states the formula and the bar that a todo.md states under `## Scoring`, such as `jira-score-formula = "100 * V / (2**S + 8)"` and `jira-score-bar = 1`, and fails to load without them. `todo-item add` refuses an item that scores under the bar, unless it is exempt. It ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep the rank the team gave them, and `rank_todo.py` doesn't rank the plan.
`todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do every issue's links. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either. `todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do its links. On an issue the loop filed, `edit --blocked-by` makes and deletes the links to the epic's open items. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals. A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. `project-record open goals-and-audience` prints a file holding the description's text, and `project-record save` writes it back, except a change to `## Goals` or `## Audience`: edit those two in Jira. A save rewrites the whole description from markdown, which keeps no mention, macro or block id that markdown can't hold. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work. To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work.
@@ -166,15 +174,17 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
## Tools ## Tools
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks; once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps. - `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks; once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts. - `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys. - `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
- `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily.
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says. - `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. - `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
- `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 and setup; 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. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. - `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 and the opening of its round commit's title, the scoring run's trigger and setup; 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. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
- `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract. - `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract.
- `markdown-section <file> <fragment>` prints the section of a markdown file under the first heading that holds the fragment, to the next heading of its level or a higher one, instead of a `grep -n` and a guessed `sed -n` range; `markdown-section --help` says what it does where several headings match.
- `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. - `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. - `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.
- `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one. - `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one.
@@ -190,18 +200,21 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter. - `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `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 on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. - `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 on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`. Each change ranks a markdown plan. `todo-item --help` states the flags. - `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once. - `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it. - `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
`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. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. ### Packages under `bin/`
`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. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. - `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages.
- `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. - `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.
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
- `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`. - `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`.
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`. - `deploy_release` imports `release_plan`'s `release_standing`.
- `do_epic/` will hold the tool that drives one Jira epic. So far `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section and language line, through `record_store`'s `EpicDescription`.
- `forge/` tells a GitHub origin from a Gitea one and runs that forge's CLI (`commands.py`), and finds a pull request and waits for its checks (`pulls.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review`.
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `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, verdicts, premises and records. - `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
- `loop_claude` runs `chunk-preflight` as a process of its own. - `loop_claude` runs `chunk-preflight` as a process of its own.
@@ -211,7 +224,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`) and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises. - `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`) and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` a plan in memory. - `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use. - `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, and picks the item the next chunk takes first (`next_chunk.py`), for `chunk_preflight` and `loop_claude`. - `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, and picks the item the next chunk takes first (`next_chunk.py`), for `chunk_preflight` and `loop_claude`.
@@ -219,9 +232,9 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. - `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
- `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. - `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. - `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 parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `test_env.py` serves the tests. - `test_env.py` serves the tests.
- `text_files/` 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. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
## Test ## Test
+1 -1
View File
@@ -12,4 +12,4 @@ Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why. - Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a plan item plans away is named with that item, not raised. - A departure a plan item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the plan item that ends it. Weigh it hard: that it was decided is no reason. - A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the plan item that ends it. Weigh it hard: that it was decided is no reason.
- Report under one heading per yardstick. - Report under one `##` heading per yardstick.
+2 -2
View File
@@ -3,8 +3,8 @@
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means. It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
adf-codec has two pairs of calls, and each function here names the one it runs: adf-codec has two pairs of calls, and each function here names the one it runs:
- The lossless pair, `*_lossless`, for a document that already exists in Jira or Confluence and is edited and saved back. It keeps each block's localId and the empty paragraphs Jira uses for spacing, so a document read and saved unedited comes back identical. - The portable pair, with no suffix, which the loop's tools use. It drops each block's localId and the empty paragraphs Jira uses for spacing, so saving a document read by it changes the document; a tool that saves one unedited sends nothing instead (`docs/decisions.md` → `project config: the loop shows a Jira description and a Confluence page as adf-codec's portable markdown, …`).
- The portable pair, with no suffix, for new text written from scratch, and for markdown shown to a person. It drops the localId and the empty paragraphs, so saving a document that exists changes it. - The lossless pair, `*_lossless`, which keeps both, so a document read and saved unedited comes back identical. Its markdown wraps every block in `!adf:` marker lines, so no tool reads by it yet.
""" """
import contextlib import contextlib
import dataclasses import dataclasses
+1 -2
View File
@@ -5,8 +5,7 @@ import time
import typing import typing
from failure import Failure from failure import Failure
from chunk_preflight.gathered import Forge from forge.commands import Forge, Run
from deploy_release.forge import Run
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
POLL_SECONDS = 60 POLL_SECONDS = 60
+5 -5
View File
@@ -29,8 +29,9 @@ merge merges the pull request in its turn: the chunks of one project on this
turns, one at a time. Run it in the background. In its turn it: turns, one at a time. Run it in the background. In its turn it:
1. fetches origin and merges its default branch into the branch, as sync does; 1. fetches origin and merges its default branch into the branch, as sync does;
2. finishes each plan item a --finish names with `todo-item finish`, passing on 2. finishes each plan item a --finish names with `todo-item finish`, passing on
--changelog or --no-changelog, and commits what that changed in the plan and the --changelog or --no-changelog (a Jira plan takes no --changelog, as todo-item says),
changelog, so both change only at merge time, on top of every chunk merged before; and commits what that changed in the plan and the changelog, so both change only
at merge time, on top of every chunk merged before;
3. pushes, also where step 2 failed after step 1 brought changes in; 3. pushes, also where step 2 failed after step 1 brought changes in;
4. waits for the pull request's checks, and those origin's default branch requires, to 4. waits for the pull request's checks, and those origin's default branch requires, to
pass on the head; where no check reports within a minute, it takes the pull request pass on the head; where no check reports within a minute, it takes the pull request
@@ -85,10 +86,9 @@ import time
import typing import typing
from chunk_pr.approval import approval, approved, awaited, unanswered from chunk_pr.approval import approval, approved, awaited, unanswered
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner from forge.pulls import checks_passed, merged_pull, open_pull, required_checks
from failure import Failure from failure import Failure
from chunk_preflight.gathered import Forge from forge.commands import Forge, forge_of, gitea, Run, runner
from chunk_preflight.choices import forge_of
from project_config.main import located from project_config.main import located
from project_config.settings import ProjectConfig from project_config.settings import ProjectConfig
from plan_store.plans import says_no_item from plan_store.plans import says_no_item
+1 -1
View File
@@ -15,7 +15,7 @@ from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
from failure import Failure from failure import Failure
from test_env import isolated_env from test_env import isolated_env
from project_config.settings import ProjectConfig from project_config.settings import ProjectConfig
from deploy_release.forge import Run from forge.commands import Run
from chunk_pr.approval import THREADS from chunk_pr.approval import THREADS
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr" TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
+1 -5
View File
@@ -1,7 +1,7 @@
"""The pure choices the preflight's steps act on.""" """The pure choices the preflight's steps act on."""
import pathlib import pathlib
from chunk_preflight.gathered import Forge from forge.commands import Forge
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields. # The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
@@ -26,10 +26,6 @@ def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pus
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}." return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
def forge_of(origin_url: str) -> Forge:
return "gh" if "github.com" in origin_url else "tea"
def pulls_command(forge: Forge, branch: str) -> list[str]: def pulls_command(forge: Forge, branch: str) -> list[str]:
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's.""" """The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
if forge == "gh": if forge == "gh":
+2 -1
View File
@@ -4,7 +4,8 @@ from touch_predictions.beside import chunks_beside
from release_plan.next_chunk import cut_name, NextChunk, NoItem from release_plan.next_chunk import cut_name, NextChunk, NoItem
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
from failure import Failure from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran from forge.commands import Forge
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran
from text_files.markdown_text import listed, quoted from text_files.markdown_text import listed, quoted
from chunk_preflight.choices import PULLS_LIST from chunk_preflight.choices import PULLS_LIST
from plan.release import version from plan.release import version
+1 -4
View File
@@ -1,15 +1,12 @@
"""What the preflight gathers, which facts.render states.""" """What the preflight gathers, which facts.render states."""
import dataclasses import dataclasses
import pathlib import pathlib
import typing
from failure import Failure from failure import Failure
from forge.commands import Forge
from release_plan.release_standing import LastCut from release_plan.release_standing import LastCut
from release_plan.next_chunk import NextChunk, NoItem from release_plan.next_chunk import NextChunk, NoItem
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
Forge = typing.Literal["gh", "tea"]
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Ran: class Ran:
+3 -2
View File
@@ -78,13 +78,14 @@ import typing
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
from failure import Failure from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran, Worktree from forge.commands import Forge, forge_of
from chunk_preflight.choices import forge_of, pulls_command, worktree_add, worktree_on from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
from chunk_preflight.facts import JOINING_DETAILS, render from chunk_preflight.facts import JOINING_DETAILS, render
from project_config.main import located from project_config.main import located
from plan.named_paths import named_paths from plan.named_paths import named_paths
from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned
from release_plan.release_standing import project_plan from release_plan.release_standing import project_plan
from chunk_preflight.choices import pulls_command, worktree_add, worktree_on
BIN = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(__file__).resolve().parents[1]
# Each tool run in the item's worktree, {item} standing for the item's ID. # Each tool run in the item's worktree, {item} standing for the item's ID.
+1 -5
View File
@@ -13,7 +13,6 @@ from project_config.templates import BRANCH
from release_plan.next_chunk import CarriedOver, NoItem from release_plan.next_chunk import CarriedOver, NoItem
from chunk_preflight import choices from chunk_preflight import choices
from failure import Failure from failure import Failure
from chunk_preflight.choices import forge_of, worktree_add
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
from test_env import isolated_env from test_env import isolated_env
from release_plan.release_standing import LastCut, UNSEEN_RELEASES from release_plan.release_standing import LastCut, UNSEEN_RELEASES
@@ -21,6 +20,7 @@ from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from release_plan import next_chunk from release_plan import next_chunk
from chunk_preflight.facts import open_pulls, render from chunk_preflight.facts import open_pulls, render
from plan_store.todo_md import plan_of from plan_store.todo_md import plan_of
from chunk_preflight.choices import worktree_add
from project_config.test_project_config import write_config from project_config.test_project_config import write_config
BIN = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -653,10 +653,6 @@ class Gathering(unittest.TestCase):
self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"]) self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"])
self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"]) self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"])
def test_lists_pull_requests_with_gh_on_a_github_origin_and_with_tea_elsewhere(self):
self.assertEqual(forge_of("git@github.com:o/r.git"), "gh")
self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea")
def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self): def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self):
self.assertEqual(seconds(None), TIMEOUT) self.assertEqual(seconds(None), TIMEOUT)
self.assertEqual(seconds("2.5"), 2.5) self.assertEqual(seconds("2.5"), 2.5)
+8 -7
View File
@@ -1,4 +1,4 @@
"""One `claude -p --output-format json` run, as loop-claude's judge and the replays start it.""" """One `claude -p --output-format stream-json` run, as loop-claude's judge and the replays start it."""
import dataclasses import dataclasses
import subprocess import subprocess
import typing import typing
@@ -17,22 +17,23 @@ class Limited:
said: str said: str
# The json reply claude_reply parses; no persistence, so its runs stay out of the session picker; no permission prompt, as no one answers it. # No persistence, so these runs stay out of the session picker; Claude Code then writes no transcript, so stream-json, which prints one, lets a caller keep it. claude_reply reads the reply from the stream's last line. -p needs --verbose with stream-json. No permission prompt, as no one answers it.
HEADLESS = ["--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"] HEADLESS = ["--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"]
def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited: def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited:
"""claude's json reply to `claude -p <args>` and HEADLESS, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a reply that is no json.""" """claude's reply to `claude -p <args>` and HEADLESS, the result event that ends its stream, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a last line that isn't a json object."""
try: try:
proc = claude(["-p", *args, *HEADLESS], cwd, prompt) proc = claude(["-p", *args, *HEADLESS], cwd, prompt)
except OSError as failure: except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}") return Failure(f"could not start claude: {failure.strerror}")
reply = json_object(proc.stdout) last = proc.stdout.strip().rpartition("\n")[2]
# The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time. reply = json_object(last)
# The result event names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time; the stream's rate_limit_event holds it as a time, which nothing reads here yet.
if reply is not None and hit_limit(reply): if reply is not None and hit_limit(reply):
return Limited(None, limit_said(reply)) return Limited(None, limit_said(reply))
if proc.returncode != 0: if proc.returncode != 0:
return Failure(proc.stderr.strip() or f"{who} exited {proc.returncode}") return Failure(proc.stderr.strip() or f"{who} exited {proc.returncode}")
if reply is None: if reply is None:
return Failure(f"{who} printed no json reply; it printed: {proc.stdout.strip() or 'nothing'}") return Failure(f"{who} printed no json reply; its last line was: {last or 'nothing'}")
return reply return reply
+10 -3
View File
@@ -199,12 +199,19 @@ class ClaudeReply(unittest.TestCase):
return subprocess.CompletedProcess(args, 0, "{}", "") return subprocess.CompletedProcess(args, 0, "{}", "")
reply.claude_reply(run, ["--tools", ""], "/r", "p", "the judge") reply.claude_reply(run, ["--tools", ""], "/r", "p", "the judge")
self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"], "/r", "p")]) self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"], "/r", "p")])
def test_reads_the_reply_from_the_streams_last_line(self):
stream = "\n".join(json.dumps(event) for event in ({"type": "system", "subtype": "init"}, {"type": "assistant"}, {"type": "result", "result": "ok"}))
self.assertEqual(reply.claude_reply(self.claude((0, stream + "\n", "")), [], "/r", "p", "the judge"), {"type": "result", "result": "ok"})
def test_a_stream_that_ends_in_no_json_names_only_its_last_line(self):
self.assertEqual(reply.claude_reply(self.claude((0, '{"type": "system"}\nWarning: bye\n', "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: Warning: bye"))
def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self): def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self):
self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"}) self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"})
self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: Warning: hook said hi")) self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: Warning: hook said hi"))
self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: nothing")) self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: nothing"))
limit = json.dumps({"type": "result", "api_error_status": 429, "result": "You've hit your limit"}) limit = json.dumps({"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
self.assertEqual(reply.claude_reply(self.claude((1, limit, "")), [], "/r", "p", "the judge"), reply.Limited(None, "You've hit your limit")) self.assertEqual(reply.claude_reply(self.claude((1, limit, "")), [], "/r", "p", "the judge"), reply.Limited(None, "You've hit your limit"))
self.assertEqual(reply.claude_reply(self.claude((2, "", " ")), [], "/r", "p", "the judge"), Failure("the judge exited 2")) self.assertEqual(reply.claude_reply(self.claude((2, "", " ")), [], "/r", "p", "the judge"), Failure("the judge exited 2"))
+5 -2
View File
@@ -1,8 +1,11 @@
import io
import json import json
import pathlib
import typing import typing
from claude_code.entries import AssistantTurn, Entry, HumanTurn, LoopPrompt, parse_entry, Text, ToolCall from claude_code.entries import AssistantTurn, Entry, HumanTurn, LoopPrompt, parse_entry, Text, ToolCall
from failure import Failure from failure import Failure
from text_files.compressed import read_stored
JUDGED_TOOL_INPUT = 400 JUDGED_TOOL_INPUT = 400
@@ -14,9 +17,9 @@ class Typed(typing.NamedTuple):
def read_transcript(path: str) -> list[Entry] | Failure: def read_transcript(path: str) -> list[Entry] | Failure:
"""The entries of the transcript at path, or of its gzip where compress-archives gzipped it."""
try: try:
with open(path, "rb") as handle: return [entry for raw in io.BytesIO(read_stored(pathlib.Path(path))) if (entry := parse_entry(raw))]
return [entry for raw in handle if (entry := parse_entry(raw))]
except OSError as failure: except OSError as failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}") return Failure(f"could not read the transcript {path}: {failure.strerror}")
+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 compress_archives import main
sys.exit(main.main(sys.argv[1:]))
View File
+65
View File
@@ -0,0 +1,65 @@
"""Gzip each file of loop-claude's archive and the review folders that no tool changes any more, keeping all of them.
usage: compress-archives
It gzips each file that last changed over 30 days ago: in loop-claude's archive,
$LOOP_CLAUDE_TRANSCRIPTS (default ~/.claude/loop-claude-transcripts), each transcript, *.jsonl;
in the review folders, ~/.local/state/larv-review, every file. A file's last change is the later
of its mtime and ctime, so a copied or unpacked file counts from when it landed.
The gzip lands beside the file as <name>.gz, with the same times. The file is removed only once
its gzip reads back the same bytes. The archive's readers and review-replay read a gzipped file by
its plain name. README.md → Install has the crontab line that runs it daily.
It prints how many files it compressed. It exits 1, saying why, on any argument but --help or -h,
and at the first file it cannot compress, leaving that file and every one after it plain.
"""
import os
import pathlib
import stat
import sys
import time
import typing
from transcript_archive.location import archive_root
from text_files.compressed import compress, SUFFIX
from failure import Failure
from review_rules.review_folder import REPORTS
# Why 30 days: docs/decisions.md → `archives: gzip each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them`.
AGE_DAYS = 30
def main(argv: list[str], env: typing.Mapping[str, str] = os.environ, home: pathlib.Path | None = None, now: float | None = None) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv:
print(f"unknown arguments {' '.join(argv)}; usage: compress-archives", file=sys.stderr)
return 1
home = home or pathlib.Path.home()
cutoff = (time.time() if now is None else now) - AGE_DAYS * 24 * 60 * 60
count = 0
for path in [*old_files(archive_root(home, env), "*.jsonl", cutoff), *old_files(home / REPORTS, "*", cutoff)]:
if failed := compress(path):
print(failed.reason, file=sys.stderr)
return 1
count += 1
print(f"Compressed {count} files.")
return 0
def old_files(root: pathlib.Path, pattern: str, cutoff: float) -> list[pathlib.Path]:
"""Each plain file under root that pattern matches and that last changed before the cutoff, sorted; a link is left alone, since its target lies elsewhere."""
found = []
for path in root.rglob(pattern):
if path.name.endswith(SUFFIX) or path.is_symlink():
continue
try:
status = path.stat()
# Removed while the walk ran, such as a file of review-replay's copy of a review folder.
except FileNotFoundError:
continue
if stat.S_ISREG(status.st_mode) and max(status.st_mtime, status.st_ctime) < cutoff:
found.append(path)
return sorted(found)
@@ -0,0 +1,126 @@
import contextlib
import gzip
import io
from unittest import mock
import os
import pathlib
import sys
import tempfile
import time
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from compress_archives import main
DAY = 24 * 60 * 60
# A month ahead, so a file's ctime, which is when the test wrote it, lies over 30 days before NOW.
NOW = time.time() + 31 * DAY
OLD = 30 * DAY + 60
NEW = 30 * DAY - 60
class Main(unittest.TestCase):
"""A home whose archive and review folders each hold files that last changed a minute over 30 days ago, and one that changed a minute under."""
def setUp(self):
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.archive = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1"
self.reviews = self.home / ".local" / "state" / "larv-review" / "code" / "proj-item-1"
for folder in (self.archive / "session" / "s" / "subagents", self.reviews / "probe"):
folder.mkdir(parents=True)
self.write(self.archive / "a.jsonl", OLD)
self.write(self.archive / "a.outcomes.md", OLD)
self.write(self.archive / "session" / "s" / "subagents" / "agent-a.jsonl", OLD)
self.write(self.archive / "session" / "s" / "subagents" / "agent-a.meta.json", OLD)
self.write(self.archive / "b.jsonl", NEW)
self.write(self.reviews / "stability-round-1.md", OLD)
self.write(self.reviews / "probe" / "out.js", OLD)
self.write(self.reviews / "branch-1.diff", NEW)
def write(self, path, seconds_ago):
path.write_bytes(f"{path.name}\n".encode())
os.utime(path, (NOW - seconds_ago, NOW - seconds_ago))
def run_main(self, argv=(), env=None, now=NOW):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(list(argv), env or {}, self.home, now)
return code, out.getvalue(), err.getvalue()
def kept(self):
return sorted(str(path.relative_to(self.home)) for path in self.home.rglob("*") if path.is_file())
def test_gzips_the_archives_transcripts_and_every_review_file_last_written_over_30_days_ago(self):
code, out, err = self.run_main()
self.assertEqual((code, err), (0, ""))
self.assertEqual(self.kept(), [
".claude/loop-claude-transcripts/proj/c1/a.jsonl.gz",
".claude/loop-claude-transcripts/proj/c1/a.outcomes.md",
".claude/loop-claude-transcripts/proj/c1/b.jsonl",
".claude/loop-claude-transcripts/proj/c1/session/s/subagents/agent-a.jsonl.gz",
".claude/loop-claude-transcripts/proj/c1/session/s/subagents/agent-a.meta.json",
".local/state/larv-review/code/proj-item-1/branch-1.diff",
".local/state/larv-review/code/proj-item-1/probe/out.js.gz",
".local/state/larv-review/code/proj-item-1/stability-round-1.md.gz",
])
self.assertEqual(gzip.decompress((self.archive / "a.jsonl.gz").read_bytes()), b"a.jsonl\n")
self.assertEqual(out, "Compressed 4 files.\n")
self.assertEqual(self.run_main(), (0, "Compressed 0 files.\n", ""))
def test_keeps_a_file_last_written_exactly_30_days_ago_plain(self):
self.write(self.archive / "b.jsonl", 30 * DAY)
self.run_main()
self.assertTrue((self.archive / "b.jsonl").is_file())
def test_keeps_a_file_copied_today_with_its_old_times_plain(self):
now = time.time()
os.utime(self.archive / "a.jsonl", (now - 31 * DAY, now - 31 * DAY))
self.assertEqual(self.run_main(now=now), (0, "Compressed 0 files.\n", ""))
self.assertTrue((self.archive / "a.jsonl").is_file())
def test_measures_the_30_days_from_the_clock_by_default(self):
with mock.patch.object(main.time, "time", return_value=NOW):
self.assertEqual(self.run_main(now=None), (0, "Compressed 4 files.\n", ""))
def test_walks_on_past_a_gzip_a_link_and_a_file_removed_while_it_walks(self):
gone = mock.Mock(**{"is_symlink.return_value": False, "stat.side_effect": FileNotFoundError})
# Mock(name=...) names the mock itself, so the path's name is set after.
gone.name = "gone.jsonl"
packed = self.archive / "c.jsonl.gz"
packed.write_bytes(b"")
link = self.archive / "d.jsonl"
link.symlink_to(self.archive / "a.jsonl")
kept = self.archive / "a.jsonl"
root = mock.Mock(**{"rglob.return_value": [packed, link, gone, kept]})
self.assertEqual(main.old_files(root, "*.jsonl", NOW), [kept])
def test_reads_the_archive_where_loop_claude_transcripts_puts_it(self):
moved = self.home / "elsewhere"
(self.home / ".claude" / "loop-claude-transcripts").rename(moved)
code, _, err = self.run_main(env={"LOOP_CLAUDE_TRANSCRIPTS": str(moved)})
self.assertEqual((code, err), (0, ""))
self.assertTrue((moved / "proj" / "c1" / "a.jsonl.gz").is_file())
def test_runs_where_neither_folder_exists_yet(self):
with tempfile.TemporaryDirectory() as empty:
self.home = pathlib.Path(empty)
self.assertEqual(self.run_main(), (0, "Compressed 0 files.\n", ""))
def test_stops_at_the_first_failure_keeping_that_file_and_every_later_one(self):
with mock.patch.object(main, "compress", return_value=Failure("could not compress x: full")):
code, out, err = self.run_main()
self.assertEqual((code, out, err), (1, "", "could not compress x: full\n"))
self.assertTrue((self.archive / "a.jsonl").is_file())
def test_prints_its_help_and_refuses_other_arguments(self):
for flag in ("--help", "-h"):
code, out, _ = self.run_main([flag])
self.assertEqual(code, 0)
self.assertTrue(out.startswith("Gzip each file"), out)
self.assertEqual(self.run_main(["x", "y"]), (1, "", "unknown arguments x y; usage: compress-archives\n"))
if __name__ == "__main__":
unittest.main()
+10 -9
View File
@@ -14,9 +14,10 @@ from deploy_release.deploy import deploy
from failure import Failure from failure import Failure
from plan_store.todo_md import FilePlan from plan_store.todo_md import FilePlan
from record_store.stores import FileStore from record_store.stores import FileStore
from deploy_release import forge from forge.commands import forge_of, runner
from chunk_preflight.choices import forge_of
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
from forge import pulls
from deploy_release import release_pull
from project_config import templates from project_config import templates
@@ -153,7 +154,7 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
url = git("config", "--get", "remote.origin.url", cwd=clone) url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure): if isinstance(url, Failure):
return url return url
on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/") on, run, branch, base = forge_of(url), runner(clone), f"release-{named}", ref.removeprefix("origin/")
head = branch_head(branch, clone) head = branch_head(branch, clone)
if isinstance(head, Failure): if isinstance(head, Failure):
return head return head
@@ -168,23 +169,23 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
if isinstance(head, Failure): if isinstance(head, Failure):
return head return head
number = forge.open_pull(on, branch, head, run) number = pulls.open_pull(on, branch, head, run)
if number is None: if number is None:
if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure): if isinstance(created := release_pull.create_pull(on, branch, base, title, run), Failure):
return created return created
number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}") number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, str): if isinstance(number, str):
said(f"opened pull request {number}") said(f"opened pull request {number}")
if isinstance(number, Failure): if isinstance(number, Failure):
return number return number
required = forge.required_checks(on, base, run) required = pulls.required_checks(on, base, run)
if isinstance(required, Failure): if isinstance(required, Failure):
return required return required
said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else "")) said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
if isinstance(passed := forge.checks_passed(on, number, head, required, run), Failure): if isinstance(passed := pulls.checks_passed(on, number, head, required, run), Failure):
return passed return passed
said(f"the checks of pull request {number} passed") said(f"the checks of pull request {number} passed")
if isinstance(merged := forge.merge(on, number, head, run), Failure): if isinstance(merged := release_pull.merge(on, number, head, run), Failure):
return merged return merged
said(f"merged pull request {number}") said(f"merged pull request {number}")
return None return None
+23
View File
@@ -0,0 +1,23 @@
"""Opening and merging a cut's pull request, with gh where origin is on GitHub and with tea elsewhere.
merge is pinned to head, the commit origin's release branch points at: the forge merges the pull request only while its head is still that commit, so a push to the branch after its checks passed is never merged.
"""
from failure import Failure
from forge.commands import Forge, gitea, Run
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
return created if isinstance(created, Failure) else None
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
if forge == "gh":
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
else:
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
return merged if isinstance(merged, Failure) else None
+4 -55
View File
@@ -1,16 +1,13 @@
import itertools
import json import json
import os import os
import pathlib import pathlib
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
import typing
import unittest import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from deploy_release.forge import checks_passed, POLL_SECONDS, required_checks, WAIT_SECONDS
from failure import Failure from failure import Failure
from test_env import isolated_env from test_env import isolated_env
@@ -229,6 +226,10 @@ save()
""".replace("PYTHON", sys.executable) """.replace("PYTHON", sys.executable)
# The protection of main that requires CI's check.
REQUIRED = '{"name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}'
class Cut(unittest.TestCase): class Cut(unittest.TestCase):
"""A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0.""" """A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0."""
@@ -486,58 +487,6 @@ class Cut(unittest.TestCase):
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0") self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
def tea(statuses: typing.Iterable[str], branch: str = '{"name": "main"}') -> typing.Callable[[list[str]], str]:
"""A tea answering each read of the head's status with the next of statuses, and of branch main with branch."""
answers = iter(statuses)
return lambda command: branch if command[-1] == "repos/{owner}/{repo}/branches/main" else next(answers)
REQUIRED = '{"name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}'
class RequiredChecks(unittest.TestCase):
def test_reads_on_tea_the_checks_the_protection_of_the_base_requires(self):
self.assertEqual(required_checks("tea", "main", tea([], REQUIRED)), {"CI / tests (pull_request)"})
def test_reads_none_on_tea_where_the_protection_turns_status_checks_off(self):
self.assertEqual(required_checks("tea", "main", tea([], '{"name": "main", "enable_status_check": false, "status_check_contexts": ["CI / tests (pull_request)"]}')), set())
def test_fails_on_tea_where_the_branch_reads_in_another_shape(self):
self.assertIsInstance(required_checks("tea", "main", tea([], "[]")), Failure)
def test_reads_none_on_github_whose_watch_covers_them(self):
self.assertEqual(required_checks("gh", "main", self.fail), set())
class ChecksPassed(unittest.TestCase):
def test_waits_on_tea_while_a_check_is_pending(self):
slept = []
self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append))
self.assertEqual(slept, [POLL_SECONDS])
def test_takes_a_commit_with_no_status_on_tea_as_passed_where_the_base_requires_none(self):
self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 0}']), self.fail))
def test_waits_on_tea_for_a_check_the_base_requires_until_it_reports_and_passes(self):
slept = []
statuses = ['{"state": "pending", "total_count": 0, "statuses": []}', '{"state": "success", "total_count": 1, "statuses": [{"context": "lint", "status": "success"}]}', '{"state": "success", "total_count": 2, "statuses": [{"context": "lint", "status": "success"}, {"context": "CI / tests (pull_request)", "status": "success"}]}']
self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / tests (pull_request)"}, tea(statuses), slept.append))
self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS])
def test_takes_on_tea_a_required_glob_as_met_by_a_check_it_matches(self):
passed = '{"state": "success", "total_count": 1, "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]}'
self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / *"}, tea([passed]), self.fail))
def test_gives_up_on_tea_after_the_wait_naming_a_required_check_that_never_reported(self):
slept = []
waited = checks_passed("tea", "1", "abc", {"CI / tests (pull_request)"}, tea(itertools.repeat('{"state": "pending", "total_count": 0, "statuses": []}')), slept.append)
self.assertIsInstance(waited, Failure)
self.assertIn("CI / tests (pull_request)", waited.reason)
self.assertEqual(sum(slept), WAIT_SECONDS)
def test_fails_on_tea_where_a_check_failed(self):
self.assertIsInstance(checks_passed("tea", "1", "abc", set(), tea(['{"state": "failure", "total_count": 1}']), self.fail), Failure)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
View File
View File
+88
View File
@@ -0,0 +1,88 @@
"""What every backend of an epic's plan must hold, as tests. A backend's test case inherits EpicStoreContract and unittest.TestCase, and builds an epic with no issues in new_store. Its assign and close change an issue as a person would in the tracker."""
import re
import typing
from do_epic.backend.protocol import EpicIssue, EpicStore
from failure import Failure
class EpicStoreContract:
assertEqual: typing.Callable[..., None]
assertIsInstance: typing.Callable[..., None]
subTest: typing.Callable[..., typing.ContextManager[None]]
def new_store(self) -> EpicStore:
raise NotImplementedError
def assign(self, store: EpicStore, key: str, name: str) -> None:
"""Assigns the issue named key to the person whose display name is name."""
raise NotImplementedError
def close(self, store: EpicStore, key: str, status: str) -> None:
"""Moves the issue named key to the done status named status."""
raise NotImplementedError
def filed(self, store: EpicStore, parent: str, summary: str, detail: str = "", labels: tuple[str, ...] = ()) -> str:
key = store.file(parent, summary, detail, labels)
assert isinstance(key, str), key
return key
def issues(self, store: EpicStore) -> list[EpicIssue]:
read = store.read()
assert isinstance(read, list), read
return read
def test_an_epic_with_no_issues_reads_empty(self) -> None:
self.assertEqual(self.new_store().read(), [])
def test_reads_back_a_child_issue_it_filed(self) -> None:
store = self.new_store()
key = self.filed(store, store.epic_key, "Count the runs.", "Why it counts.\n\nA second paragraph.", ("security", "api"))
self.assertEqual(self.issues(store), [EpicIssue(key, "Count the runs.", "Why it counts.\n\nA second paragraph.", ("api", "security"), None, "To Do", False, store.epic_key)])
def test_reads_back_a_sub_task_it_filed_after_its_parent(self) -> None:
store = self.new_store()
first = self.filed(store, store.epic_key, "Count the runs.")
second = self.filed(store, store.epic_key, "Ship the later thing.")
task = self.filed(store, first, "Count them in the api.", labels=("api",))
read = self.issues(store)
self.assertEqual([(issue.key, issue.parent) for issue in read], [(first, store.epic_key), (task, first), (second, store.epic_key)])
self.assertEqual((read[1].summary, read[1].labels, read[1].detail), ("Count them in the api.", ("api",), ""))
def test_files_each_issue_under_its_own_key_in_the_epics_project(self) -> None:
store = self.new_store()
child = self.filed(store, store.epic_key, "Count the runs.")
keys = [child, self.filed(store, store.epic_key, "Count the runs."), self.filed(store, child, "Count them in the api.")]
self.assertEqual(len(set(keys)), 3)
project = store.epic_key.rpartition("-")[0]
self.assertEqual([re.fullmatch(f"{project}-[1-9][0-9]*", key) is not None for key in keys], [True] * 3)
def test_reads_the_assignee_and_a_done_status(self) -> None:
store = self.new_store()
first = self.filed(store, store.epic_key, "Count the runs.")
second = self.filed(store, store.epic_key, "Ship the later thing.")
self.assign(store, first, "Ada Lovelace")
self.close(store, second, "Done")
read = {issue.key: issue for issue in self.issues(store)}
self.assertEqual((read[first].assignee, read[first].status, read[first].done), ("Ada Lovelace", "To Do", False))
self.assertEqual((read[second].assignee, read[second].status, read[second].done), (None, "Done", True))
def test_refuses_to_file_under_a_sub_task(self) -> None:
store = self.new_store()
child = self.filed(store, store.epic_key, "Count the runs.")
task = self.filed(store, child, "Count them in the api.")
self.assertEqual(store.file(task, "Count more.", "", ()), Failure(f"{task} is neither the epic {store.epic_key} nor one of its child issues, so nothing can be filed under it"))
self.assertEqual(len(self.issues(store)), 2)
def test_refuses_to_file_under_an_issue_outside_the_epic(self) -> None:
store = self.new_store()
for parent in ("ZZZ-1", "not a key"):
with self.subTest(parent=parent):
self.assertIsInstance(store.file(parent, "Count more.", "", ()), Failure)
self.assertEqual(self.issues(store), [])
def test_refuses_a_label_with_white_space_and_a_summary_of_two_lines(self) -> None:
store = self.new_store()
self.assertEqual(store.file(store.epic_key, "Count the runs.", "", ("two words",)), Failure("the label 'two words' is empty or holds white space"))
self.assertEqual(store.file(store.epic_key, "Count\nthe runs.", "", ()), Failure("the summary must be one line of text"))
self.assertEqual(self.issues(store), [])
+33
View File
@@ -0,0 +1,33 @@
"""An epic held in memory, for do-epic's tests, held to contract.py like every backend."""
import dataclasses
from do_epic.backend.protocol import EpicIssue, no_parent, unfit
from failure import Failure
@dataclasses.dataclass
class MemoryEpic:
"""An epic whose issues rank in the order filed. Where fails is set, every read and filing fails with it as the reason."""
epic_key: str
issues: list[EpicIssue] = dataclasses.field(default_factory=list)
fails: str | None = None
def read(self) -> list[EpicIssue] | Failure:
if self.fails:
return Failure(self.fails)
return [issue for child in self.issues if child.parent == self.epic_key for issue in (child, *(task for task in self.issues if task.parent == child.key))]
def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure:
if self.fails:
return Failure(self.fails)
if refused := unfit(summary, labels):
return refused
if parent != self.epic_key and parent not in {issue.key for issue in self.issues if issue.parent == self.epic_key}:
return no_parent(self.epic_key, parent)
key = f"{self.epic_key.rpartition('-')[0]}-{len(self.issues) + 100}"
self.issues.append(EpicIssue(key, summary, detail.strip(), tuple(sorted(labels)), None, "To Do", False, parent))
return key
def change(self, key: str, **fields: object) -> None:
"""Changes the issue named key as a person would in the tracker, such as assignee="Ada Lovelace"."""
self.issues = [dataclasses.replace(issue, **fields) if issue.key == key else issue for issue in self.issues] # type: ignore[arg-type]
+148
View File
@@ -0,0 +1,148 @@
"""An epic's plan kept as a Jira Cloud epic's child issues and their sub-tasks, read and filed over Jira's REST API version 3."""
import dataclasses
import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from project_config.settings import Epic
from do_epic.backend.protocol import EpicIssue, no_parent, unfit
from failure import Failure
from plan_store.jira_epic import ISSUE_KEY, ISSUE_TYPE, project_of, searched
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent"]
# How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes.
PARENTS_PER_SEARCH = 50
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {parent} before filing it again"
@dataclasses.dataclass(frozen=True)
class Found:
"""An issue as Jira answered it, its description still in Jira's document format."""
issue: EpicIssue
description: dict[str, typing.Any] | None
@dataclasses.dataclass(frozen=True)
class JiraEpic:
"""The issues of a Jira epic, read and filed with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
@property
def epic_key(self) -> str:
return self.epic.key
def read(self) -> list[EpicIssue] | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
found = self.found(authorization)
if isinstance(found, Failure):
return found
# A container run converts every description at once. It comes after every other check, since a read that fails doesn't need it.
described = [each for each in found if each.description is not None]
texts = self.to_markdown([each.description for each in described if each.description is not None])
if isinstance(texts, Refused):
return Failure(f"{described[texts.index].issue.key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert the descriptions of {self.epic_key}'s issues to markdown: {texts.reason}")
details = {each.issue.key: text.strip() for each, text in zip(described, texts)}
return [dataclasses.replace(each.issue, detail=details.get(each.issue.key, "")) for each in found]
def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
if refused := unfit(summary, labels) or self.not_a_parent(parent, authorization):
return refused
fields: dict[str, typing.Any] = {"project": {"key": project_of(parent)}, "parent": {"key": parent}, "summary": summary, "labels": list(labels)}
kind = {"name": ISSUE_TYPE} if parent == self.epic_key else self.sub_task_type(project_of(parent), authorization)
if isinstance(kind, Failure):
return kind
if detail.strip():
description = self.to_adf(detail)
if isinstance(description, Failure):
return Failure(f"cannot convert the detail to a Jira description: {description.reason}")
fields["description"] = description
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": fields | {"issuetype": kind}})
if isinstance(created, Failure):
return Failure(f"cannot file the issue under {parent}: {created.reason}; {PERHAPS_FILED.format(parent=parent)}")
key = created.get("key") if isinstance(created, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure(f"Jira answered the new issue without an issue key; {PERHAPS_FILED.format(parent=parent)}")
return key
def not_a_parent(self, parent: str, authorization: str) -> Failure | None:
"""Why nothing can be filed under parent; None where it is the epic or one of its child issues."""
if parent == self.epic_key:
return None
if not ISSUE_KEY.fullmatch(parent):
return no_parent(self.epic_key, parent)
# A search may not show an issue filed a moment ago, so the parent is asked for by its key.
answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{parent}?fields=parent", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {parent} to file under it: {answered.reason}")
fields = answered.get("fields") if isinstance(answered, dict) else None
above = fields.get("parent") if isinstance(fields, dict) else None
return None if isinstance(above, dict) and above.get("key") == self.epic_key else no_parent(self.epic_key, parent)
def found(self, authorization: str) -> list[Found] | Failure:
"""Each child issue, each followed by its sub-tasks."""
# The search answers no issues for an epic the account cannot see; asking for the epic itself tells that from an epic without children.
seen = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=summary", authorization, None)
if isinstance(seen, Failure):
return Failure(f"cannot read the epic {self.epic_key}: {seen.reason}")
children = self.searched(f"{self.epic_key}'s child issues", (self.epic_key,), authorization)
if isinstance(children, Failure):
return children
keys = [each.issue.key for each in children]
tasks: list[Found] = []
for start in range(0, len(keys), PARENTS_PER_SEARCH):
batch = self.searched(f"the sub-tasks of {self.epic_key}'s child issues", tuple(keys[start:start + PARENTS_PER_SEARCH]), authorization)
if isinstance(batch, Failure):
return batch
tasks += batch
return [each for child in children for each in (child, *(task for task in tasks if task.issue.parent == child.issue.key))]
def searched(self, what: str, parents: tuple[str, ...], authorization: str) -> list[Found] | Failure:
"""The issues whose parent is one of parents, in rank order."""
named = ", ".join(f'"{key}"' for key in parents)
answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS}, authorization, self.http)
if isinstance(answered, Failure):
return answered
found = [found_of(raw) for raw in answered]
return next((each for each in found if isinstance(each, Failure)), None) or [each for each in found if isinstance(each, Found)]
def sub_task_type(self, project: str, authorization: str) -> dict[str, str] | Failure:
"""The project's sub-task issue type, by id, since sites name it differently, such as Subtask or Sub-task."""
answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/createmeta/{project}/issuetypes", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {project}'s issue types: {answered.reason}")
types = answered.get("issueTypes") if isinstance(answered, dict) else None
if not isinstance(types, list):
return Failure(f"Jira answered {project}'s issue types in a shape its REST API version 3 doesn't document")
found = next((kind["id"] for kind in types if isinstance(kind, dict) and kind.get("subtask") is True and isinstance(kind.get("id"), str)), None)
return Failure(f"{project} has no sub-task issue type; turn sub-tasks on in Jira") if found is None else {"id": found}
def found_of(raw: object) -> Found | Failure:
"""The issue in one entry of a search's answer, or which issue is not in the shape Jira documents."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
# The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here.
try:
fields = raw["fields"]
summary, labels, assignee, status, parent, description = fields["summary"], fields["labels"], fields["assignee"], fields["status"], fields["parent"]["key"], fields["description"]
name = assignee["displayName"] if assignee is not None else None
state, done = status["name"], status["statusCategory"]["key"] == "done"
except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
texts = (summary, *labels, state, parent) if isinstance(labels, list) else ()
if not texts or not all(isinstance(text, str) for text in texts) or not isinstance(name, str | None) or not ISSUE_KEY.fullmatch(parent) or not isinstance(description, dict | None):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its summary, labels, assignee, status, parent or description holds another kind of value")
return Found(EpicIssue(key, summary.strip(), "", tuple(sorted(labels)), name, state, done, parent), description)
+58
View File
@@ -0,0 +1,58 @@
"""What every backend of an epic's plan reads and files: an EpicIssue, and the EpicStore protocol they all meet. do-epic reads an epic only through EpicStore, so another tracker can stand behind it; contract.py holds the tests every backend passes.
EpicStore is not plan_store's PlanStore. A PlanStore item names a release, but an epic item has none (`docs/decisions.md` → `do-epic: drives one Jira epic …`), and it may be a sub-task."""
import dataclasses
import re
import typing
from failure import Failure
# What a tracker accepts as a label: Jira refuses a label holding white space.
LABEL = re.compile(r"\S+")
@dataclasses.dataclass(frozen=True)
class EpicIssue:
"""One of an epic's child issues, or a sub-task of one, as a read found it."""
key: str
summary: str
# The description, as markdown; empty where the issue has none.
detail: str
# Sorted by name.
labels: tuple[str, ...]
# The assignee's display name; None where nobody is assigned.
assignee: str | None
# The status's name, such as "In Progress".
status: str
# Whether the status is one the tracker counts as done.
done: bool
# The epic's key for a child issue, the child's key for a sub-task.
parent: str
class EpicStore(typing.Protocol):
"""The issues of one epic. A write that fails doesn't file anything, except where its Failure says the tracker may have taken it all the same."""
@property
def epic_key(self) -> str:
"""The parent of each child issue."""
def read(self) -> list[EpicIssue] | Failure:
"""Each child issue, open or done, in the tracker's rank order, each followed by its sub-tasks in theirs."""
def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure:
"""Files an open issue under parent and answers its key: a child issue where parent is the epic, a sub-task where parent is one of its child issues. detail is markdown, and may be empty."""
def unfit(summary: str, labels: tuple[str, ...]) -> Failure | None:
"""Why no tracker can file an issue with this summary and these labels; None where one can."""
if not summary.strip() or "\n" in summary:
return Failure("the summary must be one line of text")
if bad := next((label for label in labels if not LABEL.fullmatch(label)), None):
return Failure(f"the label {bad!r} is empty or holds white space")
return None
def no_parent(epic_key: str, parent: str) -> Failure:
"""What every backend says when asked to file under parent, which is neither the epic nor one of its child issues."""
return Failure(f"{parent} is neither the epic {epic_key} nor one of its child issues, so nothing can be filed under it")
+30
View File
@@ -0,0 +1,30 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from do_epic.backend.fake import MemoryEpic
class MemoryEpicContract(EpicStoreContract, unittest.TestCase):
def new_store(self) -> MemoryEpic:
return MemoryEpic("ABC-12")
def assign(self, store: MemoryEpic, key: str, name: str) -> None: # type: ignore[override]
store.change(key, assignee=name)
def close(self, store: MemoryEpic, key: str, status: str) -> None: # type: ignore[override]
store.change(key, status=status, done=True)
class Failing(unittest.TestCase):
def test_every_read_and_filing_fails_with_the_reason_given(self) -> None:
store = MemoryEpic("ABC-12", fails="Jira is down")
self.assertEqual((store.read(), store.file("ABC-12", "Count the runs.", "", ())), (Failure("Jira is down"), Failure("Jira is down")))
if __name__ == "__main__":
unittest.main()
+190
View File
@@ -0,0 +1,190 @@
import base64
import dataclasses
import pathlib
import re
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from project_config.settings import Epic
from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from plan_store import jira_epic
from do_epic.backend.jira import JiraEpic
from adf_codec.convert import Refused
SITE = "https://acme.atlassian.net"
EPIC = Epic(SITE, "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
EPIC_URL = f"{SITE}/rest/api/3/issue/ABC-12?fields=summary"
ISSUE_TYPES = f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes"
SEARCH = f"{SITE}/rest/api/3/search/jql"
ISSUES = f"{SITE}/rest/api/3/issue"
TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}}
TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]}
def to_adf(markdown: str) -> dict[str, object]:
"""Stands in for the adf-codec shim: one paragraph holding the markdown."""
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": markdown}]}]}
def to_markdown(documents: list[dict[str, object]]) -> list[str]:
return [document["content"][0]["content"][0]["text"] + "\n" for document in documents] # type: ignore[index]
@dataclasses.dataclass
class FakeJira:
"""Jira Cloud's REST API as JiraEpic calls it. It holds issues as Jira answers them, in rank order. A search answers two issues a page, with only the fields it asks for. A call whose method and URL are in answers gets the answer held there instead."""
issues: list[dict[str, object]] = dataclasses.field(default_factory=list)
answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict)
calls: list[tuple[str, str]] = dataclasses.field(default_factory=list)
def __call__(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url))
if authorization != AUTHORIZATION:
return Failure("Jira answered 401")
if (method, url) in self.answers:
return self.answers[method, url]
if method == "GET" and url == EPIC_URL:
return {"key": "ABC-12"}
if method == "GET" and url == ISSUE_TYPES:
return TYPES
if method == "POST" and url == SEARCH:
return self.page(body)
if method == "GET" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}?fields=parent"), None)):
return {"key": held["key"], "fields": {"parent": held["fields"]["parent"]}} # type: ignore[index]
if method == "POST" and url == ISSUES:
return self.created(body)
return Failure(f"Jira answered 404 for {method} {url}")
def page(self, body: object) -> object:
assert isinstance(body, dict)
matched = re.fullmatch(r'parent in \(("[A-Z]+-[0-9]+"(?:, "[A-Z]+-[0-9]+")*)\) ORDER BY Rank ASC', body["jql"])
if matched is None:
return Failure("Jira answered 400: the JQL is not valid")
parents = re.findall(r'"([A-Z]+-[0-9]+)"', matched[1])
found = [{"key": issue["key"], "fields": {name: value for name, value in issue["fields"].items() if name in body.get("fields", [])}} for issue in self.issues if issue["fields"]["parent"]["key"] in parents] # type: ignore[index, attr-defined]
start = int(body.get("nextPageToken", 0))
return {"issues": found[start:start + 2]} | ({"nextPageToken": str(start + 2)} if start + 2 < len(found) else {})
def created(self, body: object) -> object:
assert isinstance(body, dict)
fields = body["fields"]
parent = fields["parent"]["key"]
kind = {"name": "Task"} if parent == "ABC-12" else {"id": "10003"} if any(issue["key"] == parent for issue in self.issues) else None
if fields["project"] != {"key": "ABC"} or kind is None or fields["issuetype"] != kind:
return Failure("Jira answered 400: the project, parent or issue type is not valid")
key = f"ABC-{len(self.issues) + 100}"
self.issues.append({"key": key, "fields": {"summary": fields["summary"], "description": fields.get("description"), "labels": fields["labels"], "assignee": None, "status": TO_DO, "parent": {"key": parent}}})
return {"id": "1", "key": key}
def change(self, key: str, **fields: object) -> None:
next(issue for issue in self.issues if issue["key"] == key)["fields"].update(fields) # type: ignore[union-attr]
class Case(unittest.TestCase):
def setUp(self) -> None:
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.env_file = pathlib.Path(folder.name) / "jira.env"
self.env_file.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env_file.chmod(0o600)
self.jira = FakeJira()
def new_store(self) -> JiraEpic:
return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf)
class JiraEpicContract(Case, EpicStoreContract):
def assign(self, store: JiraEpic, key: str, name: str) -> None: # type: ignore[override]
self.jira.change(key, assignee={"accountId": "5b10a2844c20165700ede21g", "displayName": name})
def close(self, store: JiraEpic, key: str, status: str) -> None: # type: ignore[override]
self.jira.change(key, status={"name": status, "statusCategory": {"key": "done"}})
class Jira(Case):
def test_reads_the_sub_tasks_of_more_children_than_one_search_names(self) -> None:
store = self.new_store()
children = [store.file("ABC-12", f"Item {n}.", "", ()) for n in range(60)]
tasks = [store.file(child, "A task.", "", ()) for child in children]
read = store.read()
assert isinstance(read, list), read
self.assertEqual([issue.key for issue in read], [key for pair in zip(children, tasks) for key in pair])
def test_files_a_child_without_asking_for_issue_types(self) -> None:
self.new_store().file("ABC-12", "Count the runs.", "", ())
self.assertNotIn(("GET", ISSUE_TYPES), self.jira.calls)
def test_a_filing_jira_fails_or_answers_without_a_key_says_the_issue_may_exist(self) -> None:
for answer, reason in ((Failure("Jira answered 503"), "cannot file the issue under ABC-12: Jira answered 503"), ({"id": "1"}, "Jira answered the new issue without an issue key"), (["ABC-100"], "Jira answered the new issue without an issue key")):
with self.subTest(answer=answer):
self.jira.answers[("POST", ISSUES)] = answer
self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure(f"{reason}; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again"))
def test_a_detail_the_codec_refuses_leaves_the_epic_as_it_was(self) -> None:
store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"))
self.assertEqual(store.file("ABC-12", "Count the runs.", "Why.", ()), Failure("cannot convert the detail to a Jira description: adf-codec refused it"))
self.assertEqual(self.jira.issues, [])
def test_files_no_sub_task_where_the_project_has_no_sub_task_type_or_its_types_cannot_be_read(self) -> None:
store = self.new_store()
child = store.file("ABC-12", "Count the runs.", "", ())
for answer, reason in ((Failure("Jira answered 403"), "cannot read ABC's issue types: Jira answered 403"), ({"issueTypes": [{"id": "10001", "subtask": False}]}, "ABC has no sub-task issue type; turn sub-tasks on in Jira"), ({}, "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document"), ([], "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document")):
with self.subTest(answer=answer):
self.jira.answers[("GET", ISSUE_TYPES)] = answer
self.assertEqual(store.file(str(child), "A task.", "", ()), Failure(reason))
self.assertEqual(len(self.jira.issues), 1)
def test_an_issue_in_another_shape_fails_the_read(self) -> None:
valid = {"summary": "Count the runs.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": "ABC-12"}}
shape = "ABC-34 is not in the shape Jira Cloud's REST API version 3 documents"
for raw, reason in (
("ABC-34", "the search answered an issue without an issue key"),
({"fields": valid}, "the search answered an issue without an issue key"),
({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"),
({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}}}, shape + ": KeyError('labels')"),
*((({"key": "ABC-34", "fields": valid | changed}, shape + ": its summary, labels, assignee, status, parent or description holds another kind of value") for changed in (
{"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"},
))),
):
with self.subTest(raw=raw):
self.jira.answers[("POST", SEARCH)] = {"issues": [raw]}
self.assertEqual(self.new_store().read(), Failure(reason))
def test_a_description_the_codec_cannot_convert_fails_the_read(self) -> None:
self.new_store().file("ABC-12", "Count the runs.", "Why.", ())
for converted, reason in ((Refused(0, Failure("a table cell holds a list")), "ABC-100's description: a table cell holds a list"), (Failure("docker is not running"), "cannot convert the descriptions of ABC-12's issues to markdown: docker is not running")):
with self.subTest(converted=converted):
self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, lambda documents: converted, to_adf).read(), Failure(reason))
def test_a_search_that_does_not_end_names_the_issues_it_sought(self) -> None:
store = self.new_store()
children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)]
for _ in range(3):
store.file(str(children[0]), "A task.", "", ())
with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 1):
self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages"))
store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages"))
def test_refuses_to_file_under_another_epics_child_or_an_issue_it_cannot_read(self) -> None:
self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}}})
store = self.new_store()
self.assertEqual(store.file("ABC-5", "Count more.", "", ()), Failure("ABC-5 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it"))
self.assertEqual(store.file("ABC-77", "Count more.", "", ()), Failure(f"cannot read ABC-77 to file under it: Jira answered 404 for GET {ISSUES}/ABC-77?fields=parent"))
self.jira.answers[("GET", f"{ISSUES}/ABC-78?fields=parent")] = ["ABC-12"]
self.assertEqual(store.file("ABC-78", "Count more.", "", ()), Failure("ABC-78 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it"))
self.assertEqual([call for call in self.jira.calls if call[0] == "POST" and call[1] == ISSUES], [])
def test_an_epic_the_account_cannot_see_fails_the_read(self) -> None:
store = JiraEpic(Epic(SITE, "ABC-99"), self.env_file, self.jira, to_markdown, to_adf)
self.assertEqual(store.read(), Failure(f"cannot read the epic ABC-99: Jira answered 404 for GET {SITE}/rest/api/3/issue/ABC-99?fields=summary"))
if __name__ == "__main__":
unittest.main()
+82
View File
@@ -0,0 +1,82 @@
"""do-epic's machine-wide settings: `~/.claude-projects/do-epic/config.toml`, and `repo-rule.md` beside it.
One pair per machine, the same for every epic (docs/decisions.md → `do-epic: drives one Jira epic …`). The config is TOML:
jira-url = "https://acme.atlassian.net"
env-file = "~/.secrets/acme-jira.env"
repoless-model = "claude-opus-5-5"
clone-folder = "~/code"
language = "Swedish"
- `jira-url` is the Jira site's address: https, a host, and no path.
- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.claude-projects` and outside the clone folder, which hold git checkouts. `~/.claude-projects/<key>.env` is fine.
- `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`.
- `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out.
- `language` is the default language of Jira text, by its English name. English where left out.
- `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank."""
import dataclasses
import pathlib
import re
from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE
from failure import Failure
from model_routing.ladder_file import read_ladder, SHIPPED
REPO_RULE = "repo-rule.md"
# Three readers, seated as the human who writes this config, picked these spellings from four candidates each, 3-0: `jira-url` over `site`, `clone-folder` over `repos-folder` (which reads as the folder of repos that already exist) and `repoless-model` over `no-repo-model`. `env-file` and `language` keep the names a project's config gives them.
JIRA_URL = "jira-url"
REPOLESS_MODEL = "repoless-model"
CLONE_FOLDER = "clone-folder"
SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL)
OPTIONAL = (CLONE_FOLDER, LANGUAGE)
LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {' and '.join(OPTIONAL)}."
@dataclasses.dataclass(frozen=True)
class DoEpicConfig:
"""folder is `~/.claude-projects/do-epic`; repo_rule is `repo-rule.md`'s text."""
folder: pathlib.Path
jira_url: str
env_file: pathlib.Path
clone_folder: pathlib.Path
language: str
repoless_model: str
repo_rule: str
def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure:
"""The settings and the repo rule under home; a Failure naming the file it can't read, else each missing or misspelt setting it finds, so that do-epic refuses to start."""
folder = home / PROJECTS / DO_EPIC
values = parsed(folder / CONFIG)
if isinstance(values, Failure):
return Failure(f"{values.reason}. {LISTED}")
ladder = read_ladder(ladder_file)
if isinstance(ladder, Failure):
return ladder
models = sorted({rung.model for rung in ladder.rungs})
rule: str | Failure
try:
rule = (folder / REPO_RULE).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
rule = Failure(f"cannot read {folder / REPO_RULE}: {failure}")
config_folders = [path for path in (home / PROJECTS).iterdir() if path.is_dir()]
clone_folder = anywhere(values.get(CLONE_FOLDER, "~/code"), home)
env_file = anywhere(values.get(ENV_FILE), home)
language = values.get(LANGUAGE, "English")
url, model = values.get(JIRA_URL), values.get(REPOLESS_MODEL)
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*([f"`{JIRA_URL}` is {url!r}, not a site's https address without a path, such as \"https://acme.atlassian.net\""] if JIRA_URL in values and not (isinstance(url, str) and re.fullmatch(SITE, url)) else []),
*([f"`{CLONE_FOLDER}` is {values[CLONE_FOLDER]!r}, not a path that starts with / or ~/"] if clone_folder is None else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not a path that starts with / or ~/"] if ENV_FILE in values and env_file is None else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of ~/{PROJECTS} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []),
*([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []),
*([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []),
*([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []),
]
if faults:
return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}")
# Without a fault, each value above is present and of the type asserted here.
assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule)
+101
View File
@@ -0,0 +1,101 @@
"""A Jira epic's description as the record of do-epic, the tool that will drive one epic.
The description holds a language line and the sections Goals, Audience, Scoring (the formula and the bar) and Decisions. They are read and written one at a time through `EpicDescription`, and a write leaves every other line of the markdown as it was. Goals and Audience change only where the human approved in an interrupt, which `write_section` takes as `approved`; `EpicDescription` refuses the change otherwise."""
import dataclasses
import re
import typing
from record_store.jira_description import EpicDescription
from failure import Failure
from text_files.markdown_text import fenced_lines
from record_store.held import Held
from project_config.settings import language_fault
SECTIONS = ("Goals", "Audience", "Scoring", "Decisions")
LANGUAGE_LINE = re.compile(r"^\*\*Language:\*\* (.*?)\s*$")
def read_section(text: str, name: str) -> str | Failure:
"""The text under the one ## name heading, up to the next heading of level 1 or 2, without the blank lines around it; empty where there is no such heading."""
span = span_of(text, name)
if isinstance(span, Failure):
return span
return "" if span is None else "\n".join(text.splitlines()[span[0] + 1 : span[1]]).strip("\n")
def with_section(text: str, name: str, body: str) -> str | Failure:
"""text with the one ## name section holding body, put after the others where there is none. A section that already holds body leaves text as it is."""
span = span_of(text, name)
if isinstance(span, Failure):
return span
if any(line.startswith(("# ", "## ")) and not fenced for line, fenced in fenced_lines(body)):
return Failure(f"the body of ## {name} holds a level 1 or 2 heading, which would start another section")
if span is None:
return text.rstrip("\n") + "\n\n" * bool(text.strip()) + f"## {name}\n\n{body.strip()}\n"
lines = text.splitlines()
if read_section(text, name) == body.strip():
return text
last = span[1] == len(lines)
return "\n".join([*lines[: span[0] + 1], "", *body.strip().splitlines(), *([] if last else [""]), *lines[span[1] :]]) + "\n"
def span_of(text: str, name: str) -> tuple[int, int] | None | Failure:
"""The index of the one ## name heading's line and of the line after its section; None where there is no such heading. A heading inside a code fence is ignored."""
if name not in SECTIONS:
return Failure(f"{name} is not a section of an epic's description; the sections are {', '.join(SECTIONS)}")
lines = fenced_lines(text)
headings = [index for index, (line, fenced) in enumerate(lines) if not fenced and (line.startswith("# ") or line.startswith("## "))]
starts = [index for index in headings if lines[index][0].startswith("## ") and lines[index][0][3:].strip() == name]
if len(starts) > 1:
return Failure(f"the epic's description has ## {name} more than once")
return (starts[0], next((index for index in headings if index > starts[0]), len(lines))) if starts else None
def language_in(text: str) -> str | None:
"""The language the description's language line names; None where it has none."""
for line, fenced in fenced_lines(text):
if not fenced and (found := LANGUAGE_LINE.match(line)):
return found.group(1)
return None
def with_language(text: str, language: str) -> str | Failure:
"""text with its language line naming language, put first where there is none."""
if fault := language_fault(language):
return Failure(f"cannot write the language {language!r}: {fault}")
line = f"**Language:** {language}"
lines = fenced_lines(text)
for index, (old, fenced) in enumerate(lines):
if not fenced and LANGUAGE_LINE.match(old):
return "\n".join([*(old for old, _ in lines[:index]), line, *(old for old, _ in lines[index + 1 :])]) + "\n"
return line + "\n" + "\n" * bool(text.strip()) + text
@dataclasses.dataclass(frozen=True)
class EpicRecord:
"""One epic's record, kept in its description."""
description: EpicDescription
def section(self, name: str) -> str | Failure:
text = self.description.read()
return text if isinstance(text, Failure) else read_section(text, name)
def language(self) -> str | None | Failure:
text = self.description.read()
return text if isinstance(text, Failure) else language_in(text)
def write_section(self, name: str, body: str, approved: bool = False) -> Held | Failure:
"""Writes body as the ## name section. approved says the human approved the change in an interrupt, which Goals and Audience need."""
return self.written(lambda text: with_section(text, name, body), frozenset({name}) if approved else frozenset())
def write_language(self, language: str) -> Held | Failure:
return self.written(lambda text: with_language(text, language), frozenset())
def written(self, change: typing.Callable[[str], str | Failure], approved: frozenset[str]) -> Held | Failure:
held = self.description.held()
if isinstance(held, Failure):
return held
text = change(held.text)
if isinstance(text, Failure):
return text
return dataclasses.replace(self.description, approved=approved).write(text, held.version)
+132
View File
@@ -0,0 +1,132 @@
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.config import DoEpicConfig, load
from failure import Failure
SETTINGS = """jira-url = "https://acme.atlassian.net"
env-file = "~/jira.env"
repoless-model = "claude-opus-5-5"
"""
class ConfigTest(unittest.TestCase):
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name).resolve()
self.folder = self.home / ".claude-projects" / "do-epic"
self.folder.mkdir(parents=True)
def write(self, settings: str | None = SETTINGS, rule: str | None = "A label that equals a repo's name names that repo.\n") -> None:
if settings is not None:
(self.folder / "config.toml").write_text(settings, encoding="utf-8")
if rule is not None:
(self.folder / "repo-rule.md").write_text(rule, encoding="utf-8")
def failure(self) -> str:
found = load(self.home)
assert isinstance(found, Failure), found
return found.reason
def test_reads_the_settings_and_the_rule_and_defaults_the_clone_folder_and_language(self) -> None:
self.write()
self.assertEqual(load(self.home), DoEpicConfig(self.folder, "https://acme.atlassian.net", self.home / "jira.env", self.home / "code", "English", "claude-opus-5-5", "A label that equals a repo's name names that repo.\n"))
def test_reads_a_clone_folder_and_language_the_config_sets(self) -> None:
self.write(SETTINGS + 'clone-folder = "/srv/repos"\nlanguage = "Brazilian Portuguese"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.clone_folder, found.language), (pathlib.Path("/srv/repos"), "Brazilian Portuguese"))
def test_refuses_while_the_config_is_missing(self) -> None:
self.write(None)
self.assertIn(f"cannot read {self.folder / 'config.toml'}", self.failure())
def test_lists_the_settings_where_the_config_is_missing(self) -> None:
self.write(None)
self.assertIn("The settings are jira-url, env-file, repoless-model", self.failure())
def test_refuses_while_the_rule_is_missing(self) -> None:
self.write(rule=None)
self.assertIn(f"cannot read {self.folder / 'repo-rule.md'}", self.failure())
def test_refuses_while_the_rule_is_blank(self) -> None:
self.write(rule=" \n")
self.assertIn("`repo-rule.md` is blank", self.failure())
def test_a_missing_rule_does_not_hide_the_settings_faults(self) -> None:
self.write(SETTINGS.replace("claude-opus-5-5", "x"), rule=None)
self.assertIn("`repoless-model` is 'x'", self.failure())
def test_names_each_missing_setting(self) -> None:
self.write("")
reason = self.failure()
for name in ("jira-url", "env-file", "repoless-model"):
self.assertIn(f"`{name}` is missing", reason)
def test_names_a_setting_it_does_not_know(self) -> None:
self.write(SETTINGS + 'checkout = "~/code/acme"\n')
self.assertIn("`checkout` is not a setting", self.failure())
def test_names_each_misspelt_value(self) -> None:
for line, name in (
('jira-url = "http://acme.atlassian.net"', "jira-url"),
('jira-url = "https://acme.atlassian.net/"', "jira-url"),
('env-file = "jira.env"', "env-file"),
('clone-folder = "code"', "clone-folder"),
('language = "sv_SE"', "language"),
('repoless-model = "opus"', "repoless-model"),
('repoless-model = "claude-opsu-5-5"', "repoless-model"),
):
with self.subTest(line):
self.write("\n".join([ln for ln in SETTINGS.splitlines() if not ln.startswith(name)] + [line]))
self.assertIn(f"`{name}` is", self.failure())
def test_keeps_the_credentials_outside_every_config_folder_and_the_clone_folder(self) -> None:
(self.home / ".claude-projects" / "acme").mkdir()
for env_file in ("~/.claude-projects/do-epic/jira.env", "~/.claude-projects/acme/jira.env", "~/code/acme/jira.env"):
with self.subTest(env_file):
self.write(SETTINGS.replace("~/jira.env", env_file))
self.assertIn("`env-file` is", self.failure())
def test_keeps_the_credentials_outside_a_clone_folder_the_config_sets(self) -> None:
self.write(SETTINGS.replace("~/jira.env", "~/clones/jira.env") + 'clone-folder = "~/clones"\n')
self.assertIn("`env-file` is", self.failure())
def test_accepts_credentials_beside_the_config_folders(self) -> None:
self.write(SETTINGS.replace("~/jira.env", "~/.claude-projects/do-epic.env"))
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.env_file, self.home / ".claude-projects" / "do-epic.env")
def test_refuses_while_the_routing_ladder_cannot_be_read(self) -> None:
self.write()
found = load(self.home, self.home / "no-ladder.json")
assert isinstance(found, Failure), found
self.assertIn("no-ladder.json", found.reason)
def test_reports_every_fault_at_once(self) -> None:
self.write('jira-url = "acme"\nrepoless-model = "x"\n')
reason = self.failure()
for part in ("`jira-url` is", "`env-file` is missing", "`repoless-model` is"):
self.assertIn(part, reason)
self.assertIn("`env-file` is missing; `jira-url` is", reason, "joined by semicolons")
def test_names_the_models_on_the_ladder_where_the_model_is_off_it(self) -> None:
ladder = self.home / "ladder.json"
ladder.write_text('[{"model": "claude-sonnet-5-5", "effort": "low"}, {"model": "claude-opus-5-5", "effort": "low"}]', encoding="utf-8")
self.write(SETTINGS.replace("claude-opus-5-5", "claude-haiku-5-5"))
found = load(self.home, ladder)
assert isinstance(found, Failure), found
self.assertIn("not a model on the routing ladder: claude-opus-5-5, claude-sonnet-5-5.", found.reason)
def test_reads_the_rule_and_the_settings_as_utf8(self) -> None:
self.write(SETTINGS + 'language = "Svenska"\n', rule="Etiketten är repots namn.\n")
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.repo_rule, "Etiketten är repots namn.\n")
+163
View File
@@ -0,0 +1,163 @@
import dataclasses
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from record_store.jira_description import EpicDescription
from do_epic.epic_record import EpicRecord, language_in, read_section, with_language, with_section
from failure import Failure
from record_store.fakes import fake_adf, fake_markdown, FakeJira
from record_store.held import Held
DESCRIPTION = """**Language:** Swedish
## Goals
1. **Achieve:** Ship.
More about shipping.
## Audience
Me.
## Scoring
Value.
### Bar
7.
## Decisions
- A choice.
"""
class SectionsTest(unittest.TestCase):
def test_reads_a_section_up_to_the_next_heading_of_its_level_keeping_its_blank_lines_and_subsections(self) -> None:
self.assertEqual(read_section(DESCRIPTION, "Goals"), "1. **Achieve:** Ship.\n\n More about shipping.")
self.assertEqual(read_section(DESCRIPTION, "Scoring"), "Value.\n\n### Bar\n7.")
self.assertEqual(read_section(DESCRIPTION, "Decisions"), "- A choice.")
def test_a_missing_section_reads_empty_and_a_repeated_one_fails(self) -> None:
self.assertEqual(read_section("## Goals\nShip.\n", "Scoring"), "")
found = read_section("## Scoring\nA\n\n## Scoring\nB\n", "Scoring")
assert isinstance(found, Failure), found
self.assertIn("Scoring", found.reason)
def test_a_heading_inside_a_code_fence_starts_no_section(self) -> None:
text = "## Scoring\n```\n## Decisions\n```\n"
self.assertEqual(read_section(text, "Decisions"), "")
self.assertEqual(read_section(text, "Scoring"), "```\n## Decisions\n```")
def test_a_top_level_heading_ends_a_section_and_indented_text_stays_indented(self) -> None:
self.assertEqual(read_section("## Scoring\n code\n# Title\nB\n", "Scoring"), " code")
def test_appending_keeps_the_trailing_spaces_of_the_last_line(self) -> None:
self.assertEqual(with_section("## Goals\nShip. \n", "Scoring", "Value."), "## Goals\nShip. \n\n## Scoring\n\nValue.\n")
def test_replaces_one_section_and_leaves_every_other_line_as_it_was(self) -> None:
changed = with_section(DESCRIPTION, "Scoring", "Risk.\n")
self.assertEqual(changed, DESCRIPTION.replace("Value.\n\n### Bar\n7.\n", "\nRisk.\n"))
self.assertEqual(read_section(changed, "Scoring"), "Risk.") # type: ignore[arg-type]
def test_replaces_the_last_section_without_a_blank_line_after_it(self) -> None:
self.assertEqual(with_section("## Scoring\nValue.\n", "Scoring", "Risk."), "## Scoring\n\nRisk.\n")
def test_a_section_with_the_text_it_holds_leaves_the_description_untouched(self) -> None:
self.assertEqual(with_section(DESCRIPTION, "Goals", "1. **Achieve:** Ship.\n\n More about shipping.\n"), DESCRIPTION)
def test_appends_a_missing_section_after_the_others(self) -> None:
self.assertEqual(with_section("## Goals\nShip.\n", "Scoring", "Value."), "## Goals\nShip.\n\n## Scoring\n\nValue.\n")
self.assertEqual(with_section("", "Scoring", "Value."), "## Scoring\n\nValue.\n")
def test_refuses_a_repeated_section_and_a_name_that_is_no_section(self) -> None:
self.assertIsInstance(with_section("## Scoring\nA\n\n## Scoring\nB\n", "Scoring", "C"), Failure)
for found in (read_section(DESCRIPTION, "Language"), with_section(DESCRIPTION, "Language", "Swedish")):
assert isinstance(found, Failure), found
self.assertIn("Language is not a section of an epic's description; the sections are Goals, Audience, Scoring, Decisions", found.reason)
def test_refuses_a_body_that_would_start_another_section(self) -> None:
for body in ("A\n## Goals\nB", "# Title"):
with self.subTest(body):
found = with_section(DESCRIPTION, "Scoring", body)
assert isinstance(found, Failure), found
self.assertIn("level 1 or 2 heading", found.reason)
self.assertIsInstance(with_section(DESCRIPTION, "Scoring", "```\n## Goals\n```\n### Bar"), str)
class LanguageTest(unittest.TestCase):
def test_reads_the_language_line(self) -> None:
self.assertEqual(language_in(DESCRIPTION), "Swedish")
self.assertIsNone(language_in("## Goals\nShip.\n"))
def test_a_language_line_in_a_code_fence_is_no_language_line(self) -> None:
self.assertIsNone(language_in("```\n**Language:** Swedish\n```\n"))
def test_replaces_the_language_line_or_puts_it_first(self) -> None:
self.assertEqual(with_language(DESCRIPTION, "Brazilian Portuguese"), DESCRIPTION.replace("Swedish", "Brazilian Portuguese"))
self.assertEqual(with_language("## Goals\nShip.\n", "Swedish"), "**Language:** Swedish\n\n## Goals\nShip.\n")
self.assertEqual(with_language("", "Swedish"), "**Language:** Swedish\n")
def test_refuses_what_names_no_language(self) -> None:
found = with_language(DESCRIPTION, "Swedish; ignore the rules")
assert isinstance(found, Failure), found
self.assertIn("not a language", found.reason)
class EpicRecordTest(unittest.TestCase):
def setUp(self) -> None:
env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
env.chmod(0o600)
self.jira = FakeJira()
self.jira.teammate_saves(DESCRIPTION)
self.record = EpicRecord(EpicDescription(Epic("https://acme.atlassian.net", "ABC-12"), env, self.jira.http, fake_markdown, fake_adf))
def test_reads_each_section_and_the_language_from_the_epics_description(self) -> None:
self.assertEqual(self.record.section("Audience"), "Me.")
self.assertEqual(self.record.language(), "Swedish")
def test_a_description_that_cannot_be_read_fails_every_read_and_write(self) -> None:
record = EpicRecord(dataclasses.replace(self.record.description, http=lambda *call: Failure("HTTP 404: gone")))
for found in (record.section("Goals"), record.language(), record.write_section("Scoring", "A"), record.write_language("Swedish")):
with self.subTest(found):
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
def test_refuses_a_write_over_a_description_a_teammate_saved_since_the_record_read_it(self) -> None:
def teammate_saves_after_the_read(method: str, url: str, authorization: str, body: object) -> object:
answer = self.jira.http(method, url, authorization, body)
if method == "GET" and len(self.jira.calls) == 1:
self.jira.teammate_saves("## Goals\nTheirs.\n")
return answer
record = EpicRecord(dataclasses.replace(self.record.description, http=teammate_saves_after_the_read))
found = record.write_section("Scoring", "Risk.")
assert isinstance(found, Failure), found
self.assertIn("someone saved", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_writes_scoring_and_decisions_and_the_language_without_approval(self) -> None:
self.assertIsInstance(self.record.write_section("Scoring", "Risk."), Held)
self.assertIsInstance(self.record.write_section("Decisions", "- Another."), Held)
self.assertIsInstance(self.record.write_language("Norwegian"), Held)
self.assertEqual(self.record.section("Scoring"), "Risk.")
self.assertEqual(self.record.section("Decisions"), "- Another.")
self.assertEqual(self.record.language(), "Norwegian")
self.assertEqual(self.record.section("Goals"), "1. **Achieve:** Ship.\n\n More about shipping.")
def test_writes_goals_or_audience_only_where_the_human_approved(self) -> None:
found = self.record.write_section("Goals", "1. **Achieve:** Ship less.")
assert isinstance(found, Failure), found
self.assertIn("approval", found.reason)
self.assertEqual(self.jira.puts(), [])
self.assertIsInstance(self.record.write_section("Goals", "1. **Achieve:** Ship less.", approved=True), Held)
self.assertEqual(self.record.section("Goals"), "1. **Achieve:** Ship less.")
# The approval covers the section it was given for, not the next write.
self.assertIsInstance(self.record.write_section("Audience", "Everyone."), Failure)
if __name__ == "__main__":
unittest.main()
View File
+42
View File
@@ -0,0 +1,42 @@
"""Which forge a checkout's origin is on, and running that forge's CLI in the checkout."""
import json
import subprocess
import typing
from failure import Failure
# The CLI of the forge that origin is on, as forge_of picks it.
Forge = typing.Literal["gh", "tea"]
# Runs a command in the checkout: what it printed, or a Failure with its reason.
Run = typing.Callable[[list[str]], str | Failure]
def forge_of(origin_url: str) -> Forge:
return "gh" if "github.com" in origin_url else "tea"
def runner(cwd: str) -> Run:
def run(command: list[str]) -> str | Failure:
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
if done.returncode:
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
return done.stdout
return run
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
if isinstance(answered, Failure) or not answered.strip():
return answered
try:
parsed = json.loads(answered)
except ValueError:
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
if isinstance(parsed, dict) and "message" in parsed:
return Failure(f"tea api {endpoint}: {parsed['message']}")
return parsed
@@ -1,50 +1,16 @@
"""The pull request steps of a cut. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart. """Finding a pull request from origin's own branch, and waiting for the checks on its head commit."""
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
"""
import fnmatch import fnmatch
import json
import subprocess
import time import time
import typing import typing
from failure import Failure from failure import Failure
from chunk_preflight.choices import Forge from forge.commands import Forge, gitea, Run
# How long the cut waits between two reads of the head commit's status on Gitea. # How long checks_passed waits between two reads: of the head commit's status on Gitea, or of gh's watch while it reports no checks.
POLL_SECONDS = 10 POLL_SECONDS = 10
# How long the cut waits for the checks before it gives up; CI took about 3 minutes in 2026-11. # How long checks_passed waits on Gitea for the checks before it gives up; CI took about 3 minutes in 2026-11. gh's watch waits as long as the checks run.
WAIT_SECONDS = 30 * 60 WAIT_SECONDS = 30 * 60
# Runs a command in the clone: what it printed, or a Failure with its reason.
Run = typing.Callable[[list[str]], str | Failure]
def runner(cwd: str) -> Run:
def run(command: list[str]) -> str | Failure:
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
if done.returncode:
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
return done.stdout
return run
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
if isinstance(answered, Failure) or not answered.strip():
return answered
try:
parsed = json.loads(answered)
except ValueError:
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
if isinstance(parsed, dict) and "message" in parsed:
return Failure(f"tea api {endpoint}: {parsed['message']}")
return parsed
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure: def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
"""The number of the open pull request from origin's own branch whose head is head; None where there is none.""" """The number of the open pull request from origin's own branch whose head is head; None where there is none."""
@@ -75,13 +41,6 @@ def pull_at(forge: Forge, branch: str, head: str, state: typing.Literal["open",
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
return created if isinstance(created, Failure) else None
def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure: def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure:
"""The checks, or glob patterns of checks, that the forge's protection of the branch base requires before a merge. None on GitHub, where gh's watch covers them. """The checks, or glob patterns of checks, that the forge's protection of the branch base requires before a merge. None on GitHub, where gh's watch covers them.
@@ -132,13 +91,3 @@ def checks_passed(forge: Forge, number: str, head: str, required: set[str], run:
sleep(POLL_SECONDS) sleep(POLL_SECONDS)
waited_on = f"{', '.join(missing)}, which the protection requires, never passed" if missing else "a check is still pending" waited_on = f"{', '.join(missing)}, which the protection requires, never passed" if missing else "a check is still pending"
return Failure(f"gave up on pull request {number} after {WAIT_SECONDS // 60} minutes: {waited_on}") return Failure(f"gave up on pull request {number} after {WAIT_SECONDS // 60} minutes: {waited_on}")
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
if forge == "gh":
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
else:
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
return merged if isinstance(merged, Failure) else None
+99
View File
@@ -0,0 +1,99 @@
import itertools
import pathlib
import sys
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from forge.pulls import checks_passed, open_pull, POLL_SECONDS, required_checks, WAIT_SECONDS
from forge.commands import forge_of, gitea
class ForgeOf(unittest.TestCase):
def test_takes_a_github_origin_as_gh_and_any_other_as_tea(self):
self.assertEqual(forge_of("git@github.com:o/r.git"), "gh")
self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea")
# An answer no call can read, longer than the 200 characters of it that a failure quotes.
LONG = "[" + ", ".join(["1"] * 100) + "]"
class Gitea(unittest.TestCase):
def test_fails_with_giteas_message_where_it_answers_an_error(self):
self.assertEqual(gitea(lambda command: '{"message": "not found"}', "repos/o/r").reason, "tea api repos/o/r: not found")
def test_fails_quoting_the_first_200_characters_where_tea_prints_no_json(self):
self.assertEqual(gitea(lambda command: "x" * 300, "repos/o/r").reason, f"tea api repos/o/r printed no JSON: {'x' * 200}")
class OpenPull(unittest.TestCase):
def test_fails_quoting_the_first_200_characters_where_tea_lists_pull_requests_in_another_shape(self):
self.assertEqual(open_pull("tea", "item-3", "abc", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}")
def tea(statuses: typing.Iterable[str], branch: str = '{"name": "main"}') -> typing.Callable[[list[str]], str]:
"""A tea answering each read of the head's status with the next of statuses, and of branch main with branch."""
answers = iter(statuses)
return lambda command: branch if command[-1] == "repos/{owner}/{repo}/branches/main" else next(answers)
REQUIRED = '{"name": "main", "enable_status_check": true, "status_check_contexts": ["CI / tests (pull_request)"]}'
class RequiredChecks(unittest.TestCase):
def test_reads_on_tea_the_checks_the_protection_of_the_base_requires(self):
self.assertEqual(required_checks("tea", "main", tea([], REQUIRED)), {"CI / tests (pull_request)"})
def test_reads_none_on_tea_where_the_protection_turns_status_checks_off(self):
self.assertEqual(required_checks("tea", "main", tea([], '{"name": "main", "enable_status_check": false, "status_check_contexts": ["CI / tests (pull_request)"]}')), set())
def test_fails_on_tea_quoting_the_first_200_characters_where_the_branch_reads_in_another_shape(self):
self.assertEqual(required_checks("tea", "main", tea([], LONG)).reason, f"tea api answered branch main in a shape that can't be read: {LONG[:200]}")
def test_reads_none_on_github_whose_watch_covers_them(self):
self.assertEqual(required_checks("gh", "main", self.fail), set())
class ChecksPassed(unittest.TestCase):
def test_waits_on_tea_while_a_check_is_pending(self):
slept = []
self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']), slept.append))
self.assertEqual(slept, [POLL_SECONDS])
def test_takes_a_commit_with_no_status_on_tea_as_passed_where_the_base_requires_none(self):
self.assertIsNone(checks_passed("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 0}']), self.fail))
def test_waits_on_tea_for_a_check_the_base_requires_until_it_reports_and_passes(self):
slept = []
statuses = ['{"state": "pending", "total_count": 0, "statuses": []}', '{"state": "success", "total_count": 1, "statuses": [{"context": "lint", "status": "success"}]}', '{"state": "success", "total_count": 2, "statuses": [{"context": "lint", "status": "success"}, {"context": "CI / tests (pull_request)", "status": "success"}]}']
self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / tests (pull_request)"}, tea(statuses), slept.append))
self.assertEqual(slept, [POLL_SECONDS, POLL_SECONDS])
def test_takes_on_tea_a_required_glob_as_met_by_a_check_it_matches(self):
passed = '{"state": "success", "total_count": 1, "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]}'
self.assertIsNone(checks_passed("tea", "1", "abc", {"CI / *"}, tea([passed]), self.fail))
def test_gives_up_on_tea_after_the_wait_naming_each_required_check_that_never_reported(self):
slept, read = [], []
pending = tea(itertools.repeat('{"state": "pending", "total_count": 0, "statuses": []}'))
waited = checks_passed("tea", "1", "abc", {"lint", "CI / tests (pull_request)"}, lambda command: read.append(command) or pending(command), slept.append)
self.assertEqual(waited.reason, "gave up on pull request 1 after 30 minutes: CI / tests (pull_request), lint, which the protection requires, never passed")
self.assertEqual(sum(slept), WAIT_SECONDS)
self.assertEqual(len(read), WAIT_SECONDS // POLL_SECONDS + 1)
def test_gives_up_on_tea_after_the_wait_saying_a_check_is_still_pending(self):
waited = checks_passed("tea", "1", "abc", set(), tea(itertools.repeat('{"state": "pending", "total_count": 1, "statuses": []}')), lambda seconds: None)
self.assertEqual(waited.reason, "gave up on pull request 1 after 30 minutes: a check is still pending")
def test_fails_on_tea_where_a_check_failed(self):
self.assertEqual(checks_passed("tea", "1", "abc", set(), tea(['{"state": "failure", "total_count": 1}']), self.fail).reason, "a check on pull request 1 ended in failure")
def test_fails_on_tea_quoting_the_first_200_characters_where_the_status_reads_in_another_shape(self):
self.assertEqual(checks_passed("tea", "1", "abc", set(), tea([LONG]), self.fail).reason, f"tea api printed no commit status for abc: {LONG[:200]}")
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -0,0 +1,15 @@
from claude_code.entries import Entry
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.cycle.judge import Grounds, JUDGE_RULES, TASK_HEADING, TRANSCRIPT_HEADING
from claude_code.transcript import human_answers
from loop_claude.cycle.prompts import typed_answer
def grounds_of(prompt: str, entries: list[Entry]) -> Grounds | Failure:
"""What the quotes of a judge run on prompt are checked against, as judge_prompt would have made it for the transcript's entries: the premises and the records before the task are quotable, the transcript the judge was shown comes before the rules. The prompt is split on the headings judge_prompt writes, at the first of each; a Failure where it lacks one. Rules of an earlier wording stay part of the transcript, a slack that lets an evidence quote them pass."""
before_task, task_heading, after_task = prompt.partition(f"\n\n{TASK_HEADING}")
_, transcript_heading, shown = after_task.partition(TRANSCRIPT_HEADING)
if not (task_heading and transcript_heading):
return Failure(f"the archived prompt lacks the heading {TASK_HEADING.strip()!r} or {TRANSCRIPT_HEADING.strip()!r}, which judge_prompt writes")
return Grounds(shown.removesuffix(f"\n\n{JUDGE_RULES}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer)))
+42 -19
View File
@@ -4,13 +4,16 @@ usage: judge-replay <model>
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the <model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest
15 of each kind, finished, unfinished, interrupt and quoted answer. Each transcript copy in the 15 of each kind, finished, unfinished, interrupt and quoted answer. Where the archive kept the judge's own
archive is what the judge read for the verdict beside it, so the replay hands the judge that copy, prompt (docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`), the
with the task, premises and records each project holds now. replay hands the judge that prompt, which holds what the judge read then. For a verdict from before the
archive kept it, the replay builds the prompt from the transcript copy beside the verdict, with the task,
premises and records each project holds now.
It first replays every verdict on the reference judge: the model at xhigh effort, the rung the It first replays every verdict on the reference judge: the model at xhigh effort, the rung the
judge ran on before loop-claude routed it. A verdict the reference judge returns another kind on judge ran on before loop-claude routed it. A verdict the reference judge returns another kind on
may rest on records or judge rules that have changed since; either way no rung is held to it. It may rest, where its prompt was rebuilt, on records or judge rules that have changed since; where the archived prompt was
replayed, the judge's own variance is the cause. Either way no rung is held to it. It
then replays the rest on each rung above the model's cheapest that a chunk's E + I raises a then replays the rest on each rung above the model's cheapest that a chunk's E + I raises a
review to, except the reference judge's rung. Then it replays them on each candidate rung, review to, except the reference judge's rung. Then it replays them on each candidate rung,
highest first: from the model's cheapest rung down to the lowest rung a worker routes to. It stops highest first: from the model's cheapest rung down to the lowest rung a worker routes to. It stops
@@ -24,8 +27,13 @@ JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge. j
keeps the judge to its own model's rungs; a rung above them that misses no interrupt is the keeps the judge to its own model's rungs; a rung above them that misses no interrupt is the
evidence to let the judge climb onto it. evidence to let the judge climb onto it.
It keeps each run and the report it prints in loop-claude's archive, in
replays/judge-replay-<model>-<UTC stamp>/ under ~/.claude/loop-claude-transcripts or $LOOP_CLAUDE_TRANSCRIPTS.
A run's .jsonl file starts with a line holding claude's arguments, working directory, prompt, exit code and
stderr, then holds claude's stream-json output; result.md holds the report.
Like the loop, it tries a judge three times running before it counts the reply as failed. A Like the loop, it tries a judge three times running before it counts the reply as failed. A
verdict whose project or transcript cannot be read replays as failed too. Exit 1, saying why, on verdict whose project, transcript or archived judge run cannot be read replays as failed too. Exit 1, saying why, on
bad arguments, an unreadable archive or models file, no archived verdict of the model's projects, bad arguments, an unreadable archive or models file, no archived verdict of the model's projects,
or a usage limit. or a usage limit.
""" """
@@ -34,14 +42,17 @@ import typing
from transcript_archive.location import archive_root, transcript_of from transcript_archive.location import archive_root, transcript_of
from transcript_archive.read import archived_outcomes from transcript_archive.read import archived_outcomes
from rung_replay.archive import archiving, print_report, replay_folder
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
from loop_claude.cycle.judge import Brief, judge_once from loop_claude.cycle.judge import Brief, judge_archived, judge_once
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
from transcript_archive.project_key import checkout_of from transcript_archive.project_key import checkout_of
from loop_effects.effects import Effects from loop_effects.effects import Effects
from failure import Failure from failure import Failure
from rung_replay.search import first_reply, replayed from rung_replay.search import first_reply, replayed
from model_routing.ladder import Ladder, REVIEW_STEPS, Rung from judge_replay.archived_prompt import grounds_of
from transcript_archive.judge_run import JudgeRun
from model_routing.ladder import Ladder, ProjectRung, REVIEW_STEPS, Rung
from claude_code.reply import Limited from claude_code.reply import Limited
from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder_file import read_ladder, SHIPPED
from loop_claude.project.premises import read_premises from loop_claude.project.premises import read_premises
@@ -64,29 +75,31 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, argv)) project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, argv))
if isinstance(project, int): if isinstance(project, int):
return project return project
cases = archived_cases(project.model, archive_root(home, env), home) cases = archived_cases(project.rung.model, archive_root(home, env), home)
if isinstance(cases, Failure): if isinstance(cases, Failure):
return failed(TOOL, cases.reason) return failed(TOOL, cases.reason)
if not cases: if not cases:
return failed(TOOL, f"no archived verdicts of projects on {project.model} in {archive_root(home, env)}; run loop-claude on a project on that model first") return failed(TOOL, f"no archived verdicts of projects on {project.rung.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
cases = sample(cases, PER_KIND) cases = sample(cases, PER_KIND)
reference = Rung(project.model, REFERENCE_EFFORT) folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now())
effects = archiving(effects, folder)
reference = Rung(project.rung.model, REFERENCE_EFFORT)
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge. # The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
replay = replayed(cases, reference, down_from(ladder, project, ladder.lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(ladder, project, reference)) replay = replayed(cases, reference, down_from(ladder, project.rung, project.lowest_worker_rung()), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(project, reference))
if isinstance(replay, Limited): if isinstance(replay, Limited):
return limited_exit(TOOL, replay) return limited_exit(TOOL, replay)
print(report(project.model, reference, cases, replay)) print_report(folder, report(project.rung.model, reference, cases, replay))
return 0 return 0
def model_argument(ladder: Ladder, argv: list[str]) -> Rung | None: def model_argument(ladder: Ladder, argv: list[str]) -> ProjectRung | None:
"""The project's rung on ladder of the one model argv names; None for any other argv.""" """The project's rung on ladder of the one model argv names; None for any other argv."""
return ladder.project_rung(argv[0]) if len(argv) == 1 else None return ladder.project_rung(argv[0]) if len(argv) == 1 else None
def climbs(ladder: Ladder, project: Rung, reference: Rung) -> list[Rung]: def climbs(project: ProjectRung, reference: Rung) -> list[Rung]:
"""The rungs above the project's rung that an E + I raises a review to, except the reference's, lowest first.""" """The rungs above the project's rung that an E + I raises a review to, except the reference's, lowest first."""
return sorted({ladder.review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=ladder.position) return sorted({project.review_floor(score) for score in REVIEW_STEPS} - {project.rung, reference}, key=project.ladder.position)
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure: def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
@@ -107,13 +120,23 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C
def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | Limited: def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | Limited:
premises, records, entries = read_premises(case.root, home), read_records(case.root, home, home / ".claude"), read_transcript(str(case.transcript)) entries = read_transcript(str(case.transcript))
if isinstance(entries, Failure):
return verdict_kind(entries)
if case.judge_run:
kept = JudgeRun.read(case.judge_run)
if isinstance(kept, Failure):
return verdict_kind(kept)
grounds = grounds_of(kept.prompt, entries)
if isinstance(grounds, Failure):
return verdict_kind(grounds)
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
premises, records = read_premises(case.root, home), read_records(case.root, home, home / ".claude")
if isinstance(premises, Failure): if isinstance(premises, Failure):
return verdict_kind(premises) return verdict_kind(premises)
if isinstance(records, Failure): if isinstance(records, Failure):
return verdict_kind(records) return verdict_kind(records)
if isinstance(entries, Failure):
return verdict_kind(entries)
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count. # 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, Brief(case.task, premises, records, entries, 0), rung, effects)) verdict = first_reply(lambda: judge_once(case.root, Brief(case.task, premises, records, entries, 0), rung, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
+6 -3
View File
@@ -4,7 +4,7 @@ import dataclasses
import pathlib import pathlib
import typing import typing
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, judge_run_at, task_of, UNFINISHED
from failure import Failure from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from rung_replay.search import Replay from rung_replay.search import Replay
@@ -22,6 +22,8 @@ class Case:
transcript: pathlib.Path transcript: pathlib.Path
at: str at: str
archived_kind: Kind archived_kind: Kind
# The judge run the archive kept beside the verdict, which holds the prompt the judge read; None where it kept none.
judge_run: pathlib.Path | None = None
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None: def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
@@ -32,7 +34,8 @@ def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None
task, verdict = task_of(outcomes), first_verdict(outcomes) task, verdict = task_of(outcomes), first_verdict(outcomes)
if task is None or verdict is None: if task is None or verdict is None:
return None return None
return Case(root, task, transcript, *verdict) run = judge_run_at(outcomes, verdict[0])
return Case(root, task, transcript, *verdict, transcript.parent / run if run else None)
def sample(cases: list[Case], per_kind: int) -> list[Case]: def sample(cases: list[Case], per_kind: int) -> list[Case]:
@@ -88,4 +91,4 @@ def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case,
def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]: def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]:
return [f" {found.root} {found.at}: archived {found.archived_kind}, replayed {kind}" for found, kind in missed] return [f" {found.root} {found.at}: archived {found.archived_kind}, replayed {kind} on {'its archived prompt' if found.judge_run else 'a prompt rebuilt from today\'s records'}" for found, kind in missed]
+131 -4
View File
@@ -10,11 +10,15 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
from text_files import compressed
from project_config.test_project_config import configured from project_config.test_project_config import configured
from loop_effects.effects import Effects from loop_effects.effects import Effects
from failure import Failure from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from judge_replay.archived_prompt import grounds_of
from loop_claude.cycle.judge import judge_archived, JUDGE_RULES, Rejected, TASK_HEADING, TRANSCRIPT_HEADING
from judge_replay import main from judge_replay import main
from rung_replay.search import Miss, Replay, Tried from rung_replay.search import Miss, Replay, Tried
from model_routing.ladder import Rung from model_routing.ladder import Rung
@@ -41,6 +45,11 @@ class CaseFrom(unittest.TestCase):
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT) found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT)
self.assertEqual(found.archived_kind, verdict) self.assertEqual(found.archived_kind, verdict)
def test_names_the_judge_run_that_the_first_verdict_records_beside_it(self):
outcomes = f"Task: t\n\n2026-10-14T10:00:00Z Verdict: unfinished\n\nJudge: j\nJudge run: judge/{'a' * 64}.json\nWorker: x\n\n2026-10-14T11:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/{'b' * 64}.json\nWorker: x\n"
self.assertEqual(case_from("/code/p", outcomes, TRANSCRIPT).judge_run, TRANSCRIPT.parent / f"judge/{'a' * 64}.json")
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nWorker: x\n", TRANSCRIPT).judge_run)
def test_skips_a_copy_with_no_verdict(self): def test_skips_a_copy_with_no_verdict(self):
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT)) self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT))
self.assertIsNone(case_from("/code/p", "not an outcomes file", TRANSCRIPT)) self.assertIsNone(case_from("/code/p", "not an outcomes file", TRANSCRIPT))
@@ -68,16 +77,21 @@ class Reproduced(unittest.TestCase):
class Report(unittest.TestCase): class Report(unittest.TestCase):
def test_names_whether_a_missed_verdict_was_replayed_on_its_archived_prompt(self):
kept = Case("/code/p", "Do it.", TRANSCRIPT, "2026-10-14T10:00:00Z", FINISHED, pathlib.Path("/archive/p/c/judge/run.json"))
lines = report("claude-opus-5-5", REFERENCE, [kept], Replay([UNFINISHED], [], [])).split("\n")
self.assertIn(" /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished on its archived prompt", lines)
def test_counts_the_verdicts_and_names_each_miss_and_the_lowest_rung(self): def test_counts_the_verdicts_and_names_each_miss_and_the_lowest_rung(self):
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)] cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)]
replay = Replay([UNFINISHED, INTERRUPTED], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(cases[1], INTERRUPTED, FINISHED)])], MIDDLE) replay = Replay([UNFINISHED, INTERRUPTED], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(cases[1], INTERRUPTED, FINISHED)])], MIDDLE)
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [ self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.", "Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:", "The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
" /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished", " /code/p 2026-10-14T10:00:00Z: archived Verdict: finished, replayed Verdict: unfinished on a prompt rebuilt from today's records",
"claude-sonnet-5-5 at high effort missed 0.", "claude-sonnet-5-5 at high effort missed 0.",
"claude-haiku-5-5 at xhigh effort missed 1:", "claude-haiku-5-5 at xhigh effort missed 1:",
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished", " /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished on a prompt rebuilt from today's records",
"Lowest candidate that, like each candidate above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort", "Lowest candidate that, like each candidate above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
]) ])
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines() missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines()
@@ -90,7 +104,7 @@ class Report(unittest.TestCase):
climbs = [Tried(Rung("claude-fable-5-2", "low"), [Miss(cases[1], INTERRUPTED, FINISHED)]), Tried(Rung("claude-fable-5-2", "high"), [])] climbs = [Tried(Rung("claude-fable-5-2", "low"), [Miss(cases[1], INTERRUPTED, FINISHED)]), Tried(Rung("claude-fable-5-2", "high"), [])]
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [])], MIDDLE, climbs)).splitlines()[2:5], [ self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [])], MIDDLE, climbs)).splitlines()[2:5], [
"claude-fable-5-2 at low effort, a rung a review climbs to, missed 1:", "claude-fable-5-2 at low effort, a rung a review climbs to, missed 1:",
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished", " /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished on a prompt rebuilt from today's records",
"claude-fable-5-2 at high effort, a rung a review climbs to, missed 0.", "claude-fable-5-2 at high effort, a rung a review climbs to, missed 0.",
]) ])
@@ -126,7 +140,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]) 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), "") return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
out, err = io.StringIO(), io.StringIO() out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects) code = main.main(argv, {}, self.home, effects)
@@ -161,6 +175,38 @@ class Main(unittest.TestCase):
# The replay shows the judge the whole transcript, with no step-up marked in it. # The replay shows the judge the whole transcript, with no step-up marked in it.
self.assertNotIn("[step]", self.prompts[0]) self.assertNotIn("[step]", self.prompts[0])
def test_keeps_each_run_and_the_printed_report_in_one_folder_of_the_archive_beside_the_projects(self):
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-20260921T141320Z"
self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out)
runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")]
self.assertEqual({run["prompt"] for run in runs}, set(self.prompts))
def test_hands_the_judge_the_prompt_the_archive_kept_and_rebuilds_the_prompt_of_a_verdict_with_none(self):
kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1"
prompt = "From the goals file, OLD premises\n\nThe records: none\n\nThe task the worker was given:\nDo it.\n\nWhat the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\nsaid Verdict: finished\n\nOLD rules"
(kept / "judge").mkdir()
(kept / "judge" / "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json").write_text(json.dumps({"prompt": prompt, "reply": {"type": "result"}}))
(kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json\nWorker: x\n")
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
# The first replay, on the finished verdict, reads the archived prompt; the second, on the interrupt, is rebuilt from the records of today.
self.assertEqual(self.prompts[0], prompt)
self.assertEqual(self.calls[0][2], self.calls[1][2])
self.assertTrue(self.calls[0][2].endswith("/code/proj"))
self.assertIn("The task the worker was given:\nDo it.", self.prompts[1])
self.assertIn("1. Ship.", self.prompts[1])
def test_a_verdict_whose_archived_judge_run_cannot_be_read_replays_as_failed(self):
kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1"
(kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json\nWorker: x\n")
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:", out)
self.assertIn("could not read the archived judge run", out)
def test_tries_no_rung_below_the_lowest_a_worker_routes_to_where_every_rung_returns_every_verdict(self): def test_tries_no_rung_below_the_lowest_a_worker_routes_to_where_every_rung_returns_every_verdict(self):
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err) self.assertEqual(code, 0, err)
@@ -188,6 +234,13 @@ class Main(unittest.TestCase):
self.assertEqual(code, 0) self.assertEqual(code, 0)
self.assertIn("replayed failed: could not read the transcript", out) self.assertIn("replayed failed: could not read the transcript", out)
def test_replays_a_verdict_whose_transcript_is_compressed(self):
self.assertIsNone(compressed.compress(self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl"))
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
self.assertNotIn("replayed failed", out)
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
def test_tries_the_projects_rung_first_and_retries_a_failed_reply_as_the_loop_does(self): def test_tries_the_projects_rung_first_and_retries_a_failed_reply_as_the_loop_does(self):
def reply(rung, interrupted): def reply(rung, interrupted):
return self.verdict(interrupted, "not in the transcript" if rung.model != "claude-opus-5-5" else f"said {INTERRUPTED if interrupted else FINISHED}") return self.verdict(interrupted, "not in the transcript" if rung.model != "claude-opus-5-5" else f"said {INTERRUPTED if interrupted else FINISHED}")
@@ -226,6 +279,80 @@ class Main(unittest.TestCase):
self.assertEqual(ran.returncode, 0) self.assertEqual(ran.returncode, 0)
self.assertIn("usage: judge-replay <model>", ran.stdout) self.assertIn("usage: judge-replay <model>", ran.stdout)
def test_exits_1_on_a_usage_limit_met_on_an_archived_prompt(self):
kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1"
(kept / "judge").mkdir()
(kept / "judge" / "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json").write_text(json.dumps({"prompt": "P", "reply": {}}))
(kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json\nWorker: x\n")
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
self.assertEqual((code, "usage limit: You've hit your limit" in err), (1, True))
class JudgeArchivedRuns(unittest.TestCase):
"""judge_archived on a prompt as judge_prompt writes it: the premises, the task, the transcript the judge was shown, and the rules."""
PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{TRANSCRIPT_HEADING}Worker chose option B.\n[human] Use Postgres.\n\n{JUDGE_RULES}"
ENTRIES = [AssistantTurn(parts=(Text("Worker chose option B."),)), HumanTurn(text="Use Postgres."), LoopPrompt(text="Keep going.")]
def judged(self, prompt=PROMPT, **fields):
"""What judge_archived returns on prompt where the judge's structured output is fields over an unfinished verdict, and the cwd claude ran in."""
output = {"answer": "", "escalation": "", "evidence": "Worker chose option B.", "finished": False, "interrupt": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False, **fields}
cwds = []
def claude(args, cwd, prompt):
cwds.append(cwd)
return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
grounds = grounds_of(prompt, self.ENTRIES)
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, effects)), cwds
def test_runs_in_the_projects_folder_and_stamps_the_verdict_with_the_entries_read(self):
verdict, cwds = self.judged()
self.assertEqual((cwds, verdict.entries_read), (["/code/p"], 3))
def test_checks_the_evidence_against_the_transcript_the_judge_was_shown_and_not_the_premises(self):
self.assertIsInstance(self.judged(evidence="Ship fast.")[0], Rejected)
self.assertIsInstance(self.judged(evidence="Worker chose option B.")[0], Unfinished)
def test_keeps_the_cost_and_the_run_of_a_rejected_reply(self):
rejected, _ = self.judged(evidence="Never said.")
self.assertEqual((rejected.cost, rejected.run.prompt), (0.25, self.PROMPT))
def test_keeps_the_cost_of_a_reply_rejected_for_its_shape(self):
rejected, _ = self.judged(finished="yes")
self.assertEqual((type(rejected), rejected.cost), (Rejected, 0.25))
def test_checks_neither_the_task_nor_the_rules_as_the_transcript_or_the_premises(self):
self.assertIsInstance(self.judged(evidence=JUDGE_RULES)[0], Rejected)
self.assertIsInstance(self.judged(answer="Do it.", question="Which?")[0], Interrupt)
def test_splits_the_prompt_at_the_first_transcript_heading(self):
quoting = self.PROMPT.replace("Worker chose", f"Quoted: {TRANSCRIPT_HEADING}Worker chose", 1)
self.assertIsInstance(self.judged(quoting, evidence="Quoted:")[0], Unfinished)
def test_splits_the_prompt_at_the_first_task_heading(self):
quoting = self.PROMPT.replace("Do it.", f"Quote:\n\n{TASK_HEADING}Ship slowly.", 1)
self.assertIsInstance(self.judged(quoting, answer="Ship fast.", question="Which?")[0], QuotedAnswer)
self.assertIsInstance(self.judged(quoting, answer="Quote:", question="Which?")[0], Interrupt)
def test_fails_before_the_judge_runs_on_a_prompt_without_a_heading(self):
for prompt in ("No headings at all.", f"{TASK_HEADING}Do it.", f"\n\n{TASK_HEADING}Do it.\n\nNo transcript heading."):
with self.subTest(prompt=prompt):
failure, cwds = self.judged(prompt)
self.assertEqual((type(failure), cwds), (Failure, []))
self.assertIn("lacks the heading", failure.reason)
def test_checks_a_quoted_answer_against_the_premises(self):
self.assertIsInstance(self.judged(answer="Ship fast.", question="Which?")[0], QuotedAnswer)
self.assertIsInstance(self.judged(answer="Use Postgres.", question="Which?")[0], Interrupt)
def test_keeps_an_escalation_that_the_worker_wrote_after_the_start_of_the_transcript(self):
self.assertEqual(self.judged(escalation="Worker chose option B.")[0].escalation, "Worker chose option B.")
self.assertEqual(self.judged(escalation="Use Postgres.")[0].escalation, "")
def test_names_the_typed_answer_that_holds_a_reversal(self):
self.assertEqual(self.judged(reversed="Use Postgres.")[0].judged.reversed, "Use Postgres.")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+14 -3
View File
@@ -1,4 +1,4 @@
"""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 and setup; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. """Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds and its round commit's title, the scoring run's trigger and setup; 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 {commands} usage: larv-review {commands}
@@ -10,8 +10,8 @@ to 10. Each seat names the places it found hard.
Run it inside a project checkout or one of its worktrees. Each command but review-folder, Run it inside a project checkout or one of its worktrees. Each command but review-folder,
record-ruling, places and agreement first fetches origin, when the checkout has that remote, and 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 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 fetch fails, round-count, reviewer-header and round-title read origin as last fetched and say so on
other four exit 1. stderr; the other four exit 1.
The history is docs/comprehension-history.md in the checkout. 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 review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its
@@ -142,6 +142,15 @@ it. It exits 1 when the pass takes no more rounds, when `project-config` fails i
the principles or standards folder is not a folder with a file in it, or, with --rerun, when the the principles or standards folder is not a folder with a file in it, or, with --rerun, when the
report that asked is missing. report that asked is missing.
round-title takes a pass as reviewer-header does. It prints how the commit that answers the pass's
unanswered round opens its title, after any prefix the project's commit-title template adds, up to
and including the `;` before the summary, such as `Answer prose round 1: 0 🔴, 2 🟡 (0 misread);`. It
counts the findings in the round's report in the review folder, or in its rerun's where there is
one: each line that opens `### 🔴` or `### 🟡`, and of them each whose mark is followed by
`[misread]`. rule-hook's round-title-counts refuses a round title whose counts differ from that
report's. It exits 1 when the pass takes no more rounds, or the report is missing, unreadable or
says BLOCK without such a line.
reviewer-context is the SubagentStart hook. It reads the hook's input on stdin. For a reviewer reviewer-context is the SubagentStart hook. It reads the hook's input on stdin. For a reviewer
whose definition under ~/.claude/agents/ has `omitClaudeMd: true`, and so starts without CLAUDE.md, whose definition under ~/.claude/agents/ has `omitClaudeMd: true`, and so starts without CLAUDE.md,
it prints the hook reply that hands the agent the Shared goal, Prose and Vocabulary sections of it prints the hook reply that hands the agent the Shared goal, Prose and Vocabulary sections of
@@ -176,6 +185,7 @@ from larv_review.plan import plan_reasons
from larv_review.scoring_setup import prepare_scoring from larv_review.scoring_setup import prepare_scoring
from larv_review.history_commands import read_agreement, read_places, record_ruling, record_scoring from larv_review.history_commands import read_agreement, read_places, record_ruling, record_scoring
from larv_review.reviewer_header import reviewer_header from larv_review.reviewer_header import reviewer_header
from larv_review.round_title import round_title
from project_config.main import title_templates from project_config.main import title_templates
@@ -231,6 +241,7 @@ COMMANDS = {
"places": Command("places", no_arguments, lambda given: printed(read_places(pathlib.Path.home()))), "places": Command("places", no_arguments, lambda given: printed(read_places(pathlib.Path.home()))),
"agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home()))), "agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home()))),
"reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header), "reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header),
"round-title": Command("round-title <pass>", lambda given: len(given) == 1 and given[0] in REVIEWERS, lambda given: with_default_branch(lambda default: printed(round_title(default, given[0], pathlib.Path.home())), stale_ok=True)),
"reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))),
} }
SHAPES = " | ".join(command.shape for command in COMMANDS.values()) SHAPES = " | ".join(command.shape for command in COMMANDS.values())
+5 -5
View File
@@ -5,12 +5,12 @@ import pathlib
from git_cli.git_repo import branch_titles, git, top from git_cli.git_repo import branch_titles, git, top
from review_rules.round_titles import cap, round_counts from review_rules.round_titles import cap, round_counts
from failure import Failure from failure import Failure
from chunk_preflight.choices import forge_of from forge.commands import forge_of, runner
from record_store.stores import goals_store, local_file, store from record_store.stores import goals_store, local_file, store
from larv_review.history_commands import history_file, places_report from larv_review.history_commands import history_file, places_report
from project_config.main import located, title_templates from project_config.main import located, title_templates
from review_rules.review_folder import made_review_folder from review_rules.review_folder import made_review_folder, rerun_report, round_report
from deploy_release.forge import open_pull, runner from forge.pulls import open_pull
from larv_review.plan_listing import plan_listing from larv_review.plan_listing import plan_listing
from plan_store.stores import store as plan_store from plan_store.stores import store as plan_store
from review_rules.reviewer_context import principles_line, starts_bare from review_rules.reviewer_context import principles_line, starts_bare
@@ -47,11 +47,11 @@ class Launch:
def asked(self) -> pathlib.Path: def asked(self) -> pathlib.Path:
"""The round's report, which asks for the rerun where there is one.""" """The round's report, which asks for the rerun where there is one."""
return self.folder / f"{self.pass_}-round-{self.round_}.md" return round_report(self.folder, self.pass_, self.round_)
def header(self) -> str: def header(self) -> str:
asked = self.asked() asked = self.asked()
report = f"{asked.with_name(asked.stem + '-rerun.md')}, in place of {asked}, which asked for this rerun" if self.rerun else str(asked) report = f"{rerun_report(asked)}, in place of {asked}, which asked for this rerun" if self.rerun else str(asked)
return "\n".join([ return "\n".join([
f"Pass: {self.pass_}, round {self.round_}.", f"Pass: {self.pass_}, round {self.round_}.",
f"PR: {self.pull}.", f"PR: {self.pull}.",
+27
View File
@@ -0,0 +1,27 @@
"""round-title: print the opening of a round commit's title, counted from the round's report."""
import pathlib
from git_cli.git_repo import branch_titles, top
from failure import Failure
from review_rules.review_folder import findings_in, review_folder, standing_report
from review_rules.round_titles import round_prefix
from project_config.main import title_templates
from larv_review.reviewer_header import unanswered_round
def round_title(default: str, pass_: str, home: pathlib.Path) -> str | Failure:
"""The title prefix of pass_'s unanswered round, counted from that round's report in the chunk's review folder."""
titles = branch_titles(default)
if isinstance(titles, Failure):
return titles
templates = title_templates(None, home)
if isinstance(templates, Failure):
return templates
round_ = unanswered_round([templates.summary(title) for title in titles], pass_)
if isinstance(round_, Failure):
return round_
worktree = top()
if isinstance(worktree, Failure):
return worktree
findings = findings_in(standing_report(pathlib.Path(review_folder(str(home), worktree)), pass_, round_))
return findings if isinstance(findings, Failure) else round_prefix(pass_, round_, findings)
+17 -1
View File
@@ -1093,7 +1093,7 @@ class LarvReviewTool(unittest.TestCase):
def test_help_and_the_usage_line_list_the_same_commands(self): def test_help_and_the_usage_line_list_the_same_commands(self):
usage = next(line for line in self.run_tool("--help").stdout.splitlines() if line.startswith("usage: larv-review ")) usage = next(line for line in self.run_tool("--help").stdout.splitlines() if line.startswith("usage: larv-review "))
listed = usage.removeprefix("usage: larv-review ").split(" | ") listed = usage.removeprefix("usage: larv-review ").split(" | ")
self.assertEqual([shape.split()[0] for shape in listed], ["review-folder", "ruling-base", "round-count", "needs-scoring-run", "scoring-run-owed", "record-ruling", "prepare-scoring", "record-scoring", "places", "agreement", "reviewer-header", "reviewer-context"]) self.assertEqual([shape.split()[0] for shape in listed], ["review-folder", "ruling-base", "round-count", "needs-scoring-run", "scoring-run-owed", "record-ruling", "prepare-scoring", "record-scoring", "places", "agreement", "reviewer-header", "round-title", "reviewer-context"])
self.assertIn(f"usage: larv-review {' | '.join(listed)}", self.run_tool().stderr) self.assertIn(f"usage: larv-review {' | '.join(listed)}", self.run_tool().stderr)
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self): def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
@@ -1173,6 +1173,22 @@ class LarvReviewTool(unittest.TestCase):
self.assertIn(f"Report: write it to {folder}/prose-round-2-rerun.md, in place of {folder}/prose-round-2.md, which asked for this rerun.", lines) self.assertIn(f"Report: write it to {folder}/prose-round-2-rerun.md, in place of {folder}/prose-round-2.md, which asked for this rerun.", lines)
self.assertFalse(any(line.startswith("Places:") for line in lines), "only architecture and stability take the places") self.assertFalse(any(line.startswith("Places:") for line in lines), "only architecture and stability take the places")
def test_round_title_counts_the_unanswered_rounds_report_and_names_one_that_is_missing(self):
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
folder.mkdir(parents=True)
(folder / "prose-round-1.md").write_text("BLOCK\n\n### 🔴 [misread] `a.md:1`: wrong\n\n### 🟡 `b.md:2`: worse\n\n### 🟢 `c.md:3`: nit\n")
ran = self.run_tool("round-title", "prose")
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "Answer prose round 1: 1 🔴, 1 🟡 (1 misread);\n", ""))
self.commit("Answer prose round 1: 1 🔴, 1 🟡 (1 misread); fix")
missing = self.run_tool("round-title", "prose")
self.assertEqual((missing.returncode, missing.stdout), (1, ""))
self.assertIn(f"no report at {folder}/prose-round-2.md", missing.stderr)
(folder / "prose-round-2.md").write_text("BLOCK\n\n### 🟡 a\n\nRerun one rung up\n")
(folder / "prose-round-2-rerun.md").write_text("APPROVE\n")
self.assertEqual(self.run_tool("round-title", "prose").stdout, "Answer prose round 2: 0 🔴, 0 🟡 (0 misread);\n", "the rerun's report stands in place of the one that asked")
for given in (["security"], ["Prose"], ["prose", "2"], []):
self.assertEqual(self.run_tool("round-title", *given).returncode, 1, given)
def test_reviewer_header_refuses_a_pass_at_its_cap_and_a_pass_no_agent_reviews(self): def test_reviewer_header_refuses_a_pass_at_its_cap_and_a_pass_no_agent_reviews(self):
self.commit("Answer stability round 1: a") self.commit("Answer stability round 1: a")
self.commit("Answer stability round 2: b") self.commit("Answer stability round 2: b")
+24 -8
View File
@@ -11,6 +11,7 @@ from loop_claude import escalation_mark
from failure import Failure from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from claude_code.transcript import human_answers from claude_code.transcript import human_answers
from transcript_archive.judge_run import JudgeRun
from loop_claude.quotes import plain, verbatim from loop_claude.quotes import plain, verbatim
from loop_claude.cycle.retry import retried from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung from model_routing.ladder import Rung
@@ -64,6 +65,10 @@ FINISHED_RULES = (
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded." "continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
) )
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES)) JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
# Open the task and the transcript in the prompt; the premises and the records come before the task, the rules after the transcript.
# judge_replay.archived_prompt splits each archived prompt on them, so rewording one makes every run archived before it replay as failed.
TASK_HEADING = "The task the worker was given:\n"
TRANSCRIPT_HEADING = "What the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -94,10 +99,15 @@ JUDGE_SCHEMA = {
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Rejected(Failure): class Rejected(Failure):
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json, and cost is what the run cost in dollars, 0 where its reply records none.""" """A judge reply loop-claude rejected: reason says why, run holds the prompt and the reply, and cost is what the run cost in dollars, 0 where its reply records none."""
reply: str run: JudgeRun
cost: float = 0.0 cost: float = 0.0
@property
def reply(self) -> str:
"""The reply as json."""
return json.dumps(self.run.reply, ensure_ascii=False)
class Grounds(typing.NamedTuple): class Grounds(typing.NamedTuple):
"""The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order.""" """The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order."""
@@ -155,6 +165,12 @@ def judge_once(root: str, brief: Brief, rung: Rung, effects: Effects) -> Verdict
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(brief.entries)) return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(brief.entries))
def judge_archived(root: str, prompt: str, grounds: Grounds, entries_read: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on a prompt the archive kept from an earlier run, as judge-replay replays it: the judge reads what it read then, and its quotes are checked against grounds, which judge_replay.archived_prompt makes from that prompt in place of the records of today."""
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, entries_read)
def judge_args(rung: Rung) -> list[str]: def judge_args(rung: Rung) -> list[str]:
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output. # --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
# No tools, so the verdict rests on the transcript grounded() checks it against. # No tools, so the verdict rests on the transcript grounded() checks it against.
@@ -172,14 +188,14 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
return reply return reply
output = structured_output(reply) output = structured_output(reply)
verdict = verdict_from(output) verdict = verdict_from(output)
replied = json.dumps(reply, ensure_ascii=False) run = JudgeRun(prompt, reply)
cost = cost_of(reply) cost = cost_of(reply)
if isinstance(verdict, Failure): if isinstance(verdict, Failure):
return Rejected(verdict.reason, replied, cost) return Rejected(verdict.reason, run, cost)
checked = quotes_checked(verdict, grounds) checked = quotes_checked(verdict, grounds)
if isinstance(checked, Failure): if isinstance(checked, Failure):
return Rejected(checked.reason, replied, cost) return Rejected(checked.reason, run, cost)
return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed))) return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed), run))
def reversal_of(output: object, typed: tuple[str, ...]) -> str: def reversal_of(output: object, typed: tuple[str, ...]) -> str:
@@ -255,8 +271,8 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
head = ( head = (
f"From the goals file, {brief.premises}\n\n" f"From the goals file, {brief.premises}\n\n"
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{brief.records or 'none'}\n\n" f"The records: the project's working rules and decisions, then the human's rules for every project:\n{brief.records or 'none'}\n\n"
f"The task the worker was given:\n{brief.task}\n\n" f"{TASK_HEADING}{brief.task}\n\n"
"What the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n" f"{TRANSCRIPT_HEADING}"
) )
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2) room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
transcript = escalation_mark.transcript(brief.entries, brief.escalated_at, typed_answer) transcript = escalation_mark.transcript(brief.entries, brief.escalated_at, typed_answer)
+34 -34
View File
@@ -5,8 +5,8 @@ from model_routing.route import ESCALATION_MARKER, Route
from loop_claude.routing import escalation_rungs from loop_claude.routing import escalation_rungs
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS
from model_routing.ladder import Ladder, Rung
from text_files.markdown_text import listed, quoted from text_files.markdown_text import listed, quoted
from model_routing.ladder import ProjectRung, Rung
from claude_code.transcript import Typed from claude_code.transcript import Typed
# Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises. # Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises.
@@ -29,17 +29,17 @@ NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CH
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it'
def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung | None, facts: str) -> str: def fresh(task: str, premises: str, route: Route, project: ProjectRung | None, facts: str) -> str:
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project)) 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 "" 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} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan 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 the goals file, {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 plan 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 the goals file, {premises}"
def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str: def routed_by(route: Route, project: ProjectRung | None) -> str:
return " ".join(( return " ".join((
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.", f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
*rung_sentences(route, ladder, project), *rung_sentences(route, project),
)) ))
@@ -63,12 +63,12 @@ def preflight_failed(reason: str) -> str:
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}" return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
def review_launches(route: Route, ladder: Ladder, project: Rung | None) -> list[str]: def review_launches(route: Route, project: ProjectRung | None) -> list[str]:
"""The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder.""" """The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder."""
if project is None: if project is None:
return [] return []
choice = chosen(ladder, project, route) choice = chosen(project, route)
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, ladder, project), *taken_in_launches(choice), *markdown_launch(choice)] 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]: def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
@@ -76,9 +76,9 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else [] return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]: def planning_launch(route: Route, project: ProjectRung) -> list[str]:
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`""" """Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else [] return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.rung.model} <L>` prints."] if project.ladder.position(route.rung) < project.ladder.position(project.rung) else []
def markdown_launch(choice: ReviewChoice) -> list[str]: def markdown_launch(choice: ReviewChoice) -> list[str]:
@@ -90,7 +90,7 @@ def markdown_launch(choice: ReviewChoice) -> list[str]:
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()}."] 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]: def shared_launches(choice: ReviewChoice, route: Route, project: ProjectRung) -> list[str]:
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on. """A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
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.` 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.`
@@ -114,28 +114,28 @@ def taken_in_launches(choice: ReviewChoice) -> list[str]:
return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."] return [f"Where an item you take into the chunk has an E + I of {min(choice.higher.values())} or more, launch {EACH_REVIEWER} with the Agent tool set to {listed(picks, 'and')}."]
def rung_named(rung: Rung, route: Route, project: Rung) -> str: def rung_named(rung: Rung, route: Route, project: ProjectRung) -> str:
"""Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in.""" """Why a review runs on rung: it is the project's, or the one the route's reviewed_on E + I picks, the item's or one taken in."""
if rung == project: if rung == project.rung:
return "the project's rung" return "the project's rung"
if route.escape_and_impact_taken_in: if route.escape_and_impact_taken_in:
return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk" return f"the rung picked by an item of E + I {route.escape_and_impact_taken_in} taken into the chunk"
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks" return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
def escalation(route: Route, ladder: Ladder, project: Rung | None) -> list[str]: def escalation(route: Route, project: ProjectRung | 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. """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. 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 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>`.` For a worker one rung above the project's, routed by item 3 of L 3, 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.rungs[:-1]: if project is None or route.rung not in project.ladder.rungs[:-1]:
return [] return []
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number." marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(ladder, project, route)] rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
if not rungs: if not rungs:
return [ return [
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{ladder.climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.", f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{project.ladder.climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
marked, marked,
] ]
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else "" further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
@@ -146,16 +146,16 @@ def escalation(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
] ]
def reruns(route: Route, ladder: Ladder, project: Rung | None) -> list[str]: def reruns(route: Route, project: ProjectRung | 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. """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 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>`.` 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.rungs: if project is None or route.rung not in project.ladder.rungs:
return [] return []
choice = chosen(ladder, project, route) choice = chosen(project, route)
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat)) launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
rerun = {name: ladder.climbed(rung, 1) for name, rung in launched if rung != ladder.rungs[-1]} rerun = {name: project.ladder.climbed(rung, 1) for name, rung in launched if rung != project.ladder.rungs[-1]}
if not rerun: if not rerun:
return [] return []
if len(set(rerun.values())) == 1: if len(set(rerun.values())) == 1:
@@ -163,31 +163,31 @@ def reruns(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."] return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
def resumed(unfinished_evidence: str, route: Route, ladder: Ladder, project: Rung | None) -> str: def resumed(unfinished_evidence: str, route: Route, project: ProjectRung | 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.""" """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 "" 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 " " 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}. {NAME_THE_ITEMS}{on}{rungs_held(route, ladder, 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, ladder: Ladder, project: Rung | None) -> list[str]: def rung_sentences(route: Route, project: ProjectRung | None) -> list[str]:
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run.""" """The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
return [*review_launches(route, ladder, project), *escalation(route, ladder, project), *reruns(route, ladder, project)] return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
def rungs_held(route: Route, ladder: Ladder, project: Rung | None) -> str: def rungs_held(route: Route, project: ProjectRung | None) -> str:
"""rung_sentences, each after a space, to follow the sentence a prompt ends on.""" """rung_sentences, each after a space, to follow the sentence a prompt ends on."""
return "".join(f" {sentence}" for sentence in rung_sentences(route, ladder, project)) return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
def answered(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str: def answered(question: str, answer: str, route: Route, project: ProjectRung | None, stepped: bool) -> str:
"""stepped is whether the answer's ruling stepped the worker up.""" """stepped is whether the answer's ruling stepped the worker up."""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, ladder, project, stepped)}" return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
def typed(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str: def typed(question: str, answer: str, route: Route, project: ProjectRung | None, stepped: bool) -> str:
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" """The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, ladder, project, stepped)}" return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds. # Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
@@ -203,9 +203,9 @@ def typed_answer(prompt: str) -> Typed | None:
return Typed(rest, answer) return Typed(rest, answer)
def stepped_to(route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str: def stepped_to(route: Route, project: ProjectRung | None, stepped: bool) -> str:
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise.""" """The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, ladder, project)}" if stepped else "" return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str: def past_the_cap(question: str, answer: str, cap: int) -> str:
+25 -30
View File
@@ -13,11 +13,12 @@ from claude_code.entries import Entry
from failure import Failure from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
from loop_claude.routing import judge_rung, next_route, step_up, StepUp from transcript_archive.judge_run import JudgeRun
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import last_spent from transcript_archive.read import last_spent
from loop_claude.routing import next_route, step_up, StepUp
from transcript_archive import outcomes from transcript_archive import outcomes
from plan_store.plans import Plan from plan_store.plans import Plan
from model_routing.ladder import ProjectRung, Rung
from loop_claude.cycle import prompts from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried from loop_claude.cycle.retry import retried
@@ -39,12 +40,11 @@ class Cycle:
effects: Effects effects: Effects
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began. # What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
facts: str facts: str
judge_model: str # The rung routing.judge_rung picks for the project's judge model.
# The project's routing ladder, as model_routing/ladder_file.py read it when the cycle started. judge: Rung
ladder: Ladder
premises: str premises: str
# The project's rung; None for a model off the ladder. # The project's rung on the ladder that model_routing/ladder_file.py read as the cycle started; None for a model off the ladder.
project: Rung | None project: ProjectRung | None
project_archive: pathlib.Path project_archive: pathlib.Path
records: str records: str
root: str root: str
@@ -84,7 +84,7 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None: def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle.""" """The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle."""
return step_up(cycle.route, next_route(cycle.ladder, cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None return step_up(cycle.route, next_route(cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
@@ -98,14 +98,9 @@ def archived_stop(project_archive: pathlib.Path, session: Session, task: str, ro
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop 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: def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects, judge_run: JudgeRun | None = None) -> 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.""" """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)) return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run)
def judge_of(cycle: Cycle) -> Rung:
"""The judge's rung, which the archive names beside each verdict."""
return judge_rung(cycle.ladder, cycle.judge_model)
def step(cycle: Cycle, state: Active) -> Event | Stop: def step(cycle: Cycle, state: Active) -> Event | Stop:
@@ -143,12 +138,12 @@ def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]: def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
if isinstance(answered, QuotedAnswer): if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
if isinstance(answered, TypedAnswer): if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
if session_open(cycle.session): if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.ladder, cycle.project), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.ladder, cycle.project, cycle.facts), resume=False) return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop: def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop:
@@ -156,7 +151,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
entries = read_transcript(transcript_path) entries = read_transcript(transcript_path)
if isinstance(entries, Failure): if isinstance(entries, Failure):
return Stop(1, entries.reason) 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)) verdict = judge(cycle.root, Brief(cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at), cycle.judge, cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
if isinstance(verdict, Stop): if isinstance(verdict, Stop):
return verdict return verdict
if not isinstance(verdict, Finished): if not isinstance(verdict, Finished):
@@ -167,7 +162,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
if isinstance(annotation, Failure): if isinstance(annotation, Failure):
return Stop(1, annotation.reason) return Stop(1, annotation.reason)
stepped = ruling_step_up(cycle, verdict) stepped = ruling_step_up(cycle, verdict)
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped): if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped, verdict.judged.run):
return Stop(1, failure.reason) return Stop(1, failure.reason)
return Ruled(verdict, stepped.after if stepped else None) return Ruled(verdict, stepped.after if stepped else None)
@@ -180,20 +175,20 @@ def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judg
subagents = spend.subagents(transcript_path) subagents = spend.subagents(transcript_path)
if isinstance(subagents, Failure): if isinstance(subagents, Failure):
return subagents return subagents
spent = spend.spent(since, entries, subagents, judge_of(cycle).model, judged.tokens) spent = spend.spent(since, entries, subagents, cycle.judge.model, judged.tokens)
return outcomes.Annotation(cycle.config, outcomes.spent_block(since, spent), judged.reversed) return outcomes.Annotation(cycle.config, outcomes.spent_block(since, spent), judged.reversed)
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> str: def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> 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 the premises or the records.""" """The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from the premises or the records."""
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers): if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
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.judged.cost, annotation=annotation) return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(cycle.judge), worker=cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation, judge_run=ruling.judged.run)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, annotation) return outcomes.interrupted(question_for(ruling), ruling.evidence, str(cycle.judge), ruling.escalation, cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation, judge_run=ruling.judged.run)
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None: 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.""" """Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects): if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(cycle.judge), judge_cost=rejected.cost, judge_run=rejected.run), cycle.effects, rejected.run):
return Stop(1, unkept.reason) return Stop(1, unkept.reason)
return None return None
@@ -211,9 +206,9 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
return HumanTyped(TypedAnswer(ruling.question, answer)) return HumanTyped(TypedAnswer(ruling.question, answer))
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None: def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None, judge_run: JudgeRun | None) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned.""" """Archives the outcome of a ruling and the judge run that gave it, then the step-up it made, if it made one. The first failure is returned."""
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects): if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects, judge_run):
return failure return failure
return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects) return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects)
@@ -236,8 +231,8 @@ def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) ->
annotation = entries if isinstance(entries, Failure) else annotation_of(cycle, transcript_path, entries, verdict.judged) annotation = entries if isinstance(entries, Failure) else annotation_of(cycle, transcript_path, entries, verdict.judged)
if isinstance(annotation, Failure): if isinstance(annotation, Failure):
return Stop(1, annotation.reason) return Stop(1, annotation.reason)
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, annotation) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, annotation) outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(cycle.judge), judge_cost=verdict.judged.cost, annotation=annotation, judge_run=verdict.judged.run) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(cycle.judge), verdict.escalation, judge_cost=verdict.judged.cost, annotation=annotation, judge_run=verdict.judged.run)
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects): if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects, verdict.judged.run):
return Stop(1, failure.reason) return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)): if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason) return Stop(1, failure.reason)
+4 -4
View File
@@ -10,11 +10,11 @@ from loop_claude.routing import first_route, kept, routed_item
from loop_claude.loop.chunk_windows import held_beside, item_of from loop_claude.loop.chunk_windows import held_beside, item_of
from chunk_preflight.main import ITEM from chunk_preflight.main import ITEM
from plan.todo_table import Item from plan.todo_table import Item
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import latest_worker from transcript_archive.read import latest_worker
from project_config.main import located from project_config.main import located
from loop_claude.loop.this_loop import Loop from loop_claude.loop.this_loop import Loop
from plan_store.plans import Plan from plan_store.plans import Plan
from model_routing.ladder import ProjectRung, Rung
from loop_claude.cycle import prompts from loop_claude.cycle import prompts
from model_routing.route import Route, route_from from model_routing.route import Route, route_from
from claude_code.session import session_open, transcript_file from claude_code.session import session_open, transcript_file
@@ -31,15 +31,15 @@ def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Fail
return plan return plan
def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route: def routed(route: Route | None, project: ProjectRung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung on ladder, and model the project's model. """The route the cycle runs on. project is the project's rung, and model the project's model.
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh. Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
""" """
if project is None: if project is None:
return Route(Rung(model)) return Route(Rung(model))
route = route or archived() route = route or archived()
return route if route and kept(route, ladder, project) else first_route(ladder, project, item()) return route if route and kept(route, project) else first_route(project, item())
def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None: def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
+5 -5
View File
@@ -4,20 +4,20 @@ import pathlib
from loop_claude.cycle.run import archived_step, archived_stop, Concluded from loop_claude.cycle.run import archived_step, archived_stop, Concluded
from loop_claude.verdicts import Finished from loop_claude.verdicts import Finished
from model_routing.ladder import Ladder, Rung
from loop_claude.loop.this_loop import Loop from loop_claude.loop.this_loop import Loop
from loop_claude.loop.reload import LoopRun from loop_claude.loop.reload import LoopRun
from loop_claude.stop import needs_human, Stop from loop_claude.stop import needs_human, Stop
from loop_claude.routing import next_route, step_up from loop_claude.routing import next_route, step_up
from model_routing.ladder import ProjectRung
from claude_code.session import 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. # 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 UNFINISHED_LIMIT = 6
def closed_cycle(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop: def closed_cycle(loop_run: LoopRun, project: ProjectRung | 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.""" """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, ladder, project, concluded) 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. # A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
if after.route is None: if after.route is None:
return after return after
@@ -38,10 +38,10 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles") return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
def after_verdict(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded) -> LoopRun: def after_verdict(loop_run: LoopRun, project: ProjectRung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. 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, and the evidence the judge gave for the verdict; and counts the verdict.""" """The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. 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, and the evidence the judge gave for the verdict; and counts the verdict."""
verdict = concluded.verdict verdict = concluded.verdict
if isinstance(verdict, Finished): if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0) return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
route = next_route(ladder, project, concluded.route, verdict) route = next_route(project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1) return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
+5 -4
View File
@@ -16,6 +16,7 @@ from loop_claude.verdicts import Finished
from loop_claude.project.model_choice import get_or_ask_models from loop_claude.project.model_choice import get_or_ask_models
from git_cli.git_repo import Git from git_cli.git_repo import Git
from loop_claude.loop.usage import HELP from loop_claude.loop.usage import HELP
from loop_claude.routing import judge_rung
from loop_claude.loop.this_loop import Loop from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths from loop_state.paths import Paths
from transcript_archive.project_key import project_key from transcript_archive.project_key import project_key
@@ -69,12 +70,12 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
concluded = run_cycle(cycle) concluded = run_cycle(cycle)
if isinstance(concluded, Stop): if isinstance(concluded, Stop):
return concluded return concluded
closed = closed_cycle(loop_run, cycle.ladder, cycle.project, concluded, cycle.project_archive, loop) closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
if isinstance(closed, Stop): if isinstance(closed, Stop):
return closed return closed
loop_run = closed loop_run = closed
# Off the ladder the worker runs on the project's model itself, which its route names. # 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), cycle.project or cycle.route.rung, loop): if stop := check_routing(archive_root(paths.home, env), cycle.project.rung if cycle.project else cycle.route.rung, loop):
return stop return stop
if isinstance(concluded.verdict, Finished): if isinstance(concluded.verdict, Finished):
return handed_on(loop_run, loop) return handed_on(loop_run, loop)
@@ -124,11 +125,11 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
# After the reads above, so a loop that stops on one makes no worktree. # After the reads above, so a loop that stops on one makes no worktree.
facts, default = chunk_start(loop) facts, default = chunk_start(loop)
project = ladder.project_rung(models.worker) project = ladder.project_rung(models.worker)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects)) route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects))
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True) say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
if ladder_file != SHIPPED: if ladder_file != SHIPPED:
say(own_ladder(ladder_file, models.worker, project is None), loop.effects) say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge=judge_rung(ladder, models.judge), premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str: def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
+32 -30
View File
@@ -34,7 +34,7 @@ from loop_claude import escalation_mark
from failure import Failure from failure import Failure
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from plan.todo_table import Item, NoItemsTable from plan.todo_table import Item, NoItemsTable
from model_routing.ladder import Ladder, Rung from model_routing.ladder import Ladder, ProjectRung, Rung
from plan_store.plans import Plan from plan_store.plans import Plan
from model_routing.route import Route from model_routing.route import Route
@@ -59,42 +59,43 @@ def routed_item(plan: Plan | Failure, cut: LastCut, item_id: int | None = None)
return takes if takes and takes.likelihood and takes.escape_and_impact else None return takes if takes and takes.likelihood and takes.escape_and_impact else None
def first_route(ladder: Ladder, project: Rung, item: Item | None) -> Route: def first_route(project: ProjectRung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks on ladder from the project's rung, or the project's rung without an item.""" """The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
if item is None: if item is None:
return Route(project) return Route(project.rung)
return Route(ladder.worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact) return Route(project.worker_rung(item.likelihood), item.id, item.likelihood, item.escape_and_impact)
def kept(route: Route, ladder: Ladder, project: Rung) -> bool: def kept(route: Route, project: ProjectRung) -> bool:
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung.""" """Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
return floor_rung(ladder, project, route) == route.rung return floor_rung(project, route) == route.rung
def item_rung(ladder: Ladder, project: Rung, route: Route) -> Rung: def item_rung(project: ProjectRung, route: Route) -> Rung:
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's.""" """The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
return ladder.worker_rung(project, route.likelihood) if route.item else project return project.worker_rung(route.likelihood) if route.item else project.rung
def floor_rung(ladder: Ladder, project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung: def floor_rung(project: ProjectRung, route: Route, likelihood_taken_in: int = 0) -> Rung:
"""The lowest rung the worker may run on: the route's own, raised to item_rung where it is lower or off the ladder, and to the rung likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, 0 for none.""" """The lowest rung the worker may run on: the route's own, raised to item_rung where it is lower or off the ladder, and to the rung likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, 0 for none."""
floor = ladder.highest(route.rung, item_rung(ladder, project, route)) floor = project.ladder.highest(route.rung, item_rung(project, route))
return ladder.highest(floor, ladder.worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor return project.ladder.highest(floor, project.worker_rung(likelihood_taken_in)) if likelihood_taken_in else floor
def escalation_rungs(ladder: Ladder, project: Rung, route: Route) -> tuple[Rung, ...]: def escalation_rungs(project: ProjectRung, route: Route) -> tuple[Rung, ...]:
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder.""" """The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
ladder = project.ladder
if route.rung not in ladder.rungs: if route.rung not in ladder.rungs:
return () return ()
return ladder.rungs[ladder.position(route.rung) + 1:ladder.position(escalation_cap(ladder, project, route)) + 1] return ladder.rungs[ladder.position(route.rung) + 1:ladder.position(escalation_cap(project, route)) + 1]
def escalation_cap(ladder: Ladder, project: Rung, route: Route) -> Rung: def escalation_cap(project: ProjectRung, route: Route) -> Rung:
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`. """The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it. It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
""" """
return ladder.climbed(item_rung(ladder, project, route), ESCALATION_CAP) return project.ladder.climbed(item_rung(project, route), ESCALATION_CAP)
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -104,31 +105,32 @@ class StepUp:
after: Route after: Route
def next_route(ladder: Ladder, project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route: def next_route(project: ProjectRung | 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.""" """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: if project is None:
return route return route
if isinstance(verdict, Unfinished): if isinstance(verdict, Unfinished):
return unfinished_route(ladder, project, route, verdict) return unfinished_route(project, route, verdict)
return escalated_route(ladder, project, route, verdict) return escalated_route(project, route, verdict)
def unfinished_route(ladder: Ladder, project: Rung, route: Route, verdict: Unfinished) -> Route: def unfinished_route(project: ProjectRung, 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 route after an unfinished verdict, as the module docstring's table says.
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. 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; the mark moves only where the verdict carries an escalation. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
""" """
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
mark = escalation_mark.moved_to(verdict) mark = escalation_mark.moved_to(verdict)
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood) escalates = mark is not None and below_cap(project, route, floor)
counted = route.unfinished + 1 counted = route.unfinished + 1
if steps(counted, mark is not None and below_cap(ladder, project, route, floor)): if steps(counted, escalates):
after = one_rung_up(ladder, route, floor, route.escalated_at if mark is None else mark) after = one_rung_up(project.ladder, route, floor, route.escalated_at if mark is None else mark)
else: else:
after = dataclasses.replace(route, rung=floor, unfinished=counted) after = dataclasses.replace(route, rung=floor, unfinished=counted)
return after.taking_in(verdict.taken_in.highest_escape_and_impact) return after.taking_in(verdict.taken_in.highest_escape_and_impact)
def escalated_route(ladder: Ladder, project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route: def escalated_route(project: ProjectRung, 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. """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. 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.
@@ -136,8 +138,8 @@ def escalated_route(ladder: Ladder, project: Rung, route: Route, verdict: Interr
mark = escalation_mark.moved_to(verdict) mark = escalation_mark.moved_to(verdict)
if mark is None: if mark is None:
return route return route
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood) floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
return one_rung_up(ladder, route, floor, mark) if below_cap(ladder, project, route, floor) else dataclasses.replace(route, rung=floor) return one_rung_up(project.ladder, route, floor, mark) if below_cap(project, route, floor) else dataclasses.replace(route, rung=floor)
def steps(counted: int, escalates: bool) -> bool: def steps(counted: int, escalates: bool) -> bool:
@@ -145,9 +147,9 @@ def steps(counted: int, escalates: bool) -> bool:
return counted >= UNFINISHED_PER_STEP or escalates return counted >= UNFINISHED_PER_STEP or escalates
def below_cap(ladder: Ladder, project: Rung, route: Route, floor: Rung) -> bool: def below_cap(project: ProjectRung, route: Route, floor: Rung) -> bool:
"""Whether an escalation from floor may step the rung: floor lies below escalation_cap.""" """Whether an escalation from floor may step the rung: floor lies below escalation_cap."""
return ladder.position(floor) < ladder.position(escalation_cap(ladder, project, route)) return project.ladder.position(floor) < project.ladder.position(escalation_cap(project, route))
def step_up(before: Route, after: Route) -> StepUp | None: def step_up(before: Route, after: Route) -> StepUp | None:
+17 -15
View File
@@ -150,7 +150,7 @@ if os.path.basename(sys.argv[0]) == "loop-claude":
""" """
PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n" PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
# Item 4's L of 4 steps one rung up from the project's. # Item 4's L of 4 steps two rungs up from the project's.
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" 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. # Item 4's L of 2 steps one rung down.
CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |") CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |")
@@ -342,7 +342,9 @@ class Checkout:
for archived in (copy, kept): for archived in (copy, kept):
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE) stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
outcomes[copy.read_text()] = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE) configured = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE)
# The judge's run is named by the hash of its prompt and reply, which test_loop_claude.py checks.
outcomes[copy.read_text()] = re.sub(r"^Judge run: judge/[0-9a-f]{64}\.json\n", "", configured, flags=re.MULTILINE)
return outcomes return outcomes
@@ -495,15 +497,15 @@ class Cycles(unittest.TestCase):
("claude-sonnet-5-5", "high"), ("claude-sonnet-5-5", "high"),
("claude-sonnet-5-5", "high"), ("claude-sonnet-5-5", "high"),
("claude-opus-5-5", "medium"), ("claude-opus-5-5", "medium"),
("claude-fable-5-2", "low"), ("claude-fable-5-2", "medium"),
("claude-sonnet-5-5", "high"), ("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.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p")) self.assertIn("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")) 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()) 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\nConfig: <config>\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: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\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": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nConfig: <config>\nJudge: judge-model\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\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self): def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -574,14 +576,14 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.code, 130) self.assertEqual(run.code, 130)
workers = [call for call in run.calls if call["role"] == "worker"] workers = [call for call in run.calls if call["role"] == "worker"]
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in workers], [ self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in workers], [
("claude-fable-5-2", "low"),
("claude-fable-5-2", "medium"), ("claude-fable-5-2", "medium"),
("claude-opus-5-5", "xhigh"),
("claude-opus-5-5", "xhigh"),
("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()) 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\nConfig: <config>\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\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "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\nConfig: <config>\nJudge: judge-model\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\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "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): def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -595,11 +597,11 @@ class Cycles(unittest.TestCase):
], terminal_input="/talk\n", before_typing=ANSWERING) ], terminal_input="/talk\n", before_typing=ANSWERING)
self.assertEqual(run.code, 130) self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) 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-fable-5-2", "low"), ("claude-fable-5-2", "medium"), ("claude-fable-5-2", "medium")]) self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-fable-5-2", "medium"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
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.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.assertNotIn("at max effort", "".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\nConfig: <config>\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)) 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\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "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))
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_on_it_and_its_judge_on_the_models_highest(self): def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_on_it_and_its_judge_on_the_models_highest(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -638,12 +640,12 @@ class Cycles(unittest.TestCase):
checkout.commit_plan(TODO) checkout.commit_plan(TODO)
run = checkout.run([worker(), judge(), worker(), judge()]) run = checkout.run([worker(), judge(), worker(), judge()])
self.assertEqual(run.code, 130) self.assertEqual(run.code, 130)
self.assertEqual((argument(run.calls[-1], "--model"), argument(run.calls[-1], "--effort")), ("claude-fable-5-2", "medium")) self.assertEqual((argument(run.calls[-1], "--model"), argument(run.calls[-1], "--effort")), ("claude-opus-5-5", "xhigh"))
checkout.git("rm", "--quiet", "todo.md") checkout.git("rm", "--quiet", "todo.md")
checkout.git("commit", "--quiet", "-m", "drop the plan") checkout.git("commit", "--quiet", "-m", "drop the plan")
run = checkout.run([worker()]) run = checkout.run([worker()])
self.assertIsNotNone(argument(run.calls[0], "--resume")) self.assertIsNotNone(argument(run.calls[0], "--resume"))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium")) self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh"))
def test_a_second_window_of_the_project_runs_its_own_session_and_leaves_the_first_ones_open_chunk_alone(self): def test_a_second_window_of_the_project_runs_its_own_session_and_leaves_the_first_ones_open_chunk_alone(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -697,7 +699,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
self.assertEqual(run.sleeps, [60, 60]) self.assertEqual(run.sleeps, [60, 60])
self.assertIn("retrying the judge in a minute: judge down", run.stderr) self.assertIn("retrying the judge in a minute: judge down", run.stderr)
self.assertIn("retrying the judge in a minute: the judge printed no json reply; it printed: nothing\n", run.stderr) self.assertIn("retrying the judge in a minute: the judge printed no json reply; its last line was: nothing\n", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string') self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string')
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self): def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
+169 -133
View File
@@ -38,10 +38,10 @@ from transcript_archive import outcomes, write
from loop_state import paths from loop_state import paths
from plan_store.todo_md import plan_of from plan_store.todo_md import plan_of
from transcript_archive.location import project_archive from transcript_archive.location import project_archive
from model_routing.ladder import ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing from loop_claude import routing
from model_routing.ladder import Rung
from loop_claude.stop import Stop from loop_claude.stop import Stop
from loop_claude import tmux from loop_claude import tmux
from claude_code.tokens import Tokens, tokens_of from claude_code.tokens import Tokens, tokens_of
@@ -51,6 +51,7 @@ from loop_claude.cycle.judge import verdict_from
# How the archive records a worker that runs off the ladder. # How the archive records a worker that runs off the ladder.
LADDER = read_ladder(SHIPPED) LADDER = read_ladder(SHIPPED)
OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium"))
OFF_LADDER = '{"model": "worker-model"}' OFF_LADDER = '{"model": "worker-model"}'
# The claude-config release and commit each cycle the tests run is under. # The claude-config release and commit each cycle the tests run is under.
CONFIG = "v0.8.0 (abc123)" CONFIG = "v0.8.0 (abc123)"
@@ -174,6 +175,9 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr) return subprocess.CompletedProcess([], code, stdout, stderr)
JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE)
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""): def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""):
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed} reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed}
return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})})) return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})}))
@@ -286,10 +290,11 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence) return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self): def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md")) """Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them."""
return sorted(JUDGE_RUN_LINE.sub("", path.read_text()) for path in self.archive.glob("*/*.outcomes.md"))
def test_a_finished_chunk_is_archived_and_its_session_deleted(self): def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
@@ -337,7 +342,7 @@ Worker: {OFF_LADDER}
def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self): def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000"}]) self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000"}])
@@ -347,7 +352,7 @@ Worker: {OFF_LADDER}
handle.write(json.dumps(human("the second")) + "\n") handle.write(json.dumps(human("the second")) + "\n")
return 0 return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer])
cycle = dataclasses.replace(self.cycle(fake), project=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
self.assertEqual(fake.terminal_environments, [{**environment, "CLAUDE_CODE_SANDBOXED": "1"} for environment in fake.worker_environments]) self.assertEqual(fake.terminal_environments, [{**environment, "CLAUDE_CODE_SANDBOXED": "1"} for environment in fake.worker_environments])
@@ -383,6 +388,32 @@ Worker: {OFF_LADDER}
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n" f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_archives_each_judge_runs_prompt_and_reply_beside_the_rejection_interrupt_and_verdict_it_gave(self):
rejected, interrupted, finished = ran(json.dumps({"structured_output": {"interrupt": False}})), judged("interrupt", cost=0.25), judged("finished")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[rejected, interrupted, finished], inputs=["Use B."])
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
prompts = [stdin for args, stdin in fake.made("claude")[:3]]
[chunk] = self.archive.iterdir()
kept = "\n".join(path.read_text() for path in chunk.glob("*.outcomes.md"))
named = re.findall(r"^Judge run: (judge/[0-9a-f]{64}\.json)$", kept, re.MULTILINE)
self.assertEqual(len(named), 3, kept)
runs = [json.loads((chunk / name).read_text()) for name in named]
replies = [json.loads(reply.stdout) for reply in (rejected, interrupted, finished)]
self.assertEqual(sorted((found["prompt"], json.dumps(found["reply"])) for found in runs), sorted((prompt, json.dumps(reply)) for prompt, reply in zip(prompts, replies)))
self.assertEqual(sorted(path.name for path in (chunk / "judge").iterdir()), sorted(name.removeprefix("judge/") for name in named))
def test_stops_when_a_judge_run_cannot_be_archived(self):
self.archive.mkdir(parents=True)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
def replace_file(path, data):
return Failure("disk full") if "/judge/" in str(path) else real_replace_file(path, data)
real_replace_file = write.replace_file
with unittest.mock.patch("transcript_archive.write.replace_file", replace_file):
stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop.code, 1)
self.assertRegex(stop.reason, r"^could not archive the transcript: .*/judge/[0-9a-f]{64}\.json: disk full$")
def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self): def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self):
for first, then, inputs in ( for first, then, inputs in (
(judged("interrupt", cost=0.25), judged("finished"), ["Use B."]), (judged("interrupt", cost=0.25), judged("finished"), ["Use B."]),
@@ -396,6 +427,7 @@ Worker: {OFF_LADDER}
run.run_cycle(dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project_archive=pathlib.Path(archive))) run.run_cycle(dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project_archive=pathlib.Path(archive)))
kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md")) kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md"))
self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept) self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept)
self.assertIn("Judge cost: 0.2500\nJudge run: judge/", kept)
def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self): def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self):
for verdict in ("interrupt", "finished"): for verdict in ("interrupt", "finished"):
@@ -523,13 +555,13 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self): def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()): with contextlib.redirect_stdout(io.StringIO()):
concluded = run.run_cycle(cycle) concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
first, resumed = fake.made("stream_claude") first, resumed = fake.made("stream_claude")
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, LADDER, Routing.OPUS)}")) self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, OPUS_PROJECT)}"))
self.assertNotIn("went through", first[first.index("-p") + 1]) self.assertNotIn("went through", first[first.index("-p") + 1])
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n" answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n"
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n" stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
@@ -540,7 +572,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self): def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self):
steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")] steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")]
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed")) self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
kept = "".join(self.archived_outcomes()) kept = "".join(self.archived_outcomes())
@@ -548,17 +580,17 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept) self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept)
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self): def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self):
cycle = dataclasses.replace(self.cycle(FakeEffects()), project=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4)) cycle = dataclasses.replace(self.cycle(FakeEffects()), project=OPUS_PROJECT, route=Route(Routing.ONE_UP, 3, 3, 4))
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)): for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
with self.subTest(ruling=ruling): with self.subTest(ruling=ruling):
self.assertIsNone(run.ruling_step_up(cycle, ruling)) self.assertIsNone(run.ruling_step_up(cycle, ruling))
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.TWO_UP, 3, 3, 4, escalated_at=3))) self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.THREE_UP, 3, 3, 4, escalated_at=3)))
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self): def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)] streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")] rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle) concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.ONE_UP, 179, 2, 5, escalated_at=4)) self.assertEqual(concluded.route, Route(Routing.ONE_UP, 179, 2, 5, escalated_at=4))
@@ -571,7 +603,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)] streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)]
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)] rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)]
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle) concluded = run.run_cycle(cycle)
self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))) self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)))
@@ -595,7 +627,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self): def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."])
cycle = dataclasses.replace(self.cycle(fake), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5))
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
concluded = run.run_cycle(cycle) concluded = run.run_cycle(cycle)
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
@@ -1005,6 +1037,7 @@ class Routing(unittest.TestCase):
ONE_UP = Rung("claude-fable-5-2", "low") ONE_UP = Rung("claude-fable-5-2", "low")
TWO_UP = Rung("claude-fable-5-2", "medium") TWO_UP = Rung("claude-fable-5-2", "medium")
THREE_UP = Rung("claude-opus-5-5", "xhigh") THREE_UP = Rung("claude-opus-5-5", "xhigh")
FOUR_UP = Rung("claude-fable-5-2", "high")
SONNET = Rung("claude-sonnet-5-5", "high") SONNET = Rung("claude-sonnet-5-5", "high")
def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self):
@@ -1034,53 +1067,53 @@ class Routing(unittest.TestCase):
self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3) self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3)
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self): def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
self.assertEqual(routing.first_route(LADDER, self.OPUS, routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5)) self.assertEqual(routing.first_route(OPUS_PROJECT, routed_item(TODO, NO_CUT)), Route(self.TWO_UP, 3, 4, 5))
cheap = routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT) cheap = routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
self.assertEqual(routing.first_route(LADDER, self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5)) self.assertEqual(routing.first_route(OPUS_PROJECT, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
self.assertEqual(routing.first_route(LADDER, self.OPUS, None), Route(self.OPUS)) self.assertEqual(routing.first_route(OPUS_PROJECT, None), Route(self.OPUS))
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self): def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished()) once = routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4), unfinished())
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1)) self.assertEqual(once, Route(self.ONE_UP, 3, 3, 4, unfinished=1))
self.assertEqual(routing.next_route(LADDER, self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4)) self.assertEqual(routing.next_route(OPUS_PROJECT, once, unfinished()), Route(self.TWO_UP, 3, 3, 4))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1]) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1])
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self): def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS), unfinished(4)).rung, self.TWO_UP)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP), unfinished(4)).rung, self.THREE_UP)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.THREE_UP)
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self): def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = Route(self.SONNET, 3, 1, 3, unfinished=1) low = Route(self.SONNET, 3, 1, 3, unfinished=1)
self.assertEqual(routing.next_route(LADDER, self.OPUS, low, unfinished()).rung, self.OPUS) self.assertEqual(routing.next_route(OPUS_PROJECT, low, unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.ONE_UP)
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self): def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.FOUR_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.TWO_UP, 3, 2, 4, unfinished=1))
def test_keeps_the_mark_through_a_step_no_escalation_took(self): def test_keeps_the_mark_through_a_step_no_escalation_took(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.TWO_UP, 3, 3, 4, escalated_at=5))
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self): def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.FOUR_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2))
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self): def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 1, 3, escalated_at=2))
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self): def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1)) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1))
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self): def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
taken = Route(self.OPUS, 3, 3, 4).taking_in(6) taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
@@ -1095,8 +1128,8 @@ class Routing(unittest.TestCase):
self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS)) self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS))
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS) self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self): def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self):
self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), self.THREE_UP) self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), self.THREE_UP)
@@ -1144,17 +1177,17 @@ class Routing(unittest.TestCase):
def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self):
item = routed_item(TODO, NO_CUT) item = routed_item(TODO, NO_CUT)
archived = Route(self.TWO_UP, 3, 4, 5) archived = Route(self.THREE_UP, 3, 4, 5)
def never(): def never():
raise AssertionError("not asked") raise AssertionError("not asked")
self.assertEqual(chunk_start.routed(archived, LADDER, None, "worker-model", never, never), Route(Rung("worker-model"))) self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(chunk_start.routed(archived, LADDER, self.OPUS, "claude-opus-5-5", never, never), archived) self.assertEqual(chunk_start.routed(archived, OPUS_PROJECT, "claude-opus-5-5", never, never), archived)
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived) self.assertEqual(chunk_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5)) self.assertEqual(chunk_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: None, lambda: item), Route(self.TWO_UP, 3, 4, 5))
self.assertEqual(chunk_start.routed(Route(self.SONNET), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) self.assertEqual(chunk_start.routed(Route(self.SONNET), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
cheap = Route(self.SONNET, 4, 2, 3) cheap = Route(self.SONNET, 4, 2, 3)
self.assertEqual(chunk_start.routed(cheap, LADDER, self.OPUS, "claude-opus-5-5", never, never), cheap) self.assertEqual(chunk_start.routed(cheap, OPUS_PROJECT, "claude-opus-5-5", never, never), cheap)
self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
class RouteSources(unittest.TestCase): class RouteSources(unittest.TestCase):
@@ -1559,27 +1592,30 @@ class StartChunks(unittest.TestCase):
class Steps(unittest.TestCase): class Steps(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium") OPUS = Rung("claude-opus-5-5", "medium")
# The rungs an L 3 and an L 4 pick from OPUS.
FABLE_LOW = Rung("claude-fable-5-2", "low")
FABLE_MEDIUM = Rung("claude-fable-5-2", "medium")
def test_a_finished_verdict_clears_the_route_and_the_evidence(self): def test_a_finished_verdict_clears_the_route_and_the_evidence(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS)) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1)) self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self): def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
raised = Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=5) raised = Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=5)
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self): def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
off_ladder = Route(Rung("worker-model")) off_ladder = Route(Rung("worker-model"))
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(close.after_verdict(run_with, LADDER, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) self.assertEqual(close.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2)) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9)) self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2)) self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
with tempfile.TemporaryDirectory() as home: with tempfile.TemporaryDirectory() as home:
@@ -1588,17 +1624,17 @@ class Steps(unittest.TestCase):
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True) transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4) before = Route(self.FABLE_LOW, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened)) after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4)) self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4))
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
close.closed_cycle(after, LADDER, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened)) close.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4)) self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4))
blocked = pathlib.Path(home, "blocked") blocked = pathlib.Path(home, "blocked")
blocked.write_text("") blocked.write_text("")
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened)) stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self): def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self):
@@ -1613,11 +1649,11 @@ class Steps(unittest.TestCase):
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True) transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4) before = Route(self.FABLE_LOW, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened)) close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6))
class ChunkFacts(unittest.TestCase): class ChunkFacts(unittest.TestCase):
@@ -1673,13 +1709,13 @@ class TypedAnswers(unittest.TestCase):
def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self):
route = Route(Rung("worker-model")) route = Route(Rung("worker-model"))
marked = "The human answered your question at loop-claude's terminal:\nB" marked = "The human answered your question at loop-claude's terminal:\nB"
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, LADDER, None, False)) typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False))
self.assertEqual(typed.answer, "Use B.") self.assertEqual(typed.answer, "Use B.")
self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task.")) self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task."))
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, LADDER, None, False)).answer, "Use B.") self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), LADDER, Routing.OPUS, True)).answer, "Use B.") self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.")
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, LADDER, None, False))) self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False)))
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, LADDER, None))) self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None)))
class WorkerArgs(unittest.TestCase): class WorkerArgs(unittest.TestCase):
@@ -1690,24 +1726,24 @@ class WorkerArgs(unittest.TestCase):
FACTS = "- A preflight fact." FACTS = "- A preflight fact."
def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self):
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS) routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed) self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed)
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS) unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)
self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted) self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted)
self.assertNotIn("loop-claude runs you on", unrouted) self.assertNotIn("loop-claude runs you on", unrouted)
def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self):
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS) routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
self.assertIn("item 3's size again", routed) self.assertIn("item 3's size again", routed)
self.assertIn("escalation trigger 1", routed) self.assertIn("escalation trigger 1", routed)
self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed)
self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS)) self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS))
def test_gives_each_fresh_worker_the_reading_rule_once(self): def test_gives_each_fresh_worker_the_reading_rule_once(self):
rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context" rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context"
for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))): for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))):
with self.subTest(route=route): with self.subTest(route=route):
self.assertEqual(prompts.fresh("Do it.", "## Goals", route, LADDER, None, self.FACTS).count(rule), 1) self.assertEqual(prompts.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1)
def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self):
self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact.")) self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact."))
@@ -1718,95 +1754,95 @@ class WorkerArgs(unittest.TestCase):
def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self): def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self):
for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")): for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")):
with self.subTest(facts=facts): with self.subTest(facts=facts):
self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, facts).count("Continue any open draft PR or worktree"), 1) self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1)
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS) below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below) self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS))
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), LADDER, opus, self.FACTS) level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 6), OPUS_PROJECT, self.FACTS)
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level) self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), LADDER, opus, self.FACTS) below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), OPUS_PROJECT, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below) self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), LADDER, opus)) self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), OPUS_PROJECT))
def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8." taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8."
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) self.assertIn(f"item 3's L of 2.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), LADDER, opus)) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 2, 6), OPUS_PROJECT))
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), LADDER, opus)) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), OPUS_PROJECT))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), LADDER, opus)) self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 2, 8), OPUS_PROJECT))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), LADDER, None)) self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), None))
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self): def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), LADDER, opus)) self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 2, 5, escape_and_impact_taken_in=7), OPUS_PROJECT))
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), LADDER, opus)) self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), OPUS_PROJECT))
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus, self.FACTS) above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT, self.FACTS)
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus) stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up) self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus)) self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT))
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), LADDER, None)) self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above) self.assertIn(f"item 3's L of 3.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above)
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS) fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh) self.assertIn("item 3's L of 2. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh)
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus)) self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus)) self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), OPUS_PROJECT))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), LADDER, opus)) self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), LADDER, opus), "one rung below the top still names the rung above") self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;", prompts.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), OPUS_PROJECT), "one rung below the top still names the rung above")
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus), "a worker off the ladder is told no rerun rung") self.assertNotIn("rerun", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT), "a worker off the ladder is told no rerun rung")
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), LADDER, opus)) self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), OPUS_PROJECT))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), LADDER, None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT))
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS)) self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS))
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`." offer = lambda cap: f" 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 `{cap}`."
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer('model fable, effort low')}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus)) self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer('model opus, effort xhigh')}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus)) self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT))
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self): def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium." markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), LADDER, opus, self.FACTS)) self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 7), OPUS_PROJECT, self.FACTS))
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus)) self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT))
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS))
def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self): def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self):
opus = Rung("claude-opus-5-5", "medium") opus = Rung("claude-opus-5-5", "medium")
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`." both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus).endswith(both)) self.assertTrue(prompts.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT).endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus).endswith(both)) self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT).endswith(both))
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both)) self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`.")) self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), LADDER, opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`.")) self.assertTrue(prompts.resumed("", Route(opus, 3, 2, 7), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`.")) self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), LADDER, None)) self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS)) self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS))
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)) self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS))
fable = Rung("claude-fable-5-2", "max") fable = Rung("claude-fable-5-2", "max")
self.assertNotIn("rerun", prompts.resumed("", Route(fable), LADDER, fable)) self.assertNotIn("rerun", prompts.resumed("", Route(fable), ProjectRung(LADDER, fable)))
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), LADDER, None, self.FACTS), resume=False) fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False)
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), LADDER, None), resume=True) resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id)) self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("--session-id", resumed) self.assertNotIn("--session-id", resumed)
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once")) self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
@@ -1913,7 +1949,7 @@ class JudgePrompt(unittest.TestCase):
self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3)) self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3))
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self): def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), LADDER, None, False) typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})] entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1)) _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown) self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
@@ -2053,7 +2089,7 @@ class ChunkItems(unittest.TestCase):
self.assertEqual(chunk_items.named([said(example)]), (297, 298)) self.assertEqual(chunk_items.named([said(example)]), (297, 298))
def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self): def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self):
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), LADDER, None)) self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), None))
def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self): def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self):
prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)") prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)")
@@ -2284,7 +2320,7 @@ class WindowStarts(unittest.TestCase):
fake = FakeEffects(git=["/r\n"]) fake = FakeEffects(git=["/r\n"])
effects, env = fake.effects(), {"TMUX_PANE": "%4"} effects, env = fake.effects(), {"TMUX_PANE": "%4"}
launcher = pathlib.Path("/b/loop-claude") launcher = pathlib.Path("/b/loop-claude")
cycle = unittest.mock.Mock(project="claude-opus-5-5") cycle = unittest.mock.Mock(project=OPUS_PROJECT)
unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished)) unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished)) finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished))
closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")] closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")]
+3
View File
@@ -1,6 +1,7 @@
"""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.""" """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 import dataclasses
from transcript_archive.judge_run import JudgeRun
from claude_code.tokens import Tokens from claude_code.tokens import Tokens
@@ -22,6 +23,8 @@ class Judged:
tokens: Tokens = Tokens() tokens: Tokens = Tokens()
# The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote. # The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote.
reversed: str = "" reversed: str = ""
# The prompt it read and its reply, which the archive keeps beside the verdict. Left out of comparisons and reprs, so that equal verdicts stay equal whatever prompt they came from.
run: JudgeRun | None = dataclasses.field(default=None, compare=False, repr=False)
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
+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 markdown_section import main
sys.exit(main.main(sys.argv[1:]))
View File
+68
View File
@@ -0,0 +1,68 @@
"""Print one section of a markdown file, picked by a fragment of its heading.
usage: markdown-section <file> <fragment>
The section starts at the heading whose text holds the fragment, in any case, and ends before the
next heading of the same or a higher level, so it holds its sub-sections. A heading's text is what
follows its `#`s. A line inside a fenced code block is never a heading.
Where no heading holds the fragment, it fails saying so. Where several headings do, it fails
listing each with its line number and prints no section: pass more of the heading you want.
A heading whose text is the fragment, in any case, is the one picked even where longer headings
hold it too.
To read a record kept outside the checkout, pass the file `project-record open <record>` prints.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
import pathlib
import sys
from failure import Failure
from text_files.markdown_text import fenced_lines, HEADING
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) != 2 or not argv[1].strip():
print("usage: markdown-section <file> <fragment>", file=sys.stderr)
return 2
try:
text = pathlib.Path(argv[0]).read_text()
except (OSError, UnicodeDecodeError) as error:
print(f"markdown-section: {error}", file=sys.stderr)
return 1
found = section(text, argv[1])
if isinstance(found, Failure):
print(f"markdown-section: {found.reason}", file=sys.stderr)
return 1
print(found, end="")
return 0
def headings(text: str) -> list[tuple[int, int, str]]:
"""Each heading of text outside a fenced code block, as its line's index, its level and its text."""
found = []
for index, (line, fenced) in enumerate(fenced_lines(text)):
if not fenced and (heading := HEADING.match(line)):
found.append((index, len(heading.group(1)), heading.group(2)))
return found
def section(text: str, fragment: str) -> str | Failure:
"""The section of text under the heading that fragment picks, or a Failure where no heading holds it or several do."""
found = headings(text)
wanted = fragment.strip().lower()
matching = [heading for heading in found if wanted in heading[2].lower()]
matching = [heading for heading in matching if heading[2].lower() == wanted] or matching
if not matching:
return Failure(f"no heading holds '{fragment}'")
lines = text.splitlines()
if len(matching) > 1:
listed = "\n".join(f"{index + 1}: {lines[index]}" for index, _, _ in matching)
return Failure(f"{len(matching)} headings hold '{fragment}', so use more of one:\n{listed}")
start, level, _ = matching[0]
end = next((index for index, deeper, _ in found if index > start and deeper <= level), None)
return "\n".join(lines[start:end]).rstrip("\n") + "\n"
@@ -0,0 +1,138 @@
import contextlib
import io
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from markdown_section import main
TOOL = pathlib.Path(__file__).resolve().parents[1] / "markdown-section"
DOCUMENT = """# Title
Intro.
## Alpha
Alpha text.
### Alpha detail
Detail text.
## Beta Gamma
Beta text.
```
## Not a heading
```
## Delta
Delta text.
"""
class Section(unittest.TestCase):
def test_a_section_runs_to_the_next_heading_of_its_level_or_a_higher_one(self):
cases = {
"a sub-section stops at a higher level heading": ("alpha detail", "### Alpha detail\n\nDetail text.\n"),
"the text under a heading isn't a heading": ("alpha text", Failure("no heading holds 'alpha text'")),
"the last section runs to the end of the file": ("delta", "## Delta\n\nDelta text.\n"),
"a level one heading holds the rest of the document": ("title", DOCUMENT),
"a fenced line that looks like a heading doesn't end it": ("beta", "## Beta Gamma\n\nBeta text.\n\n```\n## Not a heading\n```\n"),
}
for name, (fragment, expected) in cases.items():
with self.subTest(name):
self.assertEqual(main.section(DOCUMENT, fragment), expected)
def test_the_fragment_matches_any_part_of_the_heading_text_in_any_case(self):
for fragment in ("gamma", "BETA g", " beta gamma "):
with self.subTest(fragment):
self.assertEqual(str(main.section(DOCUMENT, fragment)).splitlines()[0], "## Beta Gamma")
self.assertEqual(main.section(DOCUMENT, "## beta"), Failure("no heading holds '## beta'"))
def test_a_heading_whose_text_is_the_fragment_wins_over_longer_ones(self):
self.assertEqual(main.section(DOCUMENT, "Alpha"), "## Alpha\n\nAlpha text.\n\n### Alpha detail\n\nDetail text.\n")
self.assertEqual(main.section("## Plan\n\na\n\n## Plan b\n", "PLAN"), "## Plan\n\na\n")
def test_several_matching_headings_fail_listing_each_with_its_line(self):
listed = main.section("## Plan one\n\ntext\n\n## Plan two\n", "plan")
self.assertEqual(listed, Failure("2 headings hold 'plan', so use more of one:\n1: ## Plan one\n5: ## Plan two"))
def test_what_counts_as_a_heading_or_a_fence(self):
cases = {
"a hash with no space after it is no heading": ("#hashtag\n\n## Real\n", "hashtag", Failure("no heading holds 'hashtag'")),
"a fence with an info string closes on a bare fence": ("```python\n## In\n```\n## Out\n\ntext\n", "out", "## Out\n\ntext\n"),
"a fence of four backticks holds a line of three": ("````\n```\n## In\n````\n## Out\n", "out", "## Out\n"),
"a tilde fence holds a heading": ("~~~\n## In\n~~~\n## Out\n", "in", Failure("no heading holds 'in'")),
"an indented fence holds a heading": (" ```\n## In\n ```\n", "in", Failure("no heading holds 'in'")),
"an unclosed fence holds the rest": ("## A\n\n```\n## In\n", "a", "## A\n\n```\n## In\n"),
}
for name, (text, fragment, expected) in cases.items():
with self.subTest(name):
self.assertEqual(main.section(text, fragment), expected)
def test_only_blank_lines_are_cut_from_the_end_of_a_section(self):
self.assertEqual(main.section("## A\n\nends in X\n\n\n## B\n", "a"), "## A\n\nends in X\n")
self.assertEqual(main.section("## A\n\ncode \n\n", "a"), "## A\n\ncode \n")
def test_no_heading_is_a_failure(self):
self.assertEqual(main.section(DOCUMENT, "zeta"), Failure("no heading holds 'zeta'"))
class Main(unittest.TestCase):
def setUp(self) -> None:
self.file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "notes.md"
self.file.write_text(DOCUMENT)
def run_main(self, *args: str) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(list(args))
return code, out.getvalue(), err.getvalue()
def test_prints_the_section(self):
self.assertEqual(self.run_main(str(self.file), "delta"), (0, "## Delta\n\nDelta text.\n", ""))
def test_a_failure_is_printed_to_stderr_with_exit_1(self):
self.assertEqual(self.run_main(str(self.file), "zeta"), (1, "", "markdown-section: no heading holds 'zeta'\n"))
def test_a_file_that_cant_be_read_exits_1_naming_it(self):
self.file.write_bytes(b"\xff\xfe## A\n")
missing = self.file.with_name("missing.md")
for unreadable, reason in ((missing, "missing.md"), (self.file, "decode")):
with self.subTest(reason):
code, out, err = self.run_main(str(unreadable), "a")
self.assertEqual((code, out), (1, ""))
self.assertRegex(err, rf"^markdown-section: .*{reason}")
def test_wrong_arguments_exit_2_with_the_usage(self):
for args in ((), (str(self.file),), (str(self.file), "a", "b"), (str(self.file), " ")):
with self.subTest(args):
self.assertEqual(self.run_main(*args), (2, "", "usage: markdown-section <file> <fragment>\n"))
def test_help_prints_the_usage_and_exits_0_whatever_follows_it(self):
for args in (("-h",), ("--help",), ("--help", "x")):
with self.subTest(args):
code, out, err = self.run_main(*args)
self.assertEqual((code, err), (0, ""))
self.assertTrue(out.startswith("Print one section of a markdown file"))
class Launcher(unittest.TestCase):
def test_the_launcher_runs_the_tool(self):
file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "notes.md"
file.write_text(DOCUMENT)
ran = subprocess.run([sys.executable, str(TOOL), str(file), "delta"], capture_output=True, text=True)
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "## Delta\n\nDelta text.\n", ""))
if __name__ == "__main__":
unittest.main()
+42 -34
View File
@@ -42,7 +42,7 @@ class Rung:
# The rungs a task's L steps its worker from the project's rung. # The rungs a task's L steps its worker from the project's rung.
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1} WORKER_STEPS = {1: -1, 2: -1, 3: 1, 4: 2}
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none. # The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4} REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
@@ -59,44 +59,15 @@ class Ladder:
return Rung(model, effort) return Rung(model, effort)
return Rung(family.model, effort) if effort else family return Rung(family.model, effort) if effort else family
def project_rung(self, model: str) -> Rung | None: def project_rung(self, model: str) -> "ProjectRung | None":
"""The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder.""" """The model's cheapest rung on this ladder, which for Opus 5.5 is its default effort; None for a model off the ladder."""
return next((rung for rung in self.rungs if rung.model == model), None) rung = next((rung for rung in self.rungs if rung.model == model), None)
return ProjectRung(self, rung) if rung else None
def worker_rung(self, project: Rung, likelihood: int) -> Rung:
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
return self.climbed(project, WORKER_STEPS[likelihood])
def lowest_worker_rung(self, project: Rung) -> Rung:
"""The lowest rung any L routes a worker to, counted from the project's rung."""
return self.climbed(project, min(WORKER_STEPS.values()))
def planning_rung(self, project: Rung, likelihood: int) -> Rung:
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
return self.highest(project, self.worker_rung(project, likelihood))
def review_floor(self, project: Rung, escape_and_impact: int) -> Rung:
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
return self.climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
def stepped_up(self, rung: Rung) -> Rung: def stepped_up(self, rung: Rung) -> Rung:
"""The rung above, or the top one; a rung off the ladder steps to the bottom one.""" """The rung above, or the top one; a rung off the ladder steps to the bottom one."""
return self.climbed(rung, 1) return self.climbed(rung, 1)
def review_rung(self, 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 whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own 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 self.reviewers_rung(project, worker, escape_and_impact, markdown_only)
def reviewers_rung(self, 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 self.highest(worker, self.review_floor(project, escape_and_impact))
def highest(self, *rungs: Rung) -> Rung: def highest(self, *rungs: Rung) -> Rung:
"""The most competent of the rungs; one off the ladder ranks below every rung on it.""" """The most competent of the rungs; one off the ladder ranks below every rung on it."""
return max(rungs, key=self.position) return max(rungs, key=self.position)
@@ -106,3 +77,40 @@ class Ladder:
def position(self, rung: Rung) -> int: def position(self, rung: Rung) -> int:
return self.rungs.index(rung) if rung in self.rungs else -1 return self.rungs.index(rung) if rung in self.rungs else -1
@dataclasses.dataclass(frozen=True)
class ProjectRung:
"""A project's rung on the ladder it stands on, from which each task's L and E + I count their steps."""
ladder: Ladder
rung: Rung
def worker_rung(self, likelihood: int) -> Rung:
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
return self.ladder.climbed(self.rung, WORKER_STEPS[likelihood])
def lowest_worker_rung(self) -> Rung:
"""The lowest rung any L routes a worker to, counted from the project's rung."""
return self.ladder.climbed(self.rung, min(WORKER_STEPS.values()))
def planning_rung(self, likelihood: int) -> Rung:
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
return self.ladder.highest(self.rung, self.worker_rung(likelihood))
def review_floor(self, escape_and_impact: int) -> Rung:
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
return self.ladder.climbed(self.rung, REVIEW_STEPS.get(escape_and_impact, 0))
def review_rung(self, 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 whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own 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 self.rung if kind in ("seat", "security") else self.reviewers_rung(worker, escape_and_impact, markdown_only)
def reviewers_rung(self, 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 self.rung if markdown_only else self.ladder.highest(worker, self.review_floor(escape_and_impact))
+7 -7
View File
@@ -2,7 +2,7 @@
import dataclasses import dataclasses
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
from model_routing.ladder import Ladder, Rung from model_routing.ladder import ProjectRung, Rung
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -17,12 +17,12 @@ class ReviewChoice:
higher: dict[Rung, int] higher: dict[Rung, int]
def chosen(ladder: Ladder, project: Rung, route: Route) -> ReviewChoice: def chosen(project: ProjectRung, route: Route) -> ReviewChoice:
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung on ladder is project.""" """The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
reviewers = ladder.reviewers_rung(project, route.rung, route.reviewed_on()) reviewers = project.reviewers_rung(route.rung, route.reviewed_on())
higher: dict[Rung, int] = {} higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1): for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
if (rung := ladder.reviewers_rung(project, route.rung, escape_and_impact)) != reviewers: if (rung := project.reviewers_rung(route.rung, escape_and_impact)) != reviewers:
higher.setdefault(rung, escape_and_impact) higher.setdefault(rung, escape_and_impact)
markdown_only = ladder.reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True) markdown_only = project.reviewers_rung(route.rung, route.reviewed_on(), markdown_only=True)
return ReviewChoice(reviewers, markdown_only, ladder.review_rung(project, route.rung, route.reviewed_on(), "seat"), ladder.review_rung(project, route.rung, route.reviewed_on(), "security"), higher) return ReviewChoice(reviewers, markdown_only, project.review_rung(route.rung, route.reviewed_on(), "seat"), project.review_rung(route.rung, route.reviewed_on(), "security"), higher)
+21 -20
View File
@@ -5,37 +5,38 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from plan.todo_table import LEVELS from plan.todo_table import LEVELS
from model_routing.ladder import ProjectRung, Rung, WORKER_STEPS
from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder_file import read_ladder, SHIPPED
from review_rules.review_passes import REVIEWERS from review_rules.review_passes import REVIEWERS
from model_routing.ladder import Rung, WORKER_STEPS
# The ladder this setup ships, whose rungs the tests below name. # The ladder this setup ships, whose rungs the tests below name.
LADDER = read_ladder(SHIPPED) LADDER = read_ladder(SHIPPED)
OPUS = Rung("claude-opus-5-5", "medium") OPUS = Rung("claude-opus-5-5", "medium")
PROJECT = ProjectRung(LADDER, OPUS)
FABLE_LOW = Rung("claude-fable-5-2", "low") FABLE_LOW = Rung("claude-fable-5-2", "low")
class Ladder(unittest.TestCase): class Ladder(unittest.TestCase):
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self): def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
self.assertEqual(LADDER.project_rung("claude-opus-5-5"), OPUS) self.assertEqual(LADDER.project_rung("claude-opus-5-5"), PROJECT)
self.assertEqual(LADDER.project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high")) self.assertEqual(LADDER.project_rung("claude-sonnet-5-5"), ProjectRung(LADDER, Rung("claude-sonnet-5-5", "high")))
self.assertEqual(LADDER.project_rung("claude-fable-5-2"), FABLE_LOW) self.assertEqual(LADDER.project_rung("claude-fable-5-2"), ProjectRung(LADDER, FABLE_LOW))
self.assertIsNone(LADDER.project_rung("claude-opus-5")) self.assertIsNone(LADDER.project_rung("claude-opus-5"))
self.assertIsNone(LADDER.project_rung("opus")) self.assertIsNone(LADDER.project_rung("opus"))
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self): def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
position = LADDER.rungs.index(OPUS) position = LADDER.rungs.index(OPUS)
self.assertEqual([LADDER.rungs.index(LADDER.worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1]) self.assertEqual([LADDER.rungs.index(PROJECT.worker_rung(likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 1, 2])
def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self): def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self):
position = LADDER.rungs.index(OPUS) position = LADDER.rungs.index(OPUS)
self.assertEqual([LADDER.rungs.index(LADDER.review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4]) self.assertEqual([LADDER.rungs.index(PROJECT.review_floor(total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
self.assertEqual(LADDER.review_floor(OPUS, 0), OPUS) self.assertEqual(PROJECT.review_floor(0), OPUS)
def test_a_step_past_either_end_stops_there(self): def test_a_step_past_either_end_stops_there(self):
self.assertEqual(LADDER.worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high")) self.assertEqual(PROJECT.worker_rung(1), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER.worker_rung(LADDER.rungs[0], 1), LADDER.rungs[0]) self.assertEqual(ProjectRung(LADDER, LADDER.rungs[0]).worker_rung(1), LADDER.rungs[0])
self.assertEqual(LADDER.review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER.rungs[-1]) self.assertEqual(ProjectRung(LADDER, Rung("claude-opus-5-5", "xhigh")).review_floor(8), LADDER.rungs[-1])
self.assertEqual(LADDER.stepped_up(LADDER.rungs[-1]), LADDER.rungs[-1]) self.assertEqual(LADDER.stepped_up(LADDER.rungs[-1]), LADDER.rungs[-1])
self.assertEqual(LADDER.stepped_up(OPUS), FABLE_LOW) self.assertEqual(LADDER.stepped_up(OPUS), FABLE_LOW)
@@ -43,11 +44,11 @@ class Ladder(unittest.TestCase):
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1))) self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
def test_names_the_lowest_rung_any_l_routes_a_worker_to(self): def test_names_the_lowest_rung_any_l_routes_a_worker_to(self):
self.assertEqual(LADDER.lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high")) self.assertEqual(PROJECT.lowest_worker_rung(), Rung("claude-sonnet-5-5", "high"))
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self): def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
self.assertEqual(LADDER.planning_rung(OPUS, 1), OPUS) self.assertEqual(PROJECT.planning_rung(1), OPUS)
self.assertEqual(LADDER.planning_rung(OPUS, 4), FABLE_LOW) self.assertEqual(PROJECT.planning_rung(4), Rung("claude-fable-5-2", "medium"))
def test_names_each_rung_by_a_family_the_agent_tool_takes(self): def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER.rungs}, {"model sonnet", "model opus", "model fable"}) self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER.rungs}, {"model sonnet", "model opus", "model fable"})
@@ -95,14 +96,14 @@ 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): def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
sonnet, fable = LADDER.rungs[0], LADDER.rungs[-1] sonnet, fable = LADDER.rungs[0], LADDER.rungs[-1]
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 4, "stability"), OPUS) self.assertEqual(PROJECT.review_rung(sonnet, 4, "stability"), OPUS)
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW) self.assertEqual(PROJECT.review_rung(sonnet, 5, "stability"), FABLE_LOW)
self.assertEqual(LADDER.review_rung(OPUS, fable, 5, "stability"), fable) self.assertEqual(PROJECT.review_rung(fable, 5, "stability"), fable)
self.assertEqual(LADDER.review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh")) self.assertEqual(PROJECT.review_rung(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): def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER.rungs[-1]] * len(REVIEWERS) + [OPUS, OPUS]) self.assertEqual([PROJECT.review_rung(LADDER.rungs[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER.rungs[-1]] * len(REVIEWERS) + [OPUS, OPUS])
def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self): def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self):
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2)) self.assertEqual([PROJECT.review_rung(LADDER.rungs[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
self.assertEqual(LADDER.review_rung(OPUS, LADDER.rungs[0], 4, "stability", markdown_only=True), OPUS) self.assertEqual(PROJECT.review_rung(LADDER.rungs[0], 4, "stability", markdown_only=True), OPUS)
+4 -3
View File
@@ -1,19 +1,20 @@
import unittest import unittest
from model_routing.review_choice import chosen from model_routing.review_choice import chosen
from model_routing.ladder import ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route from model_routing.route import Route
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED) LADDER = read_ladder(SHIPPED)
OPUS = Rung("claude-opus-5-5", "medium") OPUS = Rung("claude-opus-5-5", "medium")
PROJECT = ProjectRung(LADDER, OPUS)
FABLE = Rung("claude-fable-5-2", "max") FABLE = Rung("claude-fable-5-2", "max")
class Chosen(unittest.TestCase): class Chosen(unittest.TestCase):
def test_names_no_higher_rung_on_the_top_one(self): def test_names_no_higher_rung_on_the_top_one(self):
self.assertEqual(chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5)).higher, {}) self.assertEqual(chosen(PROJECT, 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): def test_reviews_a_branch_changing_only_markdown_on_the_projects_rung_and_the_seats_and_security_pass_there_always(self):
choice = chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5)) choice = chosen(PROJECT, Route(FABLE, 3, 4, 5))
self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS)) self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS))
+2 -2
View File
@@ -1,7 +1,7 @@
import unittest import unittest
from model_routing.worker_rungs import environment, handed, hands_rungs from model_routing.worker_rungs import environment, handed, hands_rungs
from model_routing.ladder import Ladder, Rung from model_routing.ladder import Ladder, ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route from model_routing.route import Route
@@ -10,7 +10,7 @@ LADDER = read_ladder(SHIPPED)
class Environment(unittest.TestCase): class Environment(unittest.TestCase):
PROJECT = Rung("claude-opus-5-5", "medium") PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium"))
WORKER = Rung("claude-sonnet-5-5", "high") WORKER = Rung("claude-sonnet-5-5", "high")
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self): def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
+7 -6
View File
@@ -3,7 +3,7 @@
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch.""" loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
import typing import typing
from model_routing.ladder import Ladder, Rung from model_routing.ladder import Ladder, ProjectRung, Rung
from model_routing.route import Route from model_routing.route import Route
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG" PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
@@ -12,9 +12,9 @@ WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT" ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
def environment(project: Rung | None, route: Route) -> dict[str, str]: def environment(project: ProjectRung | None, route: Route) -> dict[str, str]:
"""The variables a worker's claude on route starts with. A project off the ladder gets an empty project rung, so none is inherited from the environment.""" """The variables a worker's claude on route starts with. A project off the ladder gets an empty project rung, so none is inherited from the environment."""
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())} return {PROJECT_RUNG: str(project.rung) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())}
def hands_rungs(environ: typing.Mapping[str, str]) -> bool: def hands_rungs(environ: typing.Mapping[str, str]) -> bool:
@@ -22,10 +22,11 @@ def hands_rungs(environ: typing.Mapping[str, str]) -> bool:
return bool(environ.get(PROJECT_RUNG) and environ.get(WORKER_RUNG)) return bool(environ.get(PROJECT_RUNG) and environ.get(WORKER_RUNG))
def handed(environ: typing.Mapping[str, str], ladder: Ladder) -> tuple[Rung | None, Rung | None, int]: def handed(environ: typing.Mapping[str, str], ladder: Ladder) -> tuple[ProjectRung | None, Rung | None, int]:
"""The project's and the worker's rungs, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older loop-claude hands no E + I, and 0 steps no review up.""" """The project's rung and the worker's rung, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older loop-claude hands no E + I, and 0 steps no review up."""
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "") escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
return on_the_ladder(environ.get(PROJECT_RUNG), ladder), on_the_ladder(environ.get(WORKER_RUNG), ladder), int(escape_and_impact) if escape_and_impact.isdecimal() else 0 project = on_the_ladder(environ.get(PROJECT_RUNG), ladder)
return ProjectRung(ladder, project) if project else None, on_the_ladder(environ.get(WORKER_RUNG), ladder), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
def on_the_ladder(value: str | None, ladder: Ladder) -> Rung | None: def on_the_ladder(value: str | None, ladder: Ladder) -> Rung | None:
+107 -39
View File
@@ -2,7 +2,7 @@
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores. An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores.
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why.""" `add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, and its links to the epic's other open items. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
import dataclasses import dataclasses
import pathlib import pathlib
import re import re
@@ -50,6 +50,15 @@ class ReadsScoring(typing.Protocol):
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give.""" """The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
@dataclasses.dataclass(frozen=True)
class Link:
"""One "is blocked by" link of an issue."""
# The key of the issue that blocks.
blocker: str
# The link's own id, which Jira deletes it by.
id: str
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Issue: class Issue:
"""A child issue as Jira answered it, checked to hold what an item is read from.""" """A child issue as Jira answered it, checked to hold what an item is read from."""
@@ -57,8 +66,8 @@ class Issue:
summary: str summary: str
description: dict[str, typing.Any] | None description: dict[str, typing.Any] | None
fix_versions: tuple[str, ...] fix_versions: tuple[str, ...]
# The key of each issue this one "is blocked by". # The issue's "is blocked by" links, one per blocker unless Jira holds a link twice.
blockers: tuple[str, ...] links: tuple[Link, ...]
# PROPERTY's value; an empty object where the issue holds none. # PROPERTY's value; an empty object where the issue holds none.
scores: dict[str, typing.Any] scores: dict[str, typing.Any]
@@ -66,6 +75,10 @@ class Issue:
def number(self) -> int: def number(self) -> int:
return number(self.key) return number(self.key)
@property
def blockers(self) -> tuple[str, ...]:
return tuple(link.blocker for link in self.links)
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class JiraPlan: class JiraPlan:
@@ -124,10 +137,8 @@ class JiraPlan:
answered = children(self.epic, authorization, self.http) answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure): if isinstance(answered, Failure):
return answered return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)} if missing := missing_blocker(filing.blockers, keys_of(answered), self.label):
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read. return missing
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
before = placing(answered, filing.item, value, scoring) before = placing(answered, filing.item, value, scoring)
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]}) created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
if isinstance(created, Failure): if isinstance(created, Failure):
@@ -141,9 +152,7 @@ class JiraPlan:
"""Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses.""" """Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses."""
notes = [] notes = []
for blocker in blockers: for blocker in blockers:
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it. if isinstance(linked := self.link(key, blocker, authorization), Failure):
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
if isinstance(linked, Failure):
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira") notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
if isinstance(before, Failure): if isinstance(before, Failure):
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira") notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
@@ -151,6 +160,24 @@ class JiraPlan:
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira") notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
return tuple(notes) return tuple(notes)
def link(self, key: str, blocker: str, authorization: str) -> object:
"""Links the issue named key as blocked by the issue named blocker; a Failure where Jira refuses."""
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
return self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
def relinked(self, issue: Issue, wanted: tuple[str, ...] | None, open_keys: set[object], authorization: str) -> tuple[str, ...]:
"""Makes issue blocked by exactly the open children named in wanted: a link for each that it lacks, and a deletion of each link to an open child that wanted drops. A link to any other issue stays, since the team may have made it. None for wanted leaves every link as it is. A note for each request Jira refuses."""
if wanted is None:
return ()
notes = []
for blocker in (blocker for blocker in wanted if blocker not in issue.blockers):
if isinstance(linked := self.link(issue.key, blocker, authorization), Failure):
notes.append(f"edited {issue.key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
for link in (link for link in issue.links if link.blocker in open_keys and link.blocker not in wanted):
if isinstance(deleted := self.http("DELETE", f"{self.epic.site}/rest/api/3/issueLink/{link.id}", authorization, None), Failure):
notes.append(f"edited {issue.key}, but cannot delete the link that makes it blocked by {link.blocker}: {deleted.reason}; delete it in Jira")
return tuple(notes)
def rank_refusal(self, key: str, before: str, authorization: str) -> str | None: def rank_refusal(self, key: str, before: str, authorization: str) -> str | None:
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors.""" """Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before}) answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
@@ -172,8 +199,10 @@ class JiraPlan:
def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure: def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure:
"""Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_.""" """Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_."""
answered = children(self.epic, authorization, self.http) answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure): return answered if isinstance(answered, Failure) else self.child_in(answered, id_)
return answered
def child_in(self, answered: list[object], id_: int) -> dict[str, typing.Any] | Failure:
"""Item id_'s issue among the epic's open children; a Failure where none of them is item id_."""
key = f"{project_of(self.epic.key)}-{id_}" key = f"{project_of(self.epic.key)}-{id_}"
found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None) found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
return Failure(no_item(self.label, id_)) if found is None else found return Failure(no_item(self.label, id_)) if found is None else found
@@ -185,14 +214,24 @@ class JiraPlan:
description = self.to_adf(detail) description = self.to_adf(detail)
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure: def shows(self, issue: Issue, detail: str) -> bool:
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set. """Whether detail is the issue's description as a read shows it. An edit leaves such a description as Jira holds it, since converting the markdown back would drop each block's localId and Jira's spacing paragraphs."""
if issue.description is None:
return not detail.strip()
texts = self.to_markdown([issue.description])
return isinstance(texts, list) and texts[0].strip() == detail.strip()
A comment Jira refuses leaves the edit made, so the write counts as landed, and a note says to post the comment by hand.""" def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets the fields and the detail in one request, so Jira takes all of those or none, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set.
A link change or a comment Jira refuses leaves the edit made, so the write counts as landed, and a note says what to do by hand."""
authorization = basic_auth(self.env_file) authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure): if isinstance(authorization, Failure):
return authorization return authorization
raw = self.child(id_, authorization) answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
raw = self.child_in(answered, id_)
if isinstance(raw, Failure): if isinstance(raw, Failure):
return raw return raw
issue = issue_of(raw) issue = issue_of(raw)
@@ -202,8 +241,13 @@ class JiraPlan:
revision = revision_of(issue, cells(fields), detail, comment) revision = revision_of(issue, cells(fields), detail, comment)
if isinstance(revision, Failure): if isinstance(revision, Failure):
return revision return revision
open_keys = keys_of(answered)
if revision.blockers is not None and (missing := missing_blocker(revision.blockers, open_keys, self.label)):
return missing
if revision.blockers is not None and (looped := blocking_loop(answered, issue, revision.blockers, self.label)):
return looped
body = revision.body body = revision.body
if detail is not None: if detail is not None and not self.shows(issue, detail):
description = self.description_of(detail) description = self.description_of(detail)
if isinstance(description, Failure): if isinstance(description, Failure):
return description return description
@@ -217,13 +261,14 @@ class JiraPlan:
return version return version
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}} body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
url = f"{self.epic.site}/rest/api/3/issue/{key}" url = f"{self.epic.site}/rest/api/3/issue/{key}"
edited = self.http("PUT", url, authorization, body) edited = self.http("PUT", url, authorization, body) if body else None
if isinstance(edited, Failure): if isinstance(edited, Failure):
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}") return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
notes = self.relinked(issue, revision.blockers, open_keys, authorization)
if said is None: if said is None:
return Written(id_) return Written(id_, notes)
posted = self.http("POST", f"{url}/comment", authorization, {"body": said}) posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
return Written(id_, (f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ()) return Written(id_, notes + ((f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ()))
def finish(self, id_: int) -> Written | Failure: def finish(self, id_: int) -> Written | Failure:
"""Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it.""" """Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it."""
@@ -324,18 +369,18 @@ class Revision:
body: dict[str, typing.Any] body: dict[str, typing.Any]
# The release to move the issue to; None where the edit names none. # The release to move the issue to; None where the edit names none.
release: str | None release: str | None
# The key of each issue the edit makes the issue blocked by; None where the edit names no Blocked by.
blockers: tuple[str, ...] | None
def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure: def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure:
"""The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made. """The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made.
The summary, description and Fix Version of an issue a person filed are the team's, so there an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. No edit changes a link.""" The summary, description, Fix Version and links of an issue a person filed are the team's, so of such an issue an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. Only an edit of an issue the loop filed may name the blockers, whose links `JiraPlan.relinked` changes; each must be an open child, which the caller checks."""
held = issue.scores held = issue.scores
if BLOCKED_BY in named:
return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira")
own = held.get(FILED_BY[0]) == FILED_BY[1] own = held.get(FILED_BY[0]) == FILED_BY[1]
if not own and ("Item" in named or "Release" in named or detail is not None): if not own and ("Item" in named or "Release" in named or BLOCKED_BY in named or detail is not None):
return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description and Fix Version in Jira") return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira")
if not own and not (comment and comment.strip()): if not own and not (comment and comment.strip()):
return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why") return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why")
body: dict[str, typing.Any] = {} body: dict[str, typing.Any] = {}
@@ -347,7 +392,7 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment
if unfit := unfit_text(named.get("Item", ""), detail or ""): if unfit := unfit_text(named.get("Item", ""), detail or ""):
return unfit return unfit
release = named.get("Release") release = named.get("Release")
if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, f"item {issue.key}"), Failure): if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt", BLOCKED_BY) if name in named}, f"item {issue.key}", id_=issue.number), Failure):
return checked return checked
if any(name in named for name in SCORED): if any(name in named for name in SCORED):
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named} texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
@@ -360,7 +405,7 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment
body["properties"] = [{"key": PROPERTY, "value": value}] body["properties"] = [{"key": PROPERTY, "value": value}]
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY): if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]} body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
return Revision(body, release) return Revision(body, release, tuple(dict.fromkeys(f"{project_of(issue.key)}-{blocker}" for blocker in checked.blocked_by)) if BLOCKED_BY in named else None)
def offer_of(raw: object) -> tuple[str, str, str, str] | None: def offer_of(raw: object) -> tuple[str, str, str, str] | None:
@@ -403,15 +448,15 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None) seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
if isinstance(seen, Failure): if isinstance(seen, Failure):
return Failure(f"cannot read the epic {epic.key}: {seen.reason}") return Failure(f"cannot read the epic {epic.key}: {seen.reason}")
body: dict[str, object] = { return searched(epic.site, f"{epic.key}'s children", f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', {"fields": ["summary", "description", "fixVersions", "issuelinks"], "properties": [PROPERTY]}, authorization, http)
"jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC',
"fields": ["summary", "description", "fixVersions", "issuelinks"],
"properties": [PROPERTY], def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http) -> list[object] | Failure:
"maxResults": PAGE, """Every issue a JQL search on site finds, page by page. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end."""
} body: dict[str, object] = {"jql": jql, "maxResults": PAGE} | asked
found: list[object] = [] found: list[object] = []
for _ in range(MAX_PAGES): for _ in range(MAX_PAGES):
page = http("POST", f"{epic.site}/rest/api/3/search/jql", authorization, body) page = http("POST", f"{site}/rest/api/3/search/jql", authorization, body)
if isinstance(page, Failure): if isinstance(page, Failure):
return page return page
if not isinstance(page, dict) or not isinstance(page.get("issues"), list): if not isinstance(page, dict) or not isinstance(page.get("issues"), list):
@@ -420,7 +465,7 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu
if not page.get("nextPageToken"): if not page.get("nextPageToken"):
return found return found
body = body | {"nextPageToken": page["nextPageToken"]} body = body | {"nextPageToken": page["nextPageToken"]}
return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages") return Failure(f"the search for {what} did not end within {MAX_PAGES} pages")
def issue_of(raw: object) -> Issue | Failure: def issue_of(raw: object) -> Issue | Failure:
@@ -431,19 +476,42 @@ def issue_of(raw: object) -> Issue | Failure:
# The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it. # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it.
try: try:
fields = raw["fields"] fields = raw["fields"]
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") links = tuple(Link(link["inwardIssue"]["key"], link["id"]) for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
held = raw.get("properties", {}).get(PROPERTY, {}) held = raw.get("properties", {}).get(PROPERTY, {})
summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]) summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"])
except (AttributeError, KeyError, TypeError) as failure: except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
if not isinstance(held, dict): if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
issue = Issue(key, summary, description, versions, blockers, held) issue = Issue(key, summary, description, versions, links, held)
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers): if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(isinstance(link.id, str) for link in links) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value") return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a link's id or linked issue's key holds another kind of value")
return issue return issue
def keys_of(answered: list[object]) -> set[object]:
"""The key of each issue in the search's answer."""
return {raw.get("key") for raw in answered if isinstance(raw, dict)}
def missing_blocker(blockers: tuple[str, ...], held: set[object], label: str) -> Failure | None:
"""None where each of blockers is among the keys held, the plan's open children, else a Failure naming the first that isn't. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
missing = next((blocker for blocker in blockers if blocker not in held), None)
return None if missing is None else Failure(f"{label} holds no item {number(missing)} to be blocked by")
def blocking_loop(answered: list[object], issue: Issue, blockers: tuple[str, ...], label: str) -> Failure | None:
"""A Failure where issue, once blocked by blockers, which the caller has checked are open children, would block itself through the items its blockers wait for, and none of them could be taken; None otherwise. A loop the plan already holds without issue isn't this edit's."""
issues = {found.key: found for raw in answered if isinstance(found := issue_of(raw), Issue)}
waits_for = {found.key: found.blockers for found in issues.values()} | {issue.key: blockers}
reached: set[str] = set()
frontier = set(blockers)
while frontier:
reached |= frontier
frontier = {blocker for key in frontier for blocker in waits_for[key] if blocker in issues} - reached
return Failure(f"{label}: item {issue.number} would be blocked by itself through {', '.join(str(number(key)) for key in sorted(reached - {issue.key}, key=number))}; drop one of the blockers") if issue.key in reached else None
def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure: def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
"""The plan the issues hold, in their order.""" """The plan the issues hold, in their order."""
project = project_of(epic.key) project = project_of(epic.key)
+1 -1
View File
@@ -29,7 +29,7 @@ class Written:
class PlanStore(typing.Protocol): class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost.""" """A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost."""
@property @property
def label(self) -> str: def label(self) -> str:
+131 -10
View File
@@ -22,9 +22,14 @@ SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
def link_id(blocked: str, blocker: str) -> str:
"""The id Jira gives the link that says blocked is blocked by blocker."""
return f"{blocked}<{blocker}"
def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]: def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]:
links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by] links = [{"id": link_id(key, blocker), "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by]
links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks] links += [{"id": link_id(blocked, key), "type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks]
return { return {
"key": key, "key": key,
"fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links}, "fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links},
@@ -171,7 +176,7 @@ class JiraPlan(unittest.TestCase):
def test_an_issue_in_another_shape_fails_the_read_naming_it(self): def test_an_issue_in_another_shape_fails_the_read_naming_it(self):
good = issue("ABC-1") good = issue("ABC-1")
for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator] for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"id": "1", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"id": "1", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"id": 7, "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator]
with self.subTest(wrong=wrong): with self.subTest(wrong=wrong):
failure = self.read(wrong) # type: ignore[arg-type] failure = self.read(wrong) # type: ignore[arg-type]
self.assertIsInstance(failure, Failure) self.assertIsInstance(failure, Failure)
@@ -487,24 +492,30 @@ class Editing(unittest.TestCase):
self.edited: object = None self.edited: object = None
self.commented: object = {"id": "10100"} self.commented: object = {"id": "10100"}
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}] self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}]
self.linked: object = None
self.unlinked: object = None
def http(self, method: str, url: str, authorization: str, body: object) -> object: def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit and self.commented to a new comment.""" """Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit, self.commented to a new comment, self.linked to a new link and self.unlinked to a deleted one."""
self.calls.append((method, url, body)) self.calls.append((method, url, body))
assert authorization == AUTHORIZATION assert authorization == AUTHORIZATION
if method == "PUT": if method == "PUT":
return self.edited return self.edited
if method == "DELETE":
return self.unlinked
if url == LINKS:
return self.linked
return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"}) return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
def to_adf(self, markdown: str) -> dict[str, object] | Failure: def to_adf(self, markdown: str) -> dict[str, object] | Failure:
return adf(markdown) return adf(markdown)
def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None): def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment) return jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment)
def writes(self) -> list[tuple[str, str, object]]: def writes(self) -> list[tuple[str, str, object]]:
"""Each request that changes Jira, in order.""" """Each request that changes Jira, in order."""
return [call for call in self.calls if call[0] == "PUT" or call[1].endswith("/comment")] return [call for call in self.calls if call[0] in ("PUT", "DELETE") or call[1].endswith(("/comment", "/issueLink"))]
def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self): def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self):
self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34)) self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34))
@@ -518,7 +529,21 @@ class Editing(unittest.TestCase):
self.edit(34, {"E": "3"}) self.edit(34, {"E": "3"})
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}]) self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
def test_a_detail_unchanged_since_the_read_leaves_the_description_as_jira_holds_it(self):
# Jira's own spacing paragraph and localIds, which a description converted back from markdown would lose.
held = {"type": "doc", "version": 1, "content": [{"type": "paragraph", "attrs": {"localId": "p-1"}, "content": [{"type": "text", "text": "Why it counts."}]}, {"type": "paragraph", "attrs": {"localId": "p-2"}}]}
self.open = [issue("ABC-34", scores=PROPERTY, description=held)]
self.assertEqual(self.edit(34, {"L": "2"}, "Why it counts.\n"), Written(34))
self.assertEqual(self.edit(34, {}, "Why it counts."), Written(34))
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2}}]})])
def test_an_edited_detail_replaces_the_description(self):
self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))]
self.edit(34, {}, "Why it counts twice.")
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": adf("Why it counts twice.")}})])
def test_an_empty_detail_removes_the_description(self): def test_an_empty_detail_removes_the_description(self):
self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))]
self.edit(34, {}, " \n") self.edit(34, {}, " \n")
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})]) self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})])
@@ -569,7 +594,7 @@ class Editing(unittest.TestCase):
def test_what_a_person_wrote_or_planned_is_never_edited(self): def test_what_a_person_wrote_or_planned_is_never_edited(self):
for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")): for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")):
with self.subTest(fields=fields, detail=detail): with self.subTest(fields=fields, detail=detail):
self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description and Fix Version in Jira")) self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira"))
self.assertEqual(self.writes(), []) self.assertEqual(self.writes(), [])
def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self): def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self):
@@ -585,8 +610,96 @@ class Editing(unittest.TestCase):
self.commented = Failure("HTTP 403") self.commented = Failure("HTTP 403")
self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",))) self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",)))
def test_an_edit_of_the_blockers_fails_since_the_store_changes_no_link(self): def test_links_each_new_blocker_to_an_issue_the_loop_filed(self):
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Failure("the loop doesn't change an issue's links: link ABC-34 in Jira")) self.assertEqual(self.edit(34, {"Blocked by": "35, 36"}), Written(34))
self.assertEqual(self.writes(), [("POST", LINKS, {"type": {"name": "Blocks"}, "inwardIssue": {"key": f"ABC-{blocker}"}, "outwardIssue": {"key": "ABC-34"}}) for blocker in (35, 36)])
def test_links_a_blocker_named_twice_once(self):
self.edit(34, {"Blocked by": "35, 35"})
self.assertEqual([body["inwardIssue"]["key"] for _, _, body in self.writes()], ["ABC-35"]) # type: ignore[index]
def test_deletes_the_link_of_each_blocker_the_edit_drops_and_makes_none_for_one_it_keeps(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34))
self.assertEqual(self.writes(), [("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-36')}", None)])
def test_an_empty_blocked_by_deletes_every_link_the_issue_holds(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"), blocks=("ABC-35",))
self.assertEqual(self.edit(34, {"Blocked by": ""}), Written(34))
self.assertEqual(self.writes(), [("DELETE", f"{LINKS}/{link_id('ABC-34', blocker)}", None) for blocker in ("ABC-35", "ABC-36")])
def test_a_link_to_an_issue_that_is_no_open_child_is_never_deleted(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "OPS-9", "ABC-99"))
self.assertEqual(self.edit(34, {"Blocked by": "36"}), Written(34))
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("POST", LINKS), ("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-35')}")])
def test_an_edit_that_names_no_blocked_by_leaves_the_links_as_they_are(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35",))
self.edit(34, {"L": "2"})
self.assertEqual([method for method, _, _ in self.writes()], ["PUT"])
def test_a_blocked_by_the_issue_already_holds_writes_nothing(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
self.assertEqual(self.edit(34, {"Blocked by": "36, 35"}), Written(34))
self.assertEqual(self.writes(), [])
def test_a_blocker_swapped_for_another_deletes_one_link_and_makes_one(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35",))
self.edit(34, {"Blocked by": "36"})
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("POST", LINKS), ("DELETE", f"{LINKS}/{link_id('ABC-34', 'ABC-35')}")])
def test_changes_the_links_after_the_edit_and_before_the_comment(self):
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35"}, None, COMMENT), Written(34))
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")])
def test_a_failed_edit_makes_no_link(self):
self.edited = Failure("HTTP 400")
self.assertIsInstance(self.edit(34, {"L": "2", "Blocked by": "35"}), Failure)
self.assertEqual([method for method, _, _ in self.writes()], ["PUT"])
def test_a_link_jira_refuses_leaves_the_edit_made_with_a_note_and_the_other_links_changed(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-36",))
self.linked = Failure("HTTP 403")
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34, ("edited ABC-34, but cannot link it as blocked by ABC-35: HTTP 403; link it in Jira",)))
self.assertEqual([method for method, _, _ in self.writes()], ["POST", "DELETE"])
def test_a_link_jira_refuses_to_delete_leaves_a_note_and_the_comment_posted(self):
self.open[0] = issue("ABC-34", scores=PROPERTY, blocked_by=("ABC-35", "ABC-36"))
self.unlinked = Failure("HTTP 404")
self.assertEqual(self.edit(34, {"Blocked by": ""}, None, COMMENT), Written(34, ("edited ABC-34, but cannot delete the link that makes it blocked by ABC-35: HTTP 404; delete it in Jira", "edited ABC-34, but cannot delete the link that makes it blocked by ABC-36: HTTP 404; delete it in Jira")))
self.assertEqual(self.writes()[-1][1], f"{ISSUES}/ABC-34/comment")
def test_a_blocker_that_is_no_open_child_fails_before_any_write(self):
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35, 40"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40 to be blocked by"))
self.assertEqual(self.writes(), [])
def test_a_blocker_that_makes_the_issue_wait_for_itself_fails_before_any_write(self):
self.open[1] = issue("ABC-35", scores=PROPERTY, blocked_by=("ABC-34",))
self.open[2] = issue("ABC-36", scores=PROPERTY, blocked_by=("ABC-35",))
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "36"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12: item 34 would be blocked by itself through 35, 36; drop one of the blockers"))
self.assertEqual(self.writes(), [])
def test_the_loop_names_its_items_by_number_not_by_key(self):
self.open += [issue("ABC-9", scores=PROPERTY, blocked_by=("ABC-10",)), issue("ABC-10", scores=PROPERTY, blocked_by=("ABC-34",))]
failure = self.edit(34, {"Blocked by": "9"})
self.assertTrue(failure.reason.endswith("through 9, 10; drop one of the blockers")) # type: ignore[union-attr]
def test_a_loop_the_plan_holds_without_the_issue_does_not_stop_its_edit(self):
self.open[1] = issue("ABC-35", scores=PROPERTY, blocked_by=("ABC-36",))
self.open[2] = issue("ABC-36", scores=PROPERTY, blocked_by=("ABC-35",))
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Written(34))
self.assertEqual([method for method, _, _ in self.writes()], ["POST"])
def test_a_blocked_by_out_of_format_or_naming_the_issue_itself_fails_before_any_write(self):
for cell in ("ABC-35", "35,36", "34"):
with self.subTest(cell=cell):
self.assertIsInstance(self.edit(34, {"Blocked by": cell}), Failure)
self.assertEqual(self.writes(), [])
def test_the_links_of_an_issue_a_person_filed_are_never_changed(self):
for id_ in (35, 36):
with self.subTest(id_=id_):
self.assertEqual(self.edit(id_, {"Blocked by": "34"}, None, COMMENT), Failure(f"a person filed ABC-{id_}, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira"))
self.assertEqual(self.writes(), []) self.assertEqual(self.writes(), [])
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self): def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self):
@@ -655,11 +768,14 @@ class Finishing(unittest.TestCase):
self.open = [issue("ABC-34"), issue("ABC-35")] self.open = [issue("ABC-34"), issue("ABC-35")]
self.transitions: object = {"transitions": [transition("11", "Start", "In Progress", "indeterminate"), transition("31", "Mark as done", "Done")]} self.transitions: object = {"transitions": [transition("11", "Start", "In Progress", "indeterminate"), transition("31", "Mark as done", "Done")]}
self.moved: object = None self.moved: object = None
self.search_refused: Failure | None = None
def http(self, method: str, url: str, authorization: str, body: object) -> object: def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.open to the search, self.transitions for ABC-34's transitions and self.moved to a transition of it.""" """Stands in for Jira: answers the epic, self.open to the search, or self.search_refused where set, self.transitions for ABC-34's transitions and self.moved to a transition of it."""
self.calls.append((method, url, body)) self.calls.append((method, url, body))
assert authorization == AUTHORIZATION assert authorization == AUTHORIZATION
if url == SEARCH and self.search_refused:
return self.search_refused
if url == TRANSITIONS: if url == TRANSITIONS:
return self.transitions if method == "GET" else self.moved return self.transitions if method == "GET" else self.moved
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"}) return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
@@ -674,6 +790,11 @@ class Finishing(unittest.TestCase):
self.assertEqual(self.finish(), Written(34)) self.assertEqual(self.finish(), Written(34))
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})]) self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
def test_a_search_jira_refuses_fails_the_finish_before_any_move(self):
self.search_refused = Failure("HTTP 500")
self.assertEqual(self.finish(), Failure("HTTP 500"))
self.assertEqual(self.posts(), [])
def test_a_config_that_names_no_transition_fails_before_any_request(self): def test_a_config_that_names_no_transition_fails_before_any_request(self):
self.assertEqual(self.finish(by=None), Failure("the config names no transition to finish an item by: set `jira-finish-transition` and `jira-finish-status`, as `project-config --help` shows")) self.assertEqual(self.finish(by=None), Failure("the config names no transition to finish an item by: set `jira-finish-transition` and `jira-finish-status`, as `project-config --help` shows"))
self.assertEqual(self.calls, []) self.assertEqual(self.calls, [])
+6 -1
View File
@@ -6,6 +6,9 @@ Run inside a checkout, or a worktree of one. It finds the config that names the
~/.claude-projects/<key>/config.toml, and prints each setting and its absolute path, as in ~/.claude-projects/<key>/config.toml, and prints each setting and its absolute path, as in
`plan: /home/me/code/acme/todo.md`. Given a setting, it prints only that setting's path. `plan: /home/me/code/acme/todo.md`. Given a setting, it prints only that setting's path.
`~/.claude-projects/do-epic/` holds do-epic's machine-wide settings, not a project's. It needs no `checkout`,
and project-config doesn't read anything from it, so no project may use `do-epic` as its key.
The config is TOML. `checkout` names the project's main checkout, and every setting in the example below is a path: The config is TOML. `checkout` names the project's main checkout, and every setting in the example below is a path:
"checkout:<path>" inside the checkout, "folder:<path>" inside the config's own folder, or one that "checkout:<path>" inside the checkout, "folder:<path>" inside the config's own folder, or one that
starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own file. starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own file.
@@ -51,7 +54,9 @@ Where the config leaves them out, `todo-item finish` fails in a Jira plan. Each
`goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The `goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The
epic's description is then the goals file, with ## Goals and ## Audience as headings, and epic's description is then the goals file, with ## Goals and ## Audience as headings, and
`project-config goals-and-audience` prints the setting as the config spells it. The description is `project-config goals-and-audience` prints the setting as the config spells it. The description is
only read: edit it in Jira. written by `project-record save`, except a change to ## Goals or ## Audience, which is refused:
edit those two in Jira. A save rewrites the whole description from markdown, which keeps no
mention, macro or block id that markdown can't hold.
Each record, `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`, Each record, `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`,
may name a Confluence Cloud page in place of a path, as "confluence:" and the page's address, with or may name a Confluence Cloud page in place of a path, as "confluence:" and the page's address, with or
+29 -13
View File
@@ -17,6 +17,10 @@ from plan.ranking import variables
PROJECTS = ".claude-projects" PROJECTS = ".claude-projects"
CONFIG = "config.toml" CONFIG = "config.toml"
# The key of do-epic's machine-wide settings: the folder's config.toml has no `checkout`, so no project may use the key.
DO_EPIC = "do-epic"
# A Jira Cloud or Confluence Cloud site's address: only https, so the credentials are never sent in the clear.
SITE = r"https://[A-Za-z0-9.-]+(?::[0-9]+)?"
# Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They picked role names over file names, which a client's project doesn't share. # Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They picked role names over file names, which a client's project doesn't share.
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles", "standards") SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles", "standards")
# They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default. # They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default.
@@ -177,7 +181,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
top is the worktree that asks, and main itself outside a worktree. A `checkout:` path lands in top. top is the worktree that asks, and main itself outside a worktree. A `checkout:` path lands in top.
A config that cannot be read fails every project, since it may be the one that names main.""" A config that cannot be read fails every project, since it may be the one that names main."""
named: list[tuple[pathlib.Path, dict[str, object]]] = [] named: list[tuple[pathlib.Path, dict[str, object]]] = []
for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}")): for file in configs(home):
config = read(file, home) config = read(file, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
@@ -290,14 +294,14 @@ def name_of(value: object) -> str | None:
def epic_of(value: object) -> Epic | None: def epic_of(value: object) -> Epic | None:
"""The epic a setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear.""" """The epic a setting's value spells; None where it spells none."""
spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value) spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}({SITE})/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value)
return Epic(spelt.group(1), spelt.group(2)) if spelt else None return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def page_of(value: object) -> Page | None: def page_of(value: object) -> Page | None:
"""The page a setting's value spells; None where it spells none. Only https, as for an epic.""" """The page a setting's value spells; None where it spells none."""
spelt = isinstance(value, str) and re.fullmatch(rf"{CONFLUENCE}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/wiki/spaces/[^/?#]+/pages/([0-9]+)(?:/[^/?#]*)?", value) spelt = isinstance(value, str) and re.fullmatch(rf"{CONFLUENCE}({SITE})/wiki/spaces/[^/?#]+/pages/([0-9]+)(?:/[^/?#]*)?", value)
return Page(spelt.group(1), spelt.group(2), spelt.string) if spelt else None return Page(spelt.group(1), spelt.group(2), spelt.string) if spelt else None
@@ -339,25 +343,37 @@ def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None: def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None:
"""The config in folder, read as its project's main checkout reads it; None where folder is not a config's folder under home.""" """The config in folder, read as its project's main checkout reads it; None where folder is not a config's folder under home."""
# Matched on resolved paths, as git names a folder, so a config's folder reached through a symlink is still found. # Matched on resolved paths, as git names a folder, so a config's folder reached through a symlink is still found.
file = next((file for file in (home / PROJECTS).glob(f"*/{CONFIG}") if file.parent.resolve() == folder.resolve()), None) file = next((file for file in configs(home) if file.parent.resolve() == folder.resolve()), None)
if file is None: if file is None:
return None return None
config = read(file, home) config = read(file, home)
return config if isinstance(config, Failure) else load(config[0], config[0], home) return config if isinstance(config, Failure) else load(config[0], config[0], home)
def configs(home: pathlib.Path) -> list[pathlib.Path]:
"""Every project's config file under home, in key order. do-epic's machine-wide config is not a project's."""
return sorted(file for file in (home / PROJECTS).glob(f"*/{CONFIG}") if file.parent.name != DO_EPIC)
def env_files(home: pathlib.Path) -> list[pathlib.Path]: def env_files(home: pathlib.Path) -> list[pathlib.Path]:
"""Every config's env-file, read without the checks load makes, so a config that fails them still keeps its credentials guarded; a config that cannot be read names none.""" """Every config's env-file, do-epic's included. Each is read without the checks load makes, so a config that fails them still keeps its credentials guarded. A config that can't be read doesn't name one."""
configs = [read(file, home) for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}"))] values = [parsed(file) for file in (*configs(home), home / PROJECTS / DO_EPIC / CONFIG)]
return [path for config in configs if not isinstance(config, Failure) and (path := anywhere(config[1].get(ENV_FILE), home))] return [path for found in values if not isinstance(found, Failure) and (path := anywhere(found.get(ENV_FILE), home))]
def parsed(file: pathlib.Path) -> dict[str, object] | Failure:
"""The TOML values in file; a Failure where file can't be read or parsed."""
try:
return tomllib.loads(file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure:
return Failure(f"cannot read {file}: {failure}")
def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure: def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure:
"""The checkout a config names, as an absolute path, and its other values.""" """The checkout a config names, as an absolute path, and its other values."""
try: values = parsed(file)
values = tomllib.loads(file.read_text(encoding="utf-8")) if isinstance(values, Failure):
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure: return values
return Failure(f"cannot read {file}: {failure}")
checkout = anywhere(values.get("checkout"), home) checkout = anywhere(values.get("checkout"), home)
if checkout is None: if checkout is None:
found = f"not {values['checkout']!r}" if "checkout" in values else "and is missing" found = f"not {values['checkout']!r}" if "checkout" in values else "and is missing"
+15
View File
@@ -91,6 +91,13 @@ class LoadTest(ConfigCase):
self.assertEqual(found.paths["standards"], self.home / ".claude" / "skills" / "larv-review" / "standards") self.assertEqual(found.paths["standards"], self.home / ".claude" / "skills" / "larv-review" / "standards")
self.assertEqual(tuple(found.paths), SETTINGS) self.assertEqual(tuple(found.paths), SETTINGS)
def test_the_do_epic_folder_is_no_projects_config_so_it_needs_no_checkout(self) -> None:
self.write("do-epic", 'jira-url = "https://acme.atlassian.net"\n')
self.write("acme", CLIENT)
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.key, "acme")
def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None: def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None:
self.write("acme", JIRA_CLIENT) self.write("acme", JIRA_CLIENT)
found = load(self.checkout, self.checkout, self.home) found = load(self.checkout, self.checkout, self.home)
@@ -578,6 +585,10 @@ class HeldTest(ConfigCase):
(elsewhere / "config.toml").write_text(CLIENT, encoding="utf-8") (elsewhere / "config.toml").write_text(CLIENT, encoding="utf-8")
self.assertIsNone(held(elsewhere, self.home), "a config.toml outside ~/.claude-projects/") self.assertIsNone(held(elsewhere, self.home), "a config.toml outside ~/.claude-projects/")
def test_the_do_epic_folder_holds_no_projects_config(self) -> None:
folder = self.write("do-epic", CLIENT)
self.assertIsNone(held(folder, self.home))
def test_a_configs_folder_reached_through_a_symlink_holds_its_config(self) -> None: def test_a_configs_folder_reached_through_a_symlink_holds_its_config(self) -> None:
target = self.home / "kept" / "acme" target = self.home / "kept" / "acme"
target.mkdir(parents=True) target.mkdir(parents=True)
@@ -595,6 +606,10 @@ class EnvFilesTest(ConfigCase):
self.write("none", CLIENT) self.write("none", CLIENT)
self.assertEqual(env_files(self.home), [self.home / "acme.env", pathlib.Path("/srv/other.env")]) self.assertEqual(env_files(self.home), [self.home / "acme.env", pathlib.Path("/srv/other.env")])
def test_lists_do_epics_env_file_though_its_config_names_no_checkout(self) -> None:
self.write("do-epic", 'env-file = "~/jira.env"\n')
self.assertEqual(env_files(self.home), [self.home / "jira.env"])
class ToolTest(ConfigCase): class ToolTest(ConfigCase):
def test_prints_a_jira_plan_as_the_config_spells_it(self) -> None: def test_prints_a_jira_plan_as_the_config_spells_it(self) -> None:
+4 -4
View File
@@ -5,8 +5,8 @@ usage: project-record open <record>
Run inside a checkout, or a worktree of one. <record> is one of decisions, score-anchors, Run inside a checkout, or a worktree of one. <record> is one of decisions, score-anchors,
comprehension-history, reading-cost and changelog, each kept where the project's config names it, comprehension-history, reading-cost and changelog, each kept where the project's config names it,
or goals-and-audience, the goals file. Goals kept in a Jira epic's description are only read, so or goals-and-audience, the goals file. Save refuses a change to the ## Goals or ## Audience of goals
save refuses them: edit the epic in Jira. kept in a Jira epic's description: edit those two in Jira.
open prints the path of a file holding the record's text, and nothing else. Read and edit that open prints the path of a file holding the record's text, and nothing else. Read and edit that
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
@@ -20,8 +20,8 @@ save stores the file's text in the record, and prints one line saying so. Where
as a file, there is nothing left to store, and save says so. Run it after every edit, so the same as a file, there is nothing left to store, and save says so. Run it after every edit, so the same
steps work wherever a project keeps the record. steps work wherever a project keeps the record.
For a record kept on a Confluence page, save refuses where someone saved the page after open read For a record kept on a Confluence page or in a Jira epic's description, save refuses where someone
it or after save last wrote it, and the human decides what follows. The copy keeps the unsaved edit saved it after open read it or after save last wrote it, and the human decides what follows. The copy keeps the unsaved edit
until open runs again and writes the copy afresh. until open runs again and writes the copy afresh.
Exit 2 on bad arguments, and 1, saying why, on any other failure. Exit 2 on bad arguments, and 1, saying why, on any other failure.
+9
View File
@@ -16,6 +16,7 @@ from transcript_archive.write import archive
from claude_code.entries import AssistantTurn from claude_code.entries import AssistantTurn
from project_config.templates import BRANCH from project_config.templates import BRANCH
from reading_cost.measure import Checkout, Reading from reading_cost.measure import Checkout, Reading
from text_files import compressed
from failure import Failure from failure import Failure
from reading_cost import figures, main, measure from reading_cost import figures, main, measure
from transcript_archive.read import finished_chunks, FinishedChunk from transcript_archive.read import finished_chunks, FinishedChunk
@@ -173,6 +174,14 @@ class ReadingCostTool(unittest.TestCase):
self.assertEqual((ran.returncode, ran.stdout), (1, "")) self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("no config names the checkout", ran.stderr) self.assertIn("no config names the checkout", ran.stderr)
def test_measures_a_chunk_whose_archived_transcripts_are_compressed(self):
self.archive_chunk(1790000000)
for copy in self.archive.rglob("*.jsonl"):
self.assertIsNone(compressed.compress(copy))
ran = self.run_tool(self.checkout)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("33 new input tokens before the first commit.", (self.checkout / "docs" / "reading-cost.md").read_text())
def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self): def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self):
self.archive_chunk(1790000200) self.archive_chunk(1790000200)
self.archive_chunk(1790000100) self.archive_chunk(1790000100)
+19 -6
View File
@@ -8,9 +8,9 @@ import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown
from record_store.held import digest_of, Held
from rest_client.json_request import ErrorAnswer from rest_client.json_request import ErrorAnswer
from failure import Failure from failure import Failure
from record_store.held import Held
from project_config.settings import Page from project_config.settings import Page
# What Confluence answers to a write whose version isn't the one after the version it holds. # What Confluence answers to a write whose version isn't the one after the version it holds.
@@ -20,9 +20,10 @@ SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents"
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Seen: class Seen:
"""The page's version number and title as a read found them or a write left them. A write needs both, so a Held's version holds both, as JSON.""" """The page's version number and title as a read found them or a write left them, and the digest of the markdown it found or sent. A write needs the version and title, and sends nothing where its text has that digest, so a Held's version holds all three, as JSON. The digest is None where the version came from a request that held no text."""
version: int version: int
title: str title: str
digest: str | None = None
@property @property
def token(self) -> str: def token(self) -> str:
@@ -64,7 +65,7 @@ class ConfluencePage:
if not isinstance(body, str): if not isinstance(body, str):
return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format") return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format")
text = self.converted(body) text = self.converted(body)
return text if isinstance(text, Failure) else Held(text, seen.token) return text if isinstance(text, Failure) else Held(text, Seen(seen.version, seen.title, digest_of(text)).token)
def converted(self, held: str) -> str | Failure: def converted(self, held: str) -> str | Failure:
"""The markdown of the body held, the JSON of an ADF document; empty where held is.""" """The markdown of the body held, the JSON of an ADF document; empty where held is."""
@@ -86,6 +87,14 @@ class ConfluencePage:
seen = self.seen_of(over) seen = self.seen_of(over)
if isinstance(seen, Failure): if isinstance(seen, Failure):
return seen return seen
# A read's markdown leaves out the localIds and spacing paragraphs Confluence holds, so a write of the same text back would drop them: send nothing. Without a write Confluence answers no 409, so read the version to refuse where a teammate saved since.
if over is not None and seen.digest == digest_of(text):
current = self.fetched("")
if isinstance(current, Failure):
return current
if current[0].version != seen.version:
return self.saved_since(seen.version, f"Confluence holds version {current[0].version}")
return Held(text, over)
document = self.to_adf(text) document = self.to_adf(text)
if isinstance(document, Failure): if isinstance(document, Failure):
return Failure(f"cannot convert the text for {self.label} to ADF: {document.reason}") return Failure(f"cannot convert the text for {self.label} to ADF: {document.reason}")
@@ -95,10 +104,14 @@ class ConfluencePage:
body = {"id": self.page.page_id, "status": "current", "title": seen.title, "body": {"representation": "atlas_doc_format", "value": json.dumps(document)}, "version": {"number": seen.version + 1}} body = {"id": self.page.page_id, "status": "current", "title": seen.title, "body": {"representation": "atlas_doc_format", "value": json.dumps(document)}, "version": {"number": seen.version + 1}}
answer = self.http("PUT", self.url, authorization, body) answer = self.http("PUT", self.url, authorization, body)
if isinstance(answer, ErrorAnswer) and answer.status == CONFLICT: if isinstance(answer, ErrorAnswer) and answer.status == CONFLICT:
return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})") return self.saved_since(seen.version, answer.reason)
if isinstance(answer, Failure): if isinstance(answer, Failure):
return Failure(f"cannot write {self.label}: {answer.reason}") return Failure(f"cannot write {self.label}: {answer.reason}")
return Held(text, Seen(seen.version + 1, seen.title).token) return Held(text, Seen(seen.version + 1, seen.title, digest_of(text)).token)
def saved_since(self, version: int, evidence: str) -> Failure:
"""The refusal of a write over version, which a teammate's save replaced, as evidence shows."""
return Failure(f"someone saved {self.label} since the loop read version {version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({evidence})")
def fetched(self, query: str) -> tuple[Seen, object] | Failure: def fetched(self, query: str) -> tuple[Seen, object] | Failure:
"""The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't.""" """The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't."""
@@ -124,6 +137,6 @@ class ConfluencePage:
return fetched if isinstance(fetched, Failure) else fetched[0] return fetched if isinstance(fetched, Failure) else fetched[0]
try: try:
held: typing.Any = json.loads(over) held: typing.Any = json.loads(over)
return Seen(int(held["version"]), str(held["title"])) return Seen(int(held["version"]), str(held["title"]), held.get("digest"))
except (ValueError, KeyError, TypeError) as failure: except (ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}") return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}")
+31 -1
View File
@@ -1,4 +1,4 @@
"""Record stores for tests, held to record_store.contract like every backend.""" """Record stores for tests, held to record_store.contract like every backend, and a fake Jira."""
import dataclasses import dataclasses
from failure import Failure from failure import Failure
@@ -29,3 +29,33 @@ class MemoryStore:
return Failure(f"someone saved {self.label} since version {over}") return Failure(f"someone saved {self.label} since version {over}")
self.text, self.version = text, self.version + 1 self.text, self.version = text, self.version + 1
return Held(text, str(self.version)) return Held(text, str(self.version))
class FakeJira:
"""One epic as Jira Cloud's REST API version 3 serves it: a description that is null or a document, and no version a write could check. Its documents hold the text in one paragraph, which fake_adf and fake_markdown convert."""
def __init__(self) -> None:
self.description: dict[str, object] | None = None
self.calls: list[tuple[str, str, str, object]] = []
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
if method == "GET":
return {"key": "ABC-12", "fields": {"description": self.description}}
assert isinstance(body, dict)
self.description = body["fields"]["description"]
return None
def teammate_saves(self, text: str) -> None:
self.description = fake_adf(text)
def puts(self) -> list[object]:
return [call[3] for call in self.calls if call[0] == "PUT"]
def fake_adf(text: str) -> dict[str, object]:
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
def fake_markdown(documents: list[dict[str, object]]) -> list[str]:
return [document["content"][0]["content"][0]["text"] for document in documents] # type: ignore[index]
+6
View File
@@ -1,5 +1,6 @@
"""A record as a read found it or a write left it, which every record backend gives.""" """A record as a read found it or a write left it, which every record backend gives."""
import dataclasses import dataclasses
import hashlib
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -7,3 +8,8 @@ class Held:
"""A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's.""" """A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's."""
text: str text: str
version: str | None = None version: str | None = None
def digest_of(text: str) -> str:
"""A fingerprint of a record's text or document, for a version a write names."""
return hashlib.sha256(text.encode("utf-8")).hexdigest()
+64 -16
View File
@@ -1,25 +1,31 @@
"""A project's goals and audience kept as the description of one Jira Cloud epic, read over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim. """A project's goals and audience kept as the description of one Jira Cloud epic, read and written over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim.
The store only reads: a write, such as `project-record save goals-and-audience`, fails, saying to edit the epic in Jira.""" Jira keeps no version of a description, so the version a read gives is a digest of the document, and a write refuses where the description no longer has that digest. A write changes ## Goals or ## Audience only where the store was told the human approved that section in an interrupt (`approved`)."""
import dataclasses import dataclasses
import json
import pathlib import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, Refused from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToMarkdown from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from record_store.held import digest_of, Held
from project_config.settings import Epic from project_config.settings import Epic
from failure import Failure from failure import Failure
from record_store.held import Held from text_files.markdown_text import sections
READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira" # The sections of the description a write changes only after the human approves.
APPROVED_SECTIONS = ("Goals", "Audience")
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class EpicDescription: class EpicDescription:
"""The description of epic as markdown, read with the credentials env_file holds.""" """The description of epic as markdown, read and written with the credentials env_file holds. approved names the APPROVED_SECTIONS whose change the human approved."""
epic: Epic epic: Epic
env_file: pathlib.Path env_file: pathlib.Path
http: Http = jira_json http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
approved: frozenset[str] = frozenset()
@property @property
def label(self) -> str: def label(self) -> str:
@@ -31,28 +37,70 @@ class EpicDescription:
def read(self) -> str | Failure: def read(self) -> str | Failure:
"""The description as markdown; empty where the epic has none.""" """The description as markdown; empty where the epic has none."""
held = self.held()
return held if isinstance(held, Failure) else held.text
def held(self) -> Held | Failure:
"""The description as markdown, with a digest of the document Jira holds as the version a write over it names."""
description = self.fetched()
if isinstance(description, Failure):
return description
text = "" if description is None else self.markdown_of(description)
return text if isinstance(text, Failure) else Held(text, digest_of(json.dumps(description, sort_keys=True)))
@property
def url(self) -> str:
return f"{self.epic.site}/rest/api/3/issue/{self.epic.key}"
def fetched(self) -> dict[str, typing.Any] | None | Failure:
"""The description as Jira holds it, an ADF document; None where the epic has none."""
authorization = basic_auth(self.env_file) authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure): if isinstance(authorization, Failure):
return authorization return authorization
key = self.epic.key key = self.epic.key
answer = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=description", authorization, None) answer = self.http("GET", self.url + "?fields=description", authorization, None)
if isinstance(answer, Failure): if isinstance(answer, Failure):
return Failure(f"cannot read the epic {key}: {answer.reason}") return Failure(f"cannot read the epic {key}: {answer.reason}")
fields = answer.get("fields") if isinstance(answer, dict) else None fields = answer.get("fields") if isinstance(answer, dict) else None
if not isinstance(fields, dict) or "description" not in fields or not isinstance(fields["description"], dict | None): if not isinstance(fields, dict) or "description" not in fields or not isinstance(fields["description"], dict | None):
return Failure(f"the epic {key} is not in the shape Jira Cloud's REST API version 3 documents: its description field is missing, or neither a document nor null") return Failure(f"the epic {key} is not in the shape Jira Cloud's REST API version 3 documents: its description field is missing, or neither a document nor null")
if fields["description"] is None: return fields["description"]
return ""
texts = self.to_markdown([fields["description"]]) def markdown_of(self, document: dict[str, typing.Any]) -> str | Failure:
key = self.epic.key
texts = self.to_markdown([document])
if isinstance(texts, Refused): if isinstance(texts, Refused):
return Failure(f"{key}'s description: {texts.failure.reason}") return Failure(f"{key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure): if isinstance(texts, Failure):
return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}") return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}")
return texts[0] return texts[0]
def held(self) -> Held | Failure:
text = self.read()
return text if isinstance(text, Failure) else Held(text)
def write(self, text: str, over: str | None) -> Held | Failure: def write(self, text: str, over: str | None) -> Held | Failure:
return Failure(READ_ONLY) """Replaces the description with text, over the version held() gave. A text that is the description as read leaves it as Jira holds it, since converting the markdown back would drop each block's localId and Jira's spacing paragraphs; any other text rewrites the whole description, which keeps only what markdown can hold. Jira checks no version, so the check of over is a read just before the request, and an edit a teammate saves between the two is overwritten."""
key = self.epic.key
current = self.held()
if isinstance(current, Failure):
return current
if over is not None and current.version != over:
return Failure(f"someone saved the description of {key} since the loop read it, so the loop didn't write it: never overwrite their edit, but ask the human what to do")
if text == current.text:
return current
document = self.to_adf(text) if text else None
if isinstance(document, Failure):
return Failure(f"cannot convert the text for {key}'s description to ADF: {document.reason}")
# The sections of the description Jira will hold, as the codec reads them: a heading spelt another way than `## Goals` still counts.
sent = "" if document is None else self.markdown_of(document)
if isinstance(sent, Failure):
return sent
before, after = sections(current.text), sections(sent)
if repeated := [name for name, bodies in after.items() if len(bodies) > max(1, len(before.get(name, [])))]:
return Failure(f"the write would repeat ## {repeated[0]} in {key}'s description, which locks that section for reads and writes: leave a heading out of the text, or edit the description in Jira")
if unapproved := [name for name in APPROVED_SECTIONS if name not in self.approved and after.get(name) != before.get(name)]:
return Failure(f"the write changes ## {unapproved[0]} of {key}'s description without the human's approval: have the human approve it in an interrupt, or edit the section in Jira")
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answer = self.http("PUT", self.url, authorization, {"fields": {"description": document}})
if isinstance(answer, Failure):
return Failure(f"cannot write the description of {key}: {answer.reason}")
return self.held()
+1 -1
View File
@@ -87,7 +87,7 @@ def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
def goals_store(config: ProjectConfig) -> RecordStore: def goals_store(config: ProjectConfig) -> RecordStore:
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads.""" """The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description. This store is built without an approval, so it refuses a change to the epic's ## Goals or ## Audience."""
if config.goals_epic is None: if config.goals_epic is None:
return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience")) return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience"))
# load refuses a config that names an epic and no env-file. # load refuses a config that names an epic and no env-file.
+37 -5
View File
@@ -80,18 +80,50 @@ class ConfluencePageTest(ConfluenceCase):
store = self.new_store() store = self.new_store()
held = store.held() held = store.held()
assert isinstance(held, Held), held assert isinstance(held, Held), held
self.assertEqual(store.write("- a decision\n", held.version), Held("- a decision\n", '{"version": 8, "title": "Decisions"}')) written = store.write("- a decision\n", held.version)
assert isinstance(written, Held), written
self.assertEqual(written.text, "- a decision\n")
self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}})) self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}}))
def test_saving_the_text_a_read_found_leaves_the_page_as_confluence_holds_it(self) -> None:
self.confluence.teammate_saves("- a decision\n")
value = self.confluence.value
held = self.new_store().held()
assert isinstance(held, Held), held
self.assertEqual(self.new_store().write(held.text, held.version), held)
self.assertNotIn("PUT", [call[0] for call in self.confluence.calls])
self.assertEqual(self.confluence.calls[-1], ("GET", URL, AUTHORIZATION, None))
self.assertEqual((self.confluence.version, self.confluence.value), (2, value))
def test_refuses_to_save_the_text_a_read_found_where_a_teammate_saved_since(self) -> None:
self.confluence.teammate_saves("- a decision\n")
held = self.new_store().held()
assert isinstance(held, Held), held
self.confluence.teammate_saves("- their decision\n")
written = self.new_store().write(held.text, held.version)
self.assertEqual(written, Failure(f"someone saved {PAGE.spelling} since the loop read version 2 of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do (Confluence holds version 3)"))
self.assertNotIn("PUT", [call[0] for call in self.confluence.calls])
self.assertEqual(self.new_store().read(), "- their decision\n")
def test_an_unedited_save_fails_where_the_pages_version_cannot_be_read(self) -> None:
held = self.new_store().held()
assert isinstance(held, Held), held
store = ConfluencePage(PAGE, self.env, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
self.assertEqual(store.write(held.text, held.version), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found"))
def test_saving_an_edited_text_writes_the_page(self) -> None:
self.confluence.teammate_saves("- a decision\n")
held = self.new_store().held()
assert isinstance(held, Held), held
self.assertIsInstance(self.new_store().write("- another decision\n", held.version), Held)
self.assertEqual(self.new_store().read(), "- another decision\n")
def test_refuses_to_overwrite_a_teammates_save_since_the_version_it_is_handed_and_says_to_ask_the_human(self) -> None: def test_refuses_to_overwrite_a_teammates_save_since_the_version_it_is_handed_and_says_to_ask_the_human(self) -> None:
held = self.new_store().held() held = self.new_store().held()
assert isinstance(held, Held), held assert isinstance(held, Held), held
self.confluence.teammate_saves("their edit\n") self.confluence.teammate_saves("their edit\n")
written = self.new_store().write("my edit\n", held.version) written = self.new_store().write("my edit\n", held.version)
assert isinstance(written, Failure), written self.assertEqual(written, Failure(f"someone saved {PAGE.spelling} since the loop read version 1 of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do (PUT /wiki/api/v2/pages/{PAGE.page_id} answered 409: Version must be incremented on update. Current version is: 2)"))
self.assertIn("someone saved", written.reason)
self.assertIn("ask the human", written.reason)
self.assertIn(PAGE.spelling, written.reason)
self.assertEqual(self.new_store().read(), "their edit\n") self.assertEqual(self.new_store().read(), "their edit\n")
def test_keeps_no_version_itself_so_a_read_never_moves_the_version_a_write_names(self) -> None: def test_keeps_no_version_itself_so_a_read_never_moves_the_version_a_write_names(self) -> None:
+167 -7
View File
@@ -9,10 +9,14 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic from project_config.settings import Epic
from record_store.jira_description import EpicDescription from record_store.jira_description import EpicDescription
from failure import Failure from failure import Failure
from record_store.fakes import fake_adf, fake_markdown, FakeJira
from record_store.held import Held
from record_store.contract import RecordStoreContract
from adf_codec.convert import Refused from adf_codec.convert import Refused
EPIC = Epic("https://acme.atlassian.net", "ABC-12") EPIC = Epic("https://acme.atlassian.net", "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
URL = "https://acme.atlassian.net/rest/api/3/issue/ABC-12"
GOALS = {"type": "doc", "version": 1, "content": [{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Goals"}]}]} GOALS = {"type": "doc", "version": 1, "content": [{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Goals"}]}]}
@@ -69,20 +73,176 @@ class EpicDescriptionTest(unittest.TestCase):
for markdown in (Refused(0, Failure("an unsupported node")), Failure("docker is not running")): for markdown in (Refused(0, Failure("an unsupported node")), Failure("docker is not running")):
with self.subTest(markdown): with self.subTest(markdown):
self.markdown = markdown self.markdown = markdown
found = self.store().read() for found in (self.store().read(), self.store().held()):
assert isinstance(found, Failure), found assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason) self.assertIn("ABC-12", found.reason)
def test_missing_credentials_fail(self) -> None: def test_missing_credentials_fail(self) -> None:
self.env.unlink() self.env.unlink()
self.assertIsInstance(self.store().read(), Failure) self.assertIsInstance(self.store().read(), Failure)
self.assertEqual(self.calls, []) self.assertEqual(self.calls, [])
def test_writing_fails_since_the_store_only_reads(self) -> None:
found = self.store().write("## Goals\n", None) class WriteCase(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.jira = FakeJira()
def new_store(self, approved: frozenset[str] = frozenset()) -> EpicDescription:
return EpicDescription(EPIC, self.env, self.jira.http, fake_markdown, fake_adf, approved)
class EpicDescriptionContract(WriteCase, RecordStoreContract):
pass
GOALS_AND_SCORING = "## Goals\n1. **Achieve:** Ship.\n\n## Audience\nMe.\n\n## Scoring\nValue.\n"
class EpicDescriptionWriteTest(WriteCase):
def held(self, text: str) -> Held:
self.jira.teammate_saves(text)
held = self.new_store().held()
assert isinstance(held, Held), held
return held
def test_writes_the_text_as_the_epics_description(self) -> None:
held = self.held(GOALS_AND_SCORING)
text = GOALS_AND_SCORING.replace("Value.", "Value, then risk.")
written = self.new_store().write(text, held.version)
assert isinstance(written, Held), written
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(text)}}])
put = next(call for call in self.jira.calls if call[0] == "PUT")
self.assertEqual(put[:3], ("PUT", URL, AUTHORIZATION))
self.assertEqual(written, self.new_store().held())
def test_writing_empty_text_clears_the_description(self) -> None:
held = self.held("## Decisions\n- one\n")
self.assertIsInstance(self.new_store().write("", held.version), Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": None}}])
def test_saving_the_text_a_read_found_leaves_the_description_as_jira_holds_it(self) -> None:
held = self.held(GOALS_AND_SCORING)
before = self.jira.description
self.assertEqual(self.new_store().write(held.text, held.version), held)
self.assertEqual(self.jira.puts(), [])
self.assertIs(self.jira.description, before)
def test_refuses_to_write_where_a_teammate_saved_since_the_read(self) -> None:
held = self.held(GOALS_AND_SCORING)
self.jira.teammate_saves("## Goals\n1. **Achieve:** Their goal.\n")
for text in (held.text, GOALS_AND_SCORING.replace("Value.", "Risk.")):
with self.subTest(text):
found = self.new_store().write(text, held.version)
assert isinstance(found, Failure), found
self.assertIn("someone saved", found.reason)
self.assertIn("ABC-12", found.reason)
self.assertEqual(self.jira.puts(), [])
self.assertEqual(self.new_store().read(), "## Goals\n1. **Achieve:** Their goal.\n")
def test_refuses_to_write_over_the_version_of_an_epic_that_had_no_description(self) -> None:
held = self.new_store().held()
assert isinstance(held, Held), held
self.jira.teammate_saves("## Goals\nTheirs.\n")
found = self.new_store(frozenset({"Goals"})).write("## Goals\nMine.\n", held.version)
assert isinstance(found, Failure), found assert isinstance(found, Failure), found
self.assertIn("Jira", found.reason) self.assertIn("someone saved", found.reason)
self.assertEqual(self.calls, []) self.assertEqual(self.jira.puts(), [])
def test_refuses_to_change_goals_or_audience_before_the_human_approves(self) -> None:
held = self.held(GOALS_AND_SCORING)
changes = [
("Goals", GOALS_AND_SCORING.replace("Ship.", "Ship less.")),
("Audience", GOALS_AND_SCORING.replace("Me.", "Everyone.")),
("Goals", GOALS_AND_SCORING.replace("## Goals\n1. **Achieve:** Ship.\n\n", "")),
]
for name, text in changes:
with self.subTest(name, text=text):
found = self.new_store().write(text, held.version)
assert isinstance(found, Failure), found
self.assertIn(name, found.reason)
self.assertIn("approval", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_counts_a_heading_the_codec_reads_as_goals_even_where_the_markdown_spells_it_another_way(self) -> None:
held = self.held("## Scoring\nValue.\n")
as_atx = lambda documents: [fake_markdown(documents)[0].replace("Goals\n=====", "## Goals")]
store = EpicDescription(EPIC, self.env, self.jira.http, as_atx, fake_adf)
found = store.write("Goals\n=====\nShip.\n\n## Scoring\nValue.\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("## Goals", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_refuses_a_write_that_repeats_a_section_the_codec_reads_from_another_spelling_of_its_heading(self) -> None:
held = self.held("## Decisions\n- one\n")
as_atx = lambda documents: [fake_markdown(documents)[0].replace("Decisions\n=====", "## Decisions")]
store = EpicDescription(EPIC, self.env, self.jira.http, as_atx, fake_adf)
found = store.write("## Decisions\n- one\n\n## Scoring\nValue.\n\nDecisions\n=====\n- copied\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("repeat ## Decisions", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_keeps_a_section_that_was_already_repeated_in_the_description(self) -> None:
held = self.held("## Decisions\n- one\n\n## Decisions\n- two\n")
written = self.new_store().write("## Decisions\n- one\n\n## Decisions\n- two\n\n## Scoring\nValue.\n", held.version)
self.assertIsInstance(written, Held)
def test_the_version_does_not_depend_on_the_order_of_the_documents_keys(self) -> None:
held = self.held("## Scoring\nValue.\n")
self.jira.description = dict(reversed(list(fake_adf("## Scoring\nValue.\n").items())))
self.assertEqual(self.new_store().held(), held)
def test_refuses_to_write_where_a_teammate_saved_a_change_the_markdown_does_not_show(self) -> None:
held = self.held("## Scoring\nValue.\n")
self.jira.description = {**fake_adf("## Scoring\nValue.\n"), "localId": "teammate"}
found = self.new_store().write("## Scoring\nRisk.\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("someone saved", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_refuses_to_add_a_goals_section_before_the_human_approves(self) -> None:
held = self.held("## Scoring\nValue.\n")
found = self.new_store().write("## Goals\n1. **Achieve:** Ship.\n\n## Scoring\nValue.\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("Goals", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_changes_goals_once_the_human_approved_that_section_only(self) -> None:
held = self.held(GOALS_AND_SCORING)
both = GOALS_AND_SCORING.replace("Ship.", "Ship less.").replace("Me.", "Everyone.")
found = self.new_store(frozenset({"Goals"})).write(both, held.version)
assert isinstance(found, Failure), found
self.assertIn("Audience", found.reason)
self.assertNotIn("Goals", found.reason)
self.assertEqual(self.jira.puts(), [])
written = self.new_store(frozenset({"Goals", "Audience"})).write(both, held.version)
self.assertIsInstance(written, Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(both)}}])
def test_changes_scoring_and_decisions_without_approval(self) -> None:
held = self.held(GOALS_AND_SCORING)
text = GOALS_AND_SCORING.replace("Value.", "Risk.") + "\n## Decisions\n- A choice.\n"
self.assertIsInstance(self.new_store().write(text, held.version), Held)
self.assertEqual(self.jira.puts(), [{"fields": {"description": fake_adf(text)}}])
def test_a_text_the_codec_cannot_convert_is_not_sent(self) -> None:
held = self.held("## Decisions\n- one\n")
store = EpicDescription(EPIC, self.env, self.jira.http, fake_markdown, lambda text: Failure("unsupported markdown"))
found = store.write("## Decisions\n- two\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("unsupported markdown", found.reason)
self.assertEqual(self.jira.puts(), [])
def test_a_refused_request_fails_naming_the_epic(self) -> None:
held = self.held("## Decisions\n- one\n")
refusing = lambda method, url, authorization, body: Failure("HTTP 403: no permission") if method == "PUT" else self.jira.http(method, url, authorization, body)
found = EpicDescription(EPIC, self.env, refusing, fake_markdown, fake_adf).write("## Decisions\n- two\n", held.version)
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("HTTP 403", found.reason)
if __name__ == "__main__": if __name__ == "__main__":
+11 -3
View File
@@ -45,6 +45,11 @@ replay, and runs no SubagentStart hook there. So the replay without CLAUDE.md tu
instruction files off in its settings and opens the prompt with what the hook hands a reviewer, and instruction files off in its settings and opens the prompt with what the hook hands a reviewer, and
closes it with the header's line on the project principles. closes it with the header's line on the project principles.
It keeps each run, a reviewer's tool calls included, and the report it prints in loop-claude's archive, in
replays/review-replay-<pass>-<model>[-omit-claude-md]-<UTC stamp>/ under ~/.claude/loop-claude-transcripts
or $LOOP_CLAUDE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working
directory, prompt, exit code and stderr, then holds claude's stream-json output; result.md holds the report.
Like the loop, it tries claude three times running before it counts a reply as failed. A failed Like the loop, it tries claude three times running before it counts a reply as failed. A failed
review or match leaves its round out, except on a rung below the project's, where it finds review or match leaves its round out, except on a rung below the project's, where it finds
none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived
@@ -56,6 +61,7 @@ import typing
from transcript_archive.location import archive_root from transcript_archive.location import archive_root
from review_replay.rounds import archived_rounds, Round, sample from review_replay.rounds import archived_rounds, Round, sample
from rung_replay.archive import archiving, print_report, replay_folder
from rung_replay.command import arguments_or_exit, failed, limited_exit from rung_replay.command import arguments_or_exit, failed, limited_exit
from review_replay.replay import codes_found, findings_replayed from review_replay.replay import codes_found, findings_replayed
from review_replay.omit_comparison import compared from review_replay.omit_comparison import compared
@@ -89,11 +95,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
if not codes: if not codes:
return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find") return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
chosen = sample(list(codes), LATEST) chosen = sample(list(codes), LATEST)
folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now())
effects = archiving(effects, folder)
if without: if without:
report = compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare)) report = compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare))
if isinstance(report, Limited): if isinstance(report, Limited):
return limited_exit(TOOL, report) return limited_exit(TOOL, report)
print(report) print_report(folder, report)
return 0 return 0
def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited: def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited:
@@ -105,7 +113,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds") recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds")
if isinstance(recall, Limited): if isinstance(recall, Limited):
return limited_exit(TOOL, recall) return limited_exit(TOOL, recall)
print(recall_report(reviewed, project, recall)) print_report(folder, recall_report(reviewed, project, recall))
return 0 return 0
@@ -115,4 +123,4 @@ def pass_and_model(ladder: Ladder, argv: list[str]) -> tuple[ReviewedPass, Rung,
return None return None
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None) reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
project = ladder.project_rung(argv[1]) project = ladder.project_rung(argv[1])
return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None return (reviewed, project.rung, argv[2:] == [OMIT]) if reviewed and project else None
+8 -1
View File
@@ -16,6 +16,7 @@ from rung_replay.search import first_reply
from record_store.stores import local_file, store from record_store.stores import local_file, store
from project_config.main import located from project_config.main import located
from review_rules.reviewer_context import principles_line, reviewer_context from review_rules.reviewer_context import principles_line, reviewer_context
from text_files.compressed import read_stored, SUFFIX
from review_rules.review_folder import REPORTS, review_folder from review_rules.review_folder import REPORTS, review_folder
from model_routing.ladder import Rung from model_routing.ladder import Rung
from claude_code.entries import structured_output from claude_code.entries import structured_output
@@ -146,8 +147,14 @@ def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
"""Copies into reports each report written to folder after found's chunk began and before its round did.""" """Copies into reports each report written to folder after found's chunk began and before its round did."""
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find. # The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
for written in folder.iterdir() if folder.is_dir() else (): for written in folder.iterdir() if folder.is_dir() else ():
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds: if not written.is_file() or not found.began <= written.stat().st_mtime < found.seconds:
continue
name = written.name.removesuffix(SUFFIX)
if name == written.name:
shutil.copy2(written, reports) shutil.copy2(written, reports)
# A gzipped report. Where a plain report of the same name stands beside it, that one is newer and the gzip is skipped; the plain report is copied only if it was written before the round.
elif not (folder / name).is_file():
(pathlib.Path(reports) / name).write_bytes(read_stored(folder / name))
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure: def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
+3 -2
View File
@@ -11,6 +11,7 @@ from transcript_archive.project_key import checkout_of
from failure import Failure from failure import Failure
from claude_code.transcript import first_timestamped_line, read_transcript from claude_code.transcript import first_timestamped_line, read_transcript
from rung_replay.command import projects_on from rung_replay.command import projects_on
from text_files.compressed import read_stored, stored_glob
# A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them. # A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them.
FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)") FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)")
@@ -126,8 +127,8 @@ def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]: def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
copies = sorted(chunk.glob("*.jsonl")) copies = stored_glob(chunk, "*.jsonl")
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None began = parse_entry(first_timestamped_line(read_stored(copies[0]))) if copies else None
if not began or not began.timestamp: if not began or not began.timestamp:
return [] return []
found = [] found = []
+39 -4
View File
@@ -15,6 +15,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds
from text_files import compressed
from project_config.test_project_config import configured, write_config from project_config.test_project_config import configured, write_config
from loop_effects.effects import Effects, system_effects from loop_effects.effects import Effects, system_effects
from claude_code.entries import entry_from from claude_code.entries import entry_from
@@ -267,12 +268,22 @@ class Main(unittest.TestCase):
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
return subprocess.CompletedProcess(args, 0, json.dumps(result), "") return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
out, err = io.StringIO(), io.StringIO() out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects) code = main.main(argv, {}, self.home, effects)
return code, out.getvalue(), err.getvalue() return code, out.getvalue(), err.getvalue()
def test_keeps_each_reviewer_and_match_run_and_the_printed_report_in_one_folder_of_the_archive(self):
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
self.assertEqual(code, 0, err)
folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "review-replay-stability-claude-opus-5-5-20260921T141320Z"
self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out)
runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")]
# A run that repeats another word for word, as the fakes' do, is kept once.
self.assertEqual({run["prompt"] for run in runs if "--agent" in run["args"]}, {prompt for *_, prompt, _ in self.reviews})
self.assertTrue(any("--json-schema" in run["args"] for run in runs))
def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self): def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self):
finds = iter(([0, 1], [0], [0, 1], [1])) finds = iter(([0, 1], [0], [0, 1], [1]))
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)}) code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)})
@@ -365,19 +376,43 @@ class Main(unittest.TestCase):
self.assertIn("claude-opus-5-5 at low effort found 0, 0%, and missed 1 such 🔴: it doesn't qualify.", out) self.assertIn("claude-opus-5-5 at low effort found 0, 0%, and missed 1 such 🔴: it doesn't qualify.", out)
def review_folder_with_round_1(self): def review_folder_with_round_1(self):
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15.""" """The chunk's review folder. The chunk began at 09:15 and the replayed round 2 at 10:00. It holds round 1's report, written at 09:15:00; round 2's report, written after 10:00; the prose pass's report, written at 10:00:00; and an earlier attempt's report, from before 09:15."""
folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x" folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x"
folder.mkdir(parents=True) folder.mkdir(parents=True)
(folder / "stability-round-1.md").write_text("round 1\n") (folder / "stability-round-1.md").write_text("round 1\n")
before = stamp_seconds("2026-10-14T09:50:00Z") began = stamp_seconds("2026-10-14T09:15:00Z")
os.utime(folder / "stability-round-1.md", (before, before)) os.utime(folder / "stability-round-1.md", (began, began))
(folder / "stability-round-2.md").write_text("🔴 a.txt:1 wrong\n") (folder / "stability-round-2.md").write_text("🔴 a.txt:1 wrong\n")
(folder / "prose-round-1.md").write_text("later\n") (folder / "prose-round-1.md").write_text("later\n")
round_began = stamp_seconds("2026-10-14T10:00:00Z")
os.utime(folder / "prose-round-1.md", (round_began, round_began))
(folder / "stability-round-3.md").write_text("🔴 a.txt:1 wrong\n") (folder / "stability-round-3.md").write_text("🔴 a.txt:1 wrong\n")
attempt = stamp_seconds("2026-10-14T09:00:00Z") attempt = stamp_seconds("2026-10-14T09:00:00Z")
os.utime(folder / "stability-round-3.md", (attempt, attempt)) os.utime(folder / "stability-round-3.md", (attempt, attempt))
return folder return folder
def test_replays_rounds_whose_archived_transcripts_are_compressed(self):
for copy in self.archive.rglob("*.jsonl"):
self.assertIsNone(compressed.compress(copy))
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [1] if rung == LOW else [0, 1]})
self.assertEqual(code, 0, err)
self.assertTrue(out.startswith("Replayed 1 stability rounds of claude-opus-5-5 projects,"), out)
def test_copies_a_compressed_report_from_before_the_round_under_its_plain_name(self):
folder = self.review_folder_with_round_1()
self.assertIsNone(compressed.compress(folder / "stability-round-1.md"))
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.")
seen = []
def review(rung):
named = pathlib.Path(re.search(r"report to (\S+)/stability-round-2\.md", self.reviews[-1][4]).group(1))
seen.append((sorted(path.name for path in named.iterdir()), (named / "stability-round-1.md").read_text()))
return {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review)
self.assertEqual(code, 0, err)
self.assertEqual(seen[0], (["stability-round-1.md"], "round 1\n"))
def test_points_the_prompts_review_folder_at_a_copy_of_the_reports_from_before_the_round_that_it_removes(self): def test_points_the_prompts_review_folder_at_a_copy_of_the_reports_from_before_the_round_that_it_removes(self):
folder = self.review_folder_with_round_1() folder = self.review_folder_with_round_1()
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.") self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.")
+33
View File
@@ -3,6 +3,7 @@ import os
import pathlib import pathlib
from failure import Failure from failure import Failure
from review_rules.round_titles import Findings, reported
# Why here: docs/decisions.md → `review: each reviewer under agents/ writes its full report into the chunk's review folder`. # Why here: docs/decisions.md → `review: each reviewer under agents/ writes its full report into the chunk's review folder`.
REPORTS = ".local/state/larv-review" REPORTS = ".local/state/larv-review"
@@ -24,3 +25,35 @@ def made_review_folder(worktree: str, home: pathlib.Path) -> pathlib.Path | Fail
except OSError as failure: except OSError as failure:
return Failure(f"could not make the review folder {folder}: {failure}") return Failure(f"could not make the review folder {folder}: {failure}")
return folder return folder
def round_report(folder: pathlib.Path, pass_: str, round_: int) -> pathlib.Path:
"""The report of pass_'s round round_ in the review folder, which asks for the rerun one rung up where there is one."""
return folder / f"{pass_}-round-{round_}.md"
def rerun_report(asked: pathlib.Path) -> pathlib.Path:
"""The report of the rerun one rung up that `asked` asks for. It stands in place of `asked`."""
return asked.with_name(asked.stem + "-rerun.md")
def standing_report(folder: pathlib.Path, pass_: str, round_: int) -> pathlib.Path:
"""The report that stands for pass_'s round round_ in the review folder: the rerun's where there is one, else the round's."""
asked = round_report(folder, pass_, round_)
return rerun_report(asked) if rerun_report(asked).exists() else asked
def findings_in(report: pathlib.Path) -> Findings | Failure:
"""The findings a round's report gives, as round_titles.reported counts them; a Failure where the report blocks yet heads no finding as review-findings.md → "Report" asks, since its count would then be wrong."""
try:
text = report.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"no report at {report}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {report}: {failure}")
findings = reported(text)
if isinstance(findings, Failure):
return Failure(f"{report} cannot be counted: {findings.reason}; count its findings by hand")
if text.lstrip().startswith("BLOCK") and findings.red + findings.yellow == 0:
return Failure(f"{report} says BLOCK but opens no finding with `### 🔴` or `### 🟡`; count its findings by hand")
return findings
+20 -1
View File
@@ -1,7 +1,8 @@
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); <summary>`: each pass's round count against its cap, and the findings the rounds reported. <j> counts the 🔴 and 🟡 findings a reviewer marked `[misread]`.""" """The titles of larv-review's round commits, `Answer <pass> round <n>: <k> 🔴, <m> 🟡 (<j> misread); <summary>`: each pass's round count against its cap, and the findings each round reported, as its title counts them and as its report does. <j> counts the 🔴 and 🟡 findings a reviewer marked `[misread]`."""
import dataclasses import dataclasses
import re import re
from failure import Failure
from review_rules.review_passes import PASSES from review_rules.review_passes import PASSES
# The most rounds a pass takes per chunk, per `docs/decisions.md` → `review: a pass gets at most two rounds per chunk, …`. rule-hook's `round-cap` refuses a round commit that `past_cap` finds takes its pass past it, and `larv-review round-count` marks a pass that reached it. # The most rounds a pass takes per chunk, per `docs/decisions.md` → `review: a pass gets at most two rounds per chunk, …`. rule-hook's `round-cap` refuses a round commit that `past_cap` finds takes its pass past it, and `larv-review round-count` marks a pass that reached it.
@@ -16,6 +17,9 @@ EXAMPLE = "Answer stability round 1: 1 🔴, 2 🟡 (1 misread); flag a deleted
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE) ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then how many of them a reviewer marked `[misread]`, a count that titles from before it lack, then `;` and its summary, if any. # What follows a round title's colon: the round's 🔴 and 🟡 counts, then how many of them a reviewer marked `[misread]`, a count that titles from before it lack, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?: \(([0-9]+) misread\))?(?:;|$)") FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?: \(([0-9]+) misread\))?(?:;|$)")
# A 🔴 or 🟡 finding's heading in a round's report, as skills/larv-review/review-findings.md → "Report" pins it: `### `, the severity mark, then ` [misread]` where the reviewer marked it so.
FINDING = re.compile(r"^### (🔴|🟡)( \[misread\])?", re.MULTILINE)
HEADING = re.compile(r"^#{1,6} .*$", re.MULTILINE)
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -93,3 +97,18 @@ def round_findings(titles: list[str]) -> Findings | None:
return None return None
misreads = [found.misread for found in counts if found.misread is not None] misreads = [found.misread for found in counts if found.misread is not None]
return Findings(sum(found.red for found in counts), sum(found.yellow for found in counts), sum(misreads) if len(misreads) == len(counts) else None) return Findings(sum(found.red for found in counts), sum(found.yellow for found in counts), sum(misreads) if len(misreads) == len(counts) else None)
def reported(report: str) -> Findings | Failure:
"""The 🔴 and 🟡 findings a round's report gives in FINDING headings, and how many of them the reviewer marked `[misread]`; a Failure naming a heading that holds a 🔴 or 🟡 in another form, which a count would miss."""
for heading in HEADING.findall(report):
pinned = FINDING.match(heading)
if ("🔴" in heading or "🟡" in heading) and (not pinned or "[misread]" in heading and not pinned.group(2)):
return Failure(f"its heading `{heading}` holds a 🔴 or 🟡 but doesn't open `### 🔴` or `### 🟡`, followed by ` [misread]` where marked so")
marks = FINDING.findall(report)
return Findings(sum(mark == "🔴" for mark, _ in marks), sum(mark == "🟡" for mark, _ in marks), sum(bool(misread) for _, misread in marks))
def round_prefix(pass_: str, round_: int, findings: Findings) -> str:
"""The opening of the round's commit title, up to and including the `;` before its summary."""
return f"Answer {pass_} round {round_}: {findings.red} 🔴, {findings.yellow} 🟡 ({findings.misread} misread);"
+46 -1
View File
@@ -1,10 +1,13 @@
import pathlib import pathlib
import sys import sys
import tempfile
import unittest import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_rules.review_folder import review_folder from failure import Failure
from review_rules.round_titles import Findings
from review_rules.review_folder import findings_in, review_folder, standing_report
class ReviewFolder(unittest.TestCase): class ReviewFolder(unittest.TestCase):
@@ -14,3 +17,45 @@ class ReviewFolder(unittest.TestCase):
def test_keys_a_worktree_outside_home_by_its_path_relative_to_the_root(self): def test_keys_a_worktree_outside_home_by_its_path_relative_to_the_root(self):
self.assertEqual(review_folder("/h", "/srv/proj-item-3"), "/h/.local/state/larv-review/srv/proj-item-3") self.assertEqual(review_folder("/h", "/srv/proj-item-3"), "/h/.local/state/larv-review/srv/proj-item-3")
self.assertEqual(review_folder("/h", "/hx/proj"), "/h/.local/state/larv-review/hx/proj", "a sibling of home that shares its prefix is outside it") self.assertEqual(review_folder("/h", "/hx/proj"), "/h/.local/state/larv-review/hx/proj", "a sibling of home that shares its prefix is outside it")
class RoundReport(unittest.TestCase):
def test_counts_the_rounds_report_or_its_rerun_one_rung_up_where_there_is_one(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
(folder / "prose-round-1.md").write_text("BLOCK\n\n### 🟡 a\n")
self.assertEqual(findings_in(standing_report(folder, "prose", 1)), Findings(0, 1, 0))
(folder / "prose-round-1-rerun.md").write_text("BLOCK\n\n### 🔴 [misread] a\n")
self.assertEqual(findings_in(standing_report(folder, "prose", 1)), Findings(1, 0, 1))
(folder / "prose-round-1-rerun.md").write_text("BLOCK\n\n### 🔴 a\n\n### 🟡 b\n")
self.assertEqual(findings_in(standing_report(folder, "prose", 1)), Findings(1, 1, 0))
def test_names_a_missing_report(self):
with tempfile.TemporaryDirectory() as temp:
missing = findings_in(standing_report(pathlib.Path(temp), "prose", 2))
self.assertIsInstance(missing, Failure)
self.assertEqual(missing.reason, f"no report at {temp}/prose-round-2.md")
def test_names_a_report_it_cannot_read(self):
with tempfile.TemporaryDirectory() as temp:
(pathlib.Path(temp) / "prose-round-1.md").mkdir()
unread = findings_in(standing_report(pathlib.Path(temp), "prose", 1))
self.assertIsInstance(unread, Failure)
self.assertTrue(unread.reason.startswith(f"could not read {temp}/prose-round-1.md: "), unread.reason)
def test_names_a_blocking_report_that_heads_no_finding_as_its_format_asks(self):
with tempfile.TemporaryDirectory() as temp:
(pathlib.Path(temp) / "prose-round-1.md").write_text("\nBLOCK\n\n- 🟡 `a.md:1`: worse\n")
unread = findings_in(standing_report(pathlib.Path(temp), "prose", 1))
self.assertIsInstance(unread, Failure)
self.assertEqual(unread.reason, f"{temp}/prose-round-1.md says BLOCK but opens no finding with `### 🔴` or `### 🟡`; count its findings by hand")
(pathlib.Path(temp) / "prose-round-1.md").write_text("APPROVE\n")
self.assertEqual(findings_in(standing_report(pathlib.Path(temp), "prose", 1)), Findings(0, 0, 0))
def test_names_a_report_whose_headings_it_cannot_count(self):
with tempfile.TemporaryDirectory() as temp:
(pathlib.Path(temp) / "prose-round-1.md").write_text("BLOCK\n\n### 1. 🟡 `a.md:1`: worse\n")
unread = findings_in(standing_report(pathlib.Path(temp), "prose", 1))
self.assertIsInstance(unread, Failure)
self.assertTrue(unread.reason.startswith(f"{temp}/prose-round-1.md cannot be counted: its heading `### 1. 🟡"), unread.reason)
self.assertTrue(unread.reason.endswith("; count its findings by hand"), unread.reason)
+23 -1
View File
@@ -4,7 +4,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_rules.round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings, rounds_past_first from failure import Failure
from review_rules.round_titles import Findings, lacks_counts, past_cap, reported, round_counts, round_findings, round_prefix, rounds_past_first, title_counts
class Rounds(unittest.TestCase): class Rounds(unittest.TestCase):
@@ -79,5 +80,26 @@ class RoundFindings(unittest.TestCase):
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 (4 misread); fix"])) self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 (4 misread); fix"]))
class Reported(unittest.TestCase):
REPORT = "BLOCK\n\n### 🔴 [misread] `a.py:1` `f`: wrong\n\n### 🟡 `b.py:2`: worse\n\n### 🟡 [misread] `c.py:3`: worse\n\n### 🟢 `d.py:4`: nit\n\n### ❓ `e.py:5`: why\n\n- 🔴 `a.py:1` `f`: wrong, as the reply lists it\nText naming 🔴 and [misread].\n"
def test_counts_the_findings_whose_heading_opens_with_their_mark(self):
self.assertEqual(reported(self.REPORT), Findings(1, 2, 2))
def test_counts_none_in_a_report_without_findings(self):
self.assertEqual(reported("APPROVE\n\nNothing found.\n"), Findings(0, 0, 0))
def test_spells_the_title_prefix_a_round_commit_opens_with(self):
self.assertEqual(round_prefix("prose", 2, Findings(1, 2, 0)), "Answer prose round 2: 1 🔴, 2 🟡 (0 misread);")
self.assertEqual(title_counts(round_prefix("prose", 2, Findings(1, 2, 1))), Findings(1, 2, 1), "the prefix parses as the counts it spells")
def test_counts_none_of_a_report_whose_headings_hold_a_mark_in_another_form(self):
for heading in ["### 1. 🟡 `a.py:1`: worse", "## 🔴 Must fix", "#### 🟡 a sub-heading", "### 🟡 `a.py:1`: worse [misread]"]:
with self.subTest(heading):
unread = reported(f"BLOCK\n\n### 🔴 `b.py:2`: wrong\n\n{heading}\n")
self.assertIsInstance(unread, Failure)
self.assertEqual(unread.reason, f"its heading `{heading}` holds a 🔴 or 🟡 but doesn't open `### 🔴` or `### 🟡`, followed by ` [misread]` where marked so")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+3 -2
View File
@@ -3,6 +3,7 @@ import contextlib
import dataclasses import dataclasses
import fcntl import fcntl
import functools import functools
import io
import json import json
import pathlib import pathlib
import typing import typing
@@ -15,6 +16,7 @@ from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Subagent
from git_cli.git_repo import default_ref, Git from git_cli.git_repo import default_ref, Git
from claude_code.entries import Entry, parse_entry from claude_code.entries import Entry, parse_entry
from failure import Failure from failure import Failure
from text_files.compressed import read_stored
from text_files.file_writes import replace_file from text_files.file_writes import replace_file
from project_config.main import title_templates from project_config.main import title_templates
from project_config.templates import Titles from project_config.templates import Titles
@@ -115,8 +117,7 @@ def branch_history(checkout: str, home: pathlib.Path, titles: Titles, git: Git)
def entries(path: pathlib.Path) -> list[Entry]: def entries(path: pathlib.Path) -> list[Entry]:
with open(path, "rb") as handle: return [entry for line in io.BytesIO(read_stored(path)) if (entry := parse_entry(line))]
return [entry for line in handle if (entry := parse_entry(line))]
def subagent(transcript: pathlib.Path) -> Subagent: def subagent(transcript: pathlib.Path) -> Subagent:
@@ -19,6 +19,7 @@ from project_config.templates import BARE, Titles
from branch_chunks.cut import BranchChunk from branch_chunks.cut import BranchChunk
from routing_figures.calls import Call, calls, totals from routing_figures.calls import Call, calls, totals
from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent
from text_files import compressed
from project_config.test_project_config import configured, write_config from project_config.test_project_config import configured, write_config
from routing_figures.state import due from routing_figures.state import due
from claude_code.entries import entry_from from claude_code.entries import entry_from
@@ -352,6 +353,13 @@ class Archive(unittest.TestCase):
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ())) self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ()))
def test_measures_a_chunk_whose_transcripts_are_compressed(self):
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
for copy in self.root.rglob("*.jsonl"):
self.assertIsNone(compressed.compress(copy))
found = archive.measure_archive(self.root, "/h", "", no_checkout)
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self): def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self):
home = self.root / "home" home = self.root / "home"
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)} env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)}
+1 -1
View File
@@ -1,6 +1,6 @@
"""Whether a Read or a Grep reads a credentials file, or a Bash command names it or searches a folder holding it, for the `env-file-read` rule. """Whether a Read or a Grep reads a credentials file, or a Bash command names it or searches a folder holding it, for the `env-file-read` rule.
The files are `~/.claude/.env` and every config's `env-file`, not only the calling project's: a worker in one client's project must not read another client's credentials either, and listing every config's file needs no git call, as finding the calling project's would. The files are `~/.claude/.env` and every config's `env-file`, do-epic's included, not only the calling project's: a worker in one client's project must not read another client's credentials either, and listing every config's file needs no git call, as finding the calling project's would.
A Bash command names one where its text spells the file's path, or one of its words, a redirect's target included, leads to the file from the directory `cd` left the command in. Whether the command reads the file is not judged, so one that only mentions the path is refused too. A Bash command names one where its text spells the file's path, or one of its words, a redirect's target included, leads to the file from the directory `cd` left the command in. Whether the command reads the file is not judged, so one that only mentions the path is refused too.
It searches a folder holding one where `folder_search.searches` finds that an `ag`, `grep -r` or `rg` reaches the file. It searches a folder holding one where `folder_search.searches` finds that an `ag`, `grep -r` or `rg` reaches the file.
This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob, a variable of its own, `xargs` or `find -exec`.""" This guards against an agent reading the file in passing, not against one that hides the path, such as behind a glob, a variable of its own, `xargs` or `find -exec`."""
+2 -1
View File
@@ -57,6 +57,7 @@ from rule_hook.repeat_read import read_breaches
from rule_hook.reviewer_report import report_breaches from rule_hook.reviewer_report import report_breaches
from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches from rule_hook.reviewer_rung import reviewer_breaches, skill_breaches
from rule_hook.round_cap import round_cap_breaches from rule_hook.round_cap import round_cap_breaches
from rule_hook.round_report import round_report_breaches
from command_lines.shell_command import simple_commands from command_lines.shell_command import simple_commands
from project_config import templates from project_config import templates
from rule_hook.todo_check import todo_breaches from rule_hook.todo_check import todo_breaches
@@ -142,7 +143,7 @@ def commit_breaches(commit: CommitCall, home: pathlib.Path) -> list[Breach]:
titles = config.titles if isinstance(config, ProjectConfig) else templates.BARE titles = config.titles if isinstance(config, ProjectConfig) else templates.BARE
# A checkout no config names has no branch template, so no title of its must fit one. # A checkout no config names has no branch template, so no title of its must fit one.
branch = checkout_branch(commit.directory) if isinstance(config, ProjectConfig) else None branch = checkout_branch(commit.directory) if isinstance(config, ProjectConfig) else None
return unread + title_breaches(commit, titles, config.branch if isinstance(config, ProjectConfig) else templates.BRANCH, branch) + round_cap_breaches(commit, titles) + todo_breaches(commit.directory, home) return unread + title_breaches(commit, titles, config.branch if isinstance(config, ProjectConfig) else templates.BRANCH, branch) + round_cap_breaches(commit, titles) + round_report_breaches(commit, titles, home) + todo_breaches(commit.directory, home)
def checkout_branch(directory: str) -> str | None: def checkout_branch(directory: str) -> str | None:
+4 -4
View File
@@ -36,7 +36,7 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str)
project, worker, escape_and_impact = handed(environ, ladder) project, worker, escape_and_impact = handed(environ, ladder)
if project is None or worker is None: if project is None or worker is None:
return [] return []
required = ladder.review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd)) required = project.review_rung(worker, escape_and_impact, kind, markdown_only(call.cwd))
named = named_rung(call.given, worker, ladder) named = named_rung(call.given, worker, ladder)
if ladder.position(named) >= ladder.position(required): if ladder.position(named) >= ladder.position(required):
return [] return []
@@ -62,10 +62,10 @@ def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) ->
project, worker, _ = handed(environ, ladder) project, worker, _ = handed(environ, ladder)
if project is None or worker is None: if project is None or worker is None:
return [] return []
if not call.subagent and ladder.position(worker) >= ladder.position(project): if not call.subagent and ladder.position(worker) >= ladder.position(project.rung):
return [] return []
runs_on = "on a rung rule-hook cannot see" if call.subagent else f"in this context on {worker}, below {project}" runs_on = "on a rung rule-hook cannot see" if call.subagent else f"in this context on {worker}, below {project.rung}"
return [Breach("reviewer-rung", f"{skill} would run {runs_on}: invoke it from a subagent launched with {project.agent_args()}, its prompt opening with `{SECURITY_OPENER}`", call.cwd)] return [Breach("reviewer-rung", f"{skill} would run {runs_on}: invoke it from a subagent launched with {project.rung.agent_args()}, its prompt opening with `{SECURITY_OPENER}`", call.cwd)]
def opening_prompt(transcript: str) -> str: def opening_prompt(transcript: str) -> str:
+30
View File
@@ -0,0 +1,30 @@
"""rule-hook's check of a round commit's counts against the round's report in the chunk's review folder."""
import pathlib
from rule_hook.rules import Breach
from git_cli.git_command import CommitCall
from failure import Failure
from review_rules.review_folder import findings_in, review_folder, standing_report
from git_cli.git_repo import git
from review_rules.round_titles import ROUND, round_prefix, title_counts
from project_config.templates import Titles
def round_report_breaches(commit: CommitCall, titles: Titles, home: pathlib.Path) -> list[Breach]:
"""A breach for each round title whose counts differ from those its round's report gives. The round title is the commit title's summary, as `titles` cuts it. A title without all three counts is title_breaches' to refuse. A round whose report is missing or unreadable, or says BLOCK without a finding heading, goes through, as does every round where git cannot name the commit's checkout within 5 seconds."""
summaries = [titles.summary(message.strip()) for message in commit.messages]
rounds = [(named, counts) for summary in summaries if (named := ROUND.match(summary)) and (counts := title_counts(summary)) and counts.misread is not None]
if not rounds:
return []
worktree = git("rev-parse", "--show-toplevel", cwd=commit.directory, timeout=5, guarded=True)
if isinstance(worktree, Failure):
return []
folder = pathlib.Path(review_folder(str(home), worktree.strip()))
breaches = []
for named, counts in rounds:
pass_, round_ = named.group(1).lower(), int(named.group(2))
report = standing_report(folder, pass_, round_)
found = findings_in(report)
if not isinstance(found, Failure) and found != counts:
breaches.append(Breach("round-title-counts", f"{report} counts `{round_prefix(pass_, round_, found)}`; open the title's summary with that, which `larv-review round-title {pass_}` prints", commit.directory))
return breaches
+1 -1
View File
@@ -84,7 +84,7 @@ RULES: dict[RuleName, Rule] = {
), ),
"round-title-counts": Rule( "round-title-counts": Rule(
f"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, and how many of them a reviewer marked `[misread]`, at most the two together, such as `{EXAMPLE}`, since score-outcomes counts them", f"a larv-review round's commit title gives the counts of 🔴 and 🟡 findings the round reported, and how many of them a reviewer marked `[misread]`, at most the two together, such as `{EXAMPLE}`, since score-outcomes counts them",
f"a git commit whose message opens `{OPENING}`", f"a git commit whose message opens `{OPENING}`; its counts are checked against the round's report in the chunk's review folder, where that report exists",
), ),
"run-heavy": Rule( "run-heavy": Rule(
"a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine", "a heavy command, which loads the machine for minutes, runs under ~/.claude/bin/run-heavy, so sessions running at once cannot starve the machine",

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