Compare commits

...

500 Commits

Author SHA1 Message Date
lilleman 79ae24abf4 Finish item 528 in the plan
CI / tests (pull_request) Successful in 6m37s
2026-11-26 12:38:48 +01:00
lilleman c259d5fbb2 Finish item 527 in the plan 2026-11-26 12:38:47 +01:00
lilleman 87f168c4c9 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); drop a report the tree held before the run, move a comment back to its function
CI / tests (pull_request) Has been cancelled
2026-11-26 12:35:53 +01:00
lilleman 794adafb91 Leave the scratch folder out of its own copy by name
CI / tests (pull_request) Successful in 6m14s
2026-11-26 12:08:55 +01:00
lilleman 8b1c9ff184 Fail the scratch copy's test on a socket, not a patched function
CI / tests (pull_request) Successful in 8m49s
2026-11-26 11:45:36 +01:00
lilleman 014d085f26 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); reworded in the two answers before this one
CI / tests (pull_request) Has been cancelled
2026-11-26 11:42:20 +01:00
lilleman ea4d2408b2 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); say how the tools get their dependencies and which names count as tests, file item 544 2026-11-26 11:42:20 +01:00
lilleman 874e417e27 Answer stability round 1: 0 🔴, 5 🟡 (0 misread); run both tools in a scratch copy, read Infection's two sources, end PHPUnit's list, spell glob characters 2026-11-26 11:42:20 +01:00
lilleman 76de4fa497 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-26 11:42:20 +01:00
lilleman 47084dc3df Test the planters' edges that mutants survived
CI / tests (pull_request) Successful in 6m5s
2026-11-26 11:03:39 +01:00
lilleman 632023ed21 Sort the two planters' imports
CI / tests (pull_request) Successful in 5m35s
2026-11-26 10:42:42 +01:00
lilleman ffe2048b73 Plant task-bench's bugs in TypeScript and PHP, from Stryker's and Infection's killed mutants
CI / tests (pull_request) Has been cancelled
2026-11-26 10:39:36 +01:00
lilleman 48270c0439 Record the reading cost 2026-11-26 10:39:36 +01:00
lilleman 9eea738d57 Finish item 543 in the plan
CI / tests (pull_request) Successful in 5m30s
2026-11-26 10:23:12 +01:00
lilleman d97709eccd Answer prose round 1: 0 🔴, 2 🟡 (0 misread); reword both rules, define fixup
CI / tests (pull_request) Has been cancelled
2026-11-26 10:22:58 +01:00
lilleman a929e2ccc0 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); keep a blanked row 2026-11-26 10:22:54 +01:00
lilleman 4b51675596 Add two testing rules: assert the exception exists, filter after fixups
CI / tests (pull_request) Has been cancelled
2026-11-26 10:20:46 +01:00
lilleman 1ed9491d9a Finish item 524 in the plan
CI / tests (pull_request) Successful in 5m2s
2026-11-26 10:14:36 +01:00
lilleman 77d0b91595 Merge remote-tracking branch 'origin/main' into item-524
CI / tests (pull_request) Successful in 5m14s
2026-11-26 08:54:18 +01:00
lilleman 6b447280bf File the test-presence and importer-filter gap
CI / tests (pull_request) Successful in 4m50s
2026-11-26 07:57:32 +01:00
lilleman f5d14d997e File item 542: report space-indented code that no setting explains
CI / tests (pull_request) Successful in 10m11s
2026-11-26 07:45:28 +01:00
lilleman 166778ef0b Record the reading cost of the last three chunks 2026-11-26 03:39:32 +01:00
lilleman 82ff0c3db9 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); reword the comment as the reviewer did
CI / tests (pull_request) Has been cancelled
2026-11-26 02:57:34 +01:00
lilleman 1c72ea2c6a Record why task-bench keeps Haiku's Rust file where the planted file's test modules can't be told apart 2026-11-26 02:55:35 +01:00
lilleman 3fd7a841c7 Finish item 532 in the plan
CI / tests (pull_request) Successful in 4m19s
2026-11-26 02:49:46 +01:00
lilleman d0e793e39c Merge remote-tracking branch 'origin/main' into item-532
CI / tests (pull_request) Has been cancelled
# Conflicts:
#	todo.md
2026-11-26 02:47:26 +01:00
lilleman 7c01eb1f8b Answer stability round 2: 0 🔴, 1 🟡 (0 misread); keep a Rust file whose modules cannot be told apart as Haiku left it where the planted file has no module
CI / tests (pull_request) Successful in 6m22s
2026-11-26 02:03:10 +01:00
lilleman b0c5aa3390 Answer prose round 1: 0 🔴, 8 🟡 (0 misread); reword the help, docstrings and test names
CI / tests (pull_request) Successful in 6m2s
2026-11-26 01:32:20 +01:00
lilleman d3fa35372d Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); keep Rust test modules for bugs only 2026-11-26 01:32:20 +01:00
lilleman 90d88b9967 Answer stability round 1: 1 🔴, 2 🟡 (0 misread); order imports, state in the help which Rust files count, file item 539 for out-of-line tests 2026-11-26 01:32:20 +01:00
lilleman 42b23ac235 File item: leave out of a task-bench fix a change Haiku makes to a Rust test in a file of its own 2026-11-26 01:32:09 +01:00
lilleman cecabf324a Answer review: keep Rust test modules for bugs only, order imports, reword
CI / tests (pull_request) Has been cancelled
2026-11-26 01:30:46 +01:00
lilleman bf27992fbc Sort the imports the empty-transcript change added
CI / tests (pull_request) Successful in 5m59s
2026-11-26 01:29:53 +01:00
lilleman 4e9efb4946 Finish item 539 in the plan
CI / tests (pull_request) Failing after 11m10s
2026-11-26 01:10:20 +01:00
lilleman 8361145973 Merge remote-tracking branch 'origin/main' into item-539
CI / tests (pull_request) Has been cancelled
2026-11-26 01:10:01 +01:00
lilleman 4d4cecfecb Answer prose round 1: 0 🔴, 1 🟡 (0 misread); fixed in the stability round's commit 2026-11-26 01:09:58 +01:00
lilleman 05a195a09e Answer stability round 1: 0 🔴, 2 🟡 (0 misread); test the failed removal, run the new tests under the guard, and reword the prose round's finding 2026-11-26 01:09:58 +01:00
lilleman 347368040e End a raw string at its first closing quote by regex
CI / tests (pull_request) Failing after 5m36s
2026-11-26 00:53:45 +01:00
lilleman 61f901a2c9 Kill the surviving mutants of the empty-transcript change 2026-11-26 00:51:46 +01:00
lilleman bb57b68090 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to fix 2026-11-26 00:44:45 +01:00
lilleman 0bf477c630 Start a fresh session where its transcript is empty
CI / tests (pull_request) Failing after 5m31s
2026-11-26 00:34:22 +01:00
lilleman 6719d10034 Read a Rust string with a regex and kill the surviving mutants
CI / tests (pull_request) Failing after 5m39s
2026-11-26 00:28:10 +01:00
lilleman 53ce873cc2 Finish item 540 in the plan
CI / tests (pull_request) Successful in 5m16s
2026-11-26 00:13:13 +01:00
lilleman f72b9b5c26 Merge remote-tracking branch 'origin/main' into item-540 2026-11-26 00:13:13 +01:00
lilleman 95d8d201cf Answer stability round 1: 0 🔴, 2 🟡 (0 misread); settle which fixes rerun prose
CI / tests (pull_request) Has been cancelled
2026-11-26 00:08:43 +01:00
lilleman 66524cbd66 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); settle which fixes rerun prose 2026-11-26 00:08:33 +01:00
lilleman dd15690903 Tell a Rust file's test modules apart as bytes and kill the surviving mutants
CI / tests (pull_request) Failing after 5m15s
2026-11-26 00:00:33 +01:00
lilleman ee8d788d26 Rerun the prose pass once where a fix rewrites a checkable claim
CI / tests (pull_request) Has been cancelled
2026-11-26 00:00:08 +01:00
lilleman 2995def08c Merge remote-tracking branch 'origin/main' into file-gitea-pull-lookup
CI / tests (pull_request) Successful in 11m37s
2026-11-25 23:58:38 +01:00
lilleman 1bc5e67b71 File item 541: find a Gitea pull request however many pull requests are newer
CI / tests (pull_request) Has been cancelled
2026-11-25 23:49:41 +01:00
lilleman 5c759f9dee Finish item 531 in the plan
CI / tests (pull_request) Successful in 9m15s
2026-11-25 23:49:03 +01:00
lilleman b5a2cdaa4f Merge remote-tracking branch 'origin/main' into item-531
CI / tests (pull_request) Has been cancelled
# Conflicts:
#	CHANGELOG.md
#	README.md
#	docs/reading-cost.md
2026-11-25 23:46:16 +01:00
lilleman 9f4b663961 Merge remote-tracking branch 'origin/main' into filing-prose-reentry
CI / tests (pull_request) Successful in 4m49s
# Conflicts:
#	todo.md
2026-11-25 23:34:42 +01:00
lilleman 88e94d5980 File item 540: review once more each prose fix that rewrites a checkable claim
CI / tests (pull_request) Has been cancelled
2026-11-25 23:30:01 +01:00
lilleman c794073312 Keep a Rust file's test modules as planted when task-bench checks a fix
CI / tests (pull_request) Failing after 5m10s
2026-11-25 23:29:11 +01:00
lilleman fc05048180 File item 539: start a fresh session where its transcript is empty
CI / tests (pull_request) Successful in 5m43s
2026-11-25 23:28:09 +01:00
lilleman 2a9ac974e8 Answer stability round 2: 1 🔴, 1 🟡 (0 misread); a fast-forwarded feature whose branch merged the default branch into itself is passed over, and the merge's title is read for a remote-tracking branch alone, in the commit before
CI / tests (pull_request) Successful in 5m31s
2026-11-25 23:21:48 +01:00
lilleman 3d8c00617b Record the reading cost of chunk 242dc2ee7cca, which a broken worktree kept out of the repo
CI / tests (pull_request) Successful in 6m40s
2026-11-25 23:15:47 +01:00
lilleman 4fbb0ede2d Keep the routing ladder, the steps and the delegation rule against the calls of 2026-11-25 2026-11-25 23:15:31 +01:00
Lilleman a70ea1a726 File item 538: flag validation of a value other than the one the code uses
CI / tests (pull_request) Successful in 3m46s
2026-11-25 08:58:18 +01:00
Lilleman 4bad84d087 File item 537: flag $ anchors in whole-input validation regexes
CI / tests (pull_request) Successful in 3m46s
2026-11-24 20:41:01 +01:00
Lilleman a38dad4a6c Finish item 536 in the plan
CI / tests (pull_request) Successful in 6m29s
2026-11-24 15:38:23 +01:00
Lilleman a1e6791cdb Answer stability round 2: 0 🔴, 1 🟡 (0 misread); the hand-cut steps and the reused tag's refusal list the exact entries, and a hand cut reruns to the end
CI / tests (pull_request) Has been cancelled
2026-11-24 15:35:08 +01:00
Lilleman 0a38f99a8d Answer prose round 1: 1 🔴, 7 🟡 (0 misread); true rerun and range text, clearer refusals and test names, and the decision names its choices, in the stability answer 2026-11-24 15:12:17 +01:00
Lilleman 010be0c9e7 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); a patch's review no longer counts for the next release, the help says what a rerun does, and the cut lists the commits it ships, in the stability answer 2026-11-24 15:12:17 +01:00
Lilleman db32e4ef59 Answer stability round 1: 0 🔴, 5 🟡 (0 misread); share the scratch worktree, check a reused tag and main's merge-back, refuse GitHub, split the looped test 2026-11-24 15:12:17 +01:00
Lilleman ec497aa989 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-24 14:48:11 +01:00
Lilleman 3f74d32cae Kill the mutant that strips more than blank lines off a changelog with no section 2026-11-24 14:48:06 +01:00
Lilleman 39cb2f4d9e Unit-test the patch cut's changelog edits in-process 2026-11-24 14:29:51 +01:00
Lilleman 459a3d5f54 Note in item 462 that deploy-release's tests fail in mutmut's copy too 2026-11-24 14:28:55 +01:00
Lilleman 366a10cc0e Sort deploy_release's imports by their first binding 2026-11-24 14:13:32 +01:00
Lilleman 2cdd346060 Record the patch cut in the deploy decision 2026-11-24 14:10:29 +01:00
Lilleman 9c2587b5ca Cut a patch release of only the commits named with deploy-release --cut-patch 2026-11-24 14:09:56 +01:00
Lilleman 80de753b9e File item 536: cut a patch release with deploy-release --cut-patch 2026-11-24 14:05:11 +01:00
Lilleman fdb631d293 File item 535: have stability-reviewer check four things an outside reviewer and two failed gate runs found unchecked
CI / tests (pull_request) Successful in 4m3s
2026-11-24 13:41:27 +01:00
Lilleman 58cbc9a5e3 File item 534: have the reviewers follow three paths an outside reviewer found unchecked
CI / tests (pull_request) Successful in 3m42s
2026-11-24 12:54:21 +01:00
Lilleman 7e03aafe41 List the fix under 0.15.1 in the changelog
CI / tests (pull_request) Successful in 4m7s
2026-11-24 10:18:22 +01:00
Lilleman 2824404460 Merge release 0.15.1 into main 2026-11-24 10:18:11 +01:00
Lilleman dcd55df69a Cut release 0.15.1 2026-11-24 10:17:59 +01:00
Lilleman 1aa2367a31 Finish item 533 in the plan
CI / tests (pull_request) Successful in 4m10s
2026-11-24 10:08:20 +01:00
Lilleman 0cf70b06b1 Answer prose round 1: 1 🔴, 3 🟡 (0 misread); clearer docstrings, test names and item text, and AnIssueEdit above the main guard
CI / tests (pull_request) Has been cancelled
2026-11-24 10:05:08 +01:00
Lilleman fb55fc7a03 Answer stability round 1: 1 🔴, 1 🟡 (1 misread); the plan store's fake refuses an edit with neither fields nor update, and 0.15.1 is cut off v0.15.0, never from main 2026-11-24 10:05:08 +01:00
Lilleman e96b8a8182 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-24 09:57:54 +01:00
Lilleman 0c10eeb986 Kill the mutants of edit_issue: an empty edit sends nothing, and an answer on success is no failure 2026-11-24 07:52:37 +01:00
Lilleman b3bb2dd3f5 Set an issue's scores through its property endpoint where an edit holds neither fields nor update 2026-11-24 07:38:55 +01:00
Lilleman b6a576187a File item 533, a patch release 0.15.1 for Jira's refused score edits 2026-11-24 07:35:01 +01:00
lilleman 794ce37208 Finish item 526 in the plan
CI / tests (pull_request) Successful in 4m0s
2026-11-24 03:17:13 +01:00
lilleman dc8c463ad3 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Has been cancelled
2026-11-24 03:16:04 +01:00
lilleman a030a8eee9 Say in the changelog where a fast-forwarded feature starts
CI / tests (pull_request) Failing after 4m6s
2026-11-24 03:13:35 +01:00
lilleman 767a9e1217 Test that a rebased feature starts at its own chunk
CI / tests (pull_request) Successful in 4m12s
2026-11-24 03:08:47 +01:00
lilleman 1fc164a547 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); the docstrings, comments and help are reworded in the stability round's commit
CI / tests (pull_request) Successful in 4m20s
2026-11-24 02:57:18 +01:00
lilleman 178aeb6749 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); a bar in a bug's name is escaped in the table, the help says a Rust test in its code's file counts, and item 532 files leaving it out; the fixes are in the commit before 2026-11-24 02:57:18 +01:00
lilleman b38e8a1931 Answer stability round 1: 1 🔴, 2 🟡 (0 misread); no outcomes file means no mutant, two tests use subTest, and a test's name fits its assertion 2026-11-24 02:57:18 +01:00
lilleman 7d58002fdd Answer prose round 1: 0 🔴, 6 🟡 (0 misread); the help, README, constant, comments and test docstrings are reworded in the commit before
CI / tests (pull_request) Successful in 4m4s
2026-11-24 02:48:50 +01:00
lilleman 7f4c312021 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the start now also stops at a merge or rebase chunk that shipped no item, in the commit before 2026-11-24 02:48:50 +01:00
lilleman 4328a13ad8 Answer stability round 1: 2 🔴, 0 🟡 (0 misread); a fast-forwarded feature starts after the latest earlier chunk of another feature, a merge of the default branch into a feature branch marks no start, and the types hold 2026-11-24 02:48:41 +01:00
lilleman 70fbc2a02d Kill the mutants that survived in the Rust planter
CI / tests (pull_request) Successful in 4m13s
2026-11-24 02:34:10 +01:00
lilleman f025bc65cd Test that a fast-forwarded feature with no earlier feature is passed over
CI / tests (pull_request) Failing after 4m4s
2026-11-24 02:30:12 +01:00
lilleman a1465a386a Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-24 02:16:52 +01:00
lilleman 49d16378e8 Plant bugs for task-bench in Rust, from the mutants cargo-mutants kills
CI / tests (pull_request) Successful in 4m35s
2026-11-24 02:15:50 +01:00
lilleman 6fbfd54821 Record the reading cost 2026-11-24 02:13:14 +01:00
lilleman 280f7521d0 Bench a shipped feature whose branch landed by fast-forward from the commits after the item shipped before it
CI / tests (pull_request) Failing after 4m50s
2026-11-24 02:09:49 +01:00
lilleman 6f5839479a Finish item 507 in the plan
CI / tests (pull_request) Successful in 8m14s
2026-11-24 01:58:07 +01:00
lilleman b77912589b Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved; item 531's detail says how many of this project's features landed by fast-forward
CI / tests (pull_request) Has been cancelled
2026-11-24 01:55:34 +01:00
lilleman 788a66d628 Answer prose round 1: 0 🔴, 8 🟡 (0 misread); the help, docstrings, comments and item 507's detail are reworded in this commit and the two before 2026-11-24 01:29:45 +01:00
lilleman 8d4609fad7 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the digest and the gather prompt name the folders that hold each side without a shipped feature, and the help's exit-1 paragraph reads whole 2026-11-24 01:29:45 +01:00
lilleman c6ebfe0cfe Answer stability round 1: 1 🔴, 2 🟡 (1 misread); a feature whose branch landed by fast-forward is passed over and item 531 files benching it, a test refuses a plan outside the checkout from another folder, and the README states the import once 2026-11-24 01:29:45 +01:00
lilleman 52c525a12f Test a shipped feature that holds a file whose name is not UTF-8 2026-11-24 00:55:14 +01:00
lilleman 7e4854bd8e Test a shipped feature's binary file, linked test, removed test and passing test, a checkout that drops a diff's prefixes, and a bench run from a folder inside the checkout 2026-11-24 00:54:52 +01:00
lilleman 74ffd6da53 Sort the shipped-feature imports and type what a bench makes its tasks from 2026-11-24 00:33:08 +01:00
lilleman 8e43967fac Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-24 00:32:03 +01:00
lilleman 1ca84223ce Say in item 507 how a shipped feature is found, as built
CI / tests (pull_request) Failing after 3m57s
2026-11-24 00:30:34 +01:00
lilleman 87726f9f0b Bench rebuilding a shipped feature: take its chunk's change out, tell Haiku the item's tagline, check with the tests the change holds 2026-11-24 00:29:25 +01:00
lilleman c0445a26d7 Test a bench of the features a project's history shipped 2026-11-24 00:29:25 +01:00
lilleman d432aa272c Record reading cost 2026-11-24 00:20:11 +01:00
lilleman 1ca6c800f5 Re-score item 507 to L 4 and say how a shipped feature is found 2026-11-24 00:20:11 +01:00
lilleman c86d15f25f Finish item 530 in the plan
CI / tests (pull_request) Successful in 6m22s
2026-11-24 00:10:25 +01:00
lilleman 7521168ac5 Merge remote-tracking branch 'origin/main' into item-530
CI / tests (pull_request) Has been cancelled
2026-11-24 00:10:15 +01:00
lilleman b367f6fe19 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Has been cancelled
2026-11-24 00:10:13 +01:00
lilleman 9541d0df54 Answer prose round 1: 1 🔴, 1 🟡 (1 misread); the docstring now says both tools' lines, the comment says only the mutant's last line goes without a line end, and the two test names are reworded in the commit before
CI / tests (pull_request) Successful in 3m57s
2026-11-23 23:52:25 +01:00
lilleman 763ee78296 Answer stability round 1: 1 🔴, 0 🟡 (1 misread); mutated matches Gremlins' lines that keep their CR as well as mutmut's, and the last line of a mutant that ends the file takes no line end; the prose findings' rewording is in this commit 2026-11-23 23:52:25 +01:00
lilleman 5739a308b2 Finish item 529 in the plan
CI / tests (pull_request) Successful in 3m51s
2026-11-23 23:35:58 +01:00
lilleman ceab5d2f82 Merge remote-tracking branch 'origin/main' into item-529
CI / tests (pull_request) Has been cancelled
2026-11-23 23:33:39 +01:00
lilleman 38581b98be Answer stability round 2: 0 🔴, 1 🟡 (0 misread); the repo check holds the README's pytest pins too, and run-tests' comment names it instead of counting copies 2026-11-23 23:33:35 +01:00
lilleman a45279fe54 Take a CRLF file's line end from its first line, with a test of a mixed file
CI / tests (pull_request) Successful in 4m13s
2026-11-23 23:32:20 +01:00
lilleman a4ff7de729 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); the Dockerfile comment and the README paragraph are rewritten in the commit before 2026-11-23 23:32:00 +01:00
lilleman 774f127534 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the --prefix and the build step are in the commit before 2026-11-23 23:32:00 +01:00
lilleman 461f1a6ef1 Answer stability round 1: 1 🔴, 3 🟡 (0 misread); the README command gets a mutmut --prefix and its own build step, the Dockerfile and run-tests' comments name each other's pins, and a repo check holds them equal 2026-11-23 23:32:00 +01:00
lilleman b0258ef736 Sort the new check's imports 2026-11-23 23:31:55 +01:00
lilleman ca99ed3ef5 Pin the bench image's Python and pytest to what CI uses, and give its command a mutmut prefix and its own build step 2026-11-23 23:29:40 +01:00
lilleman 81e03f2a6d Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 23:21:45 +01:00
lilleman 307b7d3c04 Record the reading cost of item 529's chunk
CI / tests (pull_request) Successful in 4m2s
2026-11-23 23:21:22 +01:00
lilleman 38c91606d6 Document a task-bench command for this repo, with an image that holds what its tests need 2026-11-23 23:21:11 +01:00
lilleman a7d178446b Finish item 512 in the plan
CI / tests (pull_request) Successful in 6m55s
2026-11-23 23:20:46 +01:00
lilleman 920459c2fb Merge remote-tracking branch 'origin/main' into item-512
CI / tests (pull_request) Has been cancelled
# Conflicts:
#	docs/reading-cost.md
2026-11-23 23:18:49 +01:00
lilleman 380e16de6d Answer prose round 1: 0 🔴, 1 🟡 (0 misread); the bullet gives one example per collision, joined segments and shared prefixes, and says resolves 2026-11-23 23:18:40 +01:00
lilleman 4620365931 Plant a mutant in a Python file whose lines end in CRLF
CI / tests (pull_request) Successful in 4m8s
2026-11-23 23:14:36 +01:00
lilleman 67ded86ef4 Make stability-reviewer check that keys built from path segments, or matched by prefix, cannot collide 2026-11-23 23:13:49 +01:00
lilleman fb3e526989 Finish item 506 in the plan
CI / tests (pull_request) Successful in 10m19s
2026-11-23 23:02:34 +01:00
lilleman e5fd1dc4f5 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); the one 🟢 is fixed in the commit before: a folder outside both repos isn't committed
CI / tests (pull_request) Has been cancelled
2026-11-23 23:02:18 +01:00
lilleman 0586fb41d2 Go over the bench features in each release review: a folder outside both repos isn't committed
CI / tests (pull_request) Has been cancelled
2026-11-23 23:02:08 +01:00
lilleman 13ea3d5f32 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); the stability answer's rewrite also defines a bench feature first, names the bench's base through the head and lists each step in order
CI / tests (pull_request) Has been cancelled
2026-11-23 23:00:26 +01:00
lilleman 5e2db60a8f Answer stability round 1: 1 🔴, 6 🟡 (0 misread); the bullet says bench feature, holds the full check at the head, orders delete before rewrite and covers every code place 2026-11-23 23:00:26 +01:00
lilleman bacd94faf5 Record the reading cost
CI / tests (pull_request) Successful in 3m56s
2026-11-23 22:56:05 +01:00
lilleman 725637c11c Go over the bench features in each release review 2026-11-23 22:56:02 +01:00
lilleman 225c5497d6 Finish item 508 in the plan
CI / tests (pull_request) Successful in 3m46s
2026-11-23 22:50:26 +01:00
lilleman e0bce39e6e Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); no finding; the two ❓ on unrun claims are answered by the tests that fake the tools and read pytest 9.2.0's own report
CI / tests (pull_request) Successful in 5m14s
2026-11-23 22:32:43 +01:00
lilleman 2aa7b7399a Answer prose round 1: 0 🔴, 6 🟡 (0 misread); docstrings and a fixture's comment say what the code does
CI / tests (pull_request) Has been cancelled
2026-11-23 22:31:03 +01:00
lilleman fe6d119183 Answer product-owner round 1: 1 🔴, 0 🟡 (0 misread); the help shows one prefix that runs both tools and says which runner --test must run 2026-11-23 22:31:03 +01:00
lilleman c43d9e9bae Answer stability round 1: 0 🔴, 3 🟡 (0 misread); mutmut's copy keeps a link to a folder, the README place waits for item 300, and CRLF files are item 530 2026-11-23 22:31:03 +01:00
lilleman 04c1778d57 Test that the planter keeps the mutants of every folder mutmut runs in
CI / tests (pull_request) Successful in 3m49s
2026-11-23 22:19:52 +01:00
lilleman fc9749aa0a Test the planters' and mutmut's report on the lines the mutation run left alive
CI / tests (pull_request) Successful in 3m53s
2026-11-23 21:58:35 +01:00
lilleman 8bab7b3a6f Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 21:36:29 +01:00
lilleman b0e50e24ae Sort the imports and hand the planter its languages as an argument
CI / tests (pull_request) Successful in 3m28s
2026-11-23 21:35:21 +01:00
lilleman c6cdd2f850 Plant bugs for task-bench in Python from the mutants mutmut kills
CI / tests (pull_request) Failing after 3m46s
2026-11-23 21:31:00 +01:00
lilleman cb6aedd603 Re-score item 508 to L 4, S 6 2026-11-23 21:09:27 +01:00
lilleman 04c6d062c2 Finish item 505 in the plan
CI / tests (pull_request) Successful in 3m40s
2026-11-23 21:03:09 +01:00
lilleman f78beb7b0e Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); no finding; the ❓ on a missing interpreter is answered by passing such a task over, and the unrun claims by the tests that fake docker
CI / tests (pull_request) Successful in 3m41s
2026-11-23 20:58:16 +01:00
lilleman fc103321a2 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); pass over a data source whose script the image cannot run, exit 126 or 127 2026-11-23 20:58:16 +01:00
lilleman c9948496eb Pass over a data source whose script the image cannot run 2026-11-23 20:37:46 +01:00
lilleman 5727456738 Answer prose round 1: 2 🔴, 3 🟡 (0 misread); the exit paragraph and tasks.py name data sources, the help asks for a seeded script, and the bench prints data source
CI / tests (pull_request) Successful in 3m46s
2026-11-23 20:12:32 +01:00
lilleman c1184ef6b0 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the help names a data-source bench's exits and what the script's container holds, and a pass-over quotes the script's last line 2026-11-23 20:12:32 +01:00
lilleman 092dd3d7d5 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); refuse a register entry that is no regular file, and name three kinds of task 2026-11-23 20:12:32 +01:00
lilleman 4f71d5777d Test an unreadable register without a mock 2026-11-23 19:51:28 +01:00
lilleman 44c0f13883 Refuse a register entry that is no regular file, and say data source in what task-bench prints 2026-11-23 19:49:22 +01:00
lilleman c798278406 Name data-sources in task-bench's usage line
CI / tests (pull_request) Successful in 3m41s
2026-11-23 19:41:53 +01:00
lilleman 0a270d5d45 Answer security round 2: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 19:41:35 +01:00
lilleman 2ffa4908c9 Answer security round 1: 1 🔴, 0 🟡 (0 misread); pass over a data source whose script writes a .git, and test the script's failures
CI / tests (pull_request) Successful in 3m45s
2026-11-23 19:18:26 +01:00
lilleman 82a03e9a1b Sort the imports of the data-source kind's files 2026-11-23 18:50:48 +01:00
lilleman 20caafeae6 Record the reading cost
CI / tests (pull_request) Failing after 3m54s
2026-11-23 18:48:08 +01:00
lilleman c45472397e Bench adding a data source in task-bench, from a register a seeded script generates 2026-11-23 18:48:03 +01:00
lilleman f6b180fd9d Split item 505: fejkdata's five source-data tasks are item 525 2026-11-23 18:42:20 +01:00
lilleman 79be72aec6 Finish item 504 in the plan
CI / tests (pull_request) Successful in 4m2s
2026-11-23 18:33:39 +01:00
lilleman 3d7c97aac0 Merge remote-tracking branch 'origin/main' into item-504
CI / tests (pull_request) Has been cancelled
2026-11-23 18:31:15 +01:00
lilleman 0f1f367139 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); no finding; the ❓, that three help claims were not run, is answered by running the two that start no container
CI / tests (pull_request) Has been cancelled
2026-11-23 18:31:05 +01:00
lilleman c79f72cd96 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 18:31:05 +01:00
lilleman 4d2c896f21 Test that a bugs bench fails where Gremlins fails
CI / tests (pull_request) Successful in 3m44s
2026-11-23 18:25:09 +01:00
lilleman 2b26cdc530 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); say how a build is checked, and what a digest of features asks of gather
CI / tests (pull_request) Failing after 3m44s
2026-11-23 17:59:26 +01:00
lilleman e60db165f3 Answer product-owner round 1: 1 🔴, 0 🟡 (0 misread); say where to keep the features so the project's own tests skip them 2026-11-23 17:59:26 +01:00
lilleman 5814a3e895 Answer stability round 1: 0 🔴, 8 🟡 (0 misread); check a reference patch as a build is checked, test the rule at the head, split the bench's setup by kind 2026-11-23 17:59:26 +01:00
lilleman e5742c2a5d Keep the routing ladder and steps against the calls of 2026-11-23
CI / tests (pull_request) Successful in 5m0s
2026-11-23 17:38:39 +01:00
lilleman 20105231fc Test that a bench of features reads no places
CI / tests (pull_request) Successful in 3m45s
2026-11-23 17:30:29 +01:00
lilleman b355a2025c Start every feature from one committed tree per side, and name the kind of task in each table and digest
CI / tests (pull_request) Successful in 3m44s
2026-11-23 17:08:09 +01:00
lilleman b053a54989 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 16:35:59 +01:00
lilleman add003215d Sort the imports of the feature tasks' files
CI / tests (pull_request) Successful in 3m51s
2026-11-23 16:34:17 +01:00
lilleman cdeb66bf6e Bench features in task-bench with --tasks features, from the folder the config names as bench-tasks
CI / tests (pull_request) Has been cancelled
2026-11-23 16:31:27 +01:00
lilleman 28537b5aa3 Split item 504 into the bench's feature mode and fejkdata's six features, and re-score it 2026-11-23 16:16:41 +01:00
lilleman cf40c8aa8d Finish item 509 in the plan
CI / tests (pull_request) Successful in 5m25s
2026-11-23 16:07:02 +01:00
lilleman 7b5fdb97e6 Merge remote-tracking branch 'origin/main' into item-509
CI / tests (pull_request) Has been cancelled
2026-11-23 16:06:47 +01:00
lilleman d37a9fbb68 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding; the 🟢, that a bench it could not record prints no table, stands, since the folder it names holds the table 2026-11-23 16:06:47 +01:00
lilleman 1360627b4d Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); no finding; the 🟢, that a bench the history already holds is refused only after it ran, stands, since a scoring run takes one bench 2026-11-23 16:00:51 +01:00
lilleman 71cf3ffa2b Sort the imports of record_figures.py 2026-11-23 15:41:25 +01:00
lilleman c1b16e09a3 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); reword the help, the skill's bullets, the README's sentence, the comment and the docstrings 2026-11-23 15:36:08 +01:00
lilleman febca8b5ee Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the bench records under its own lock, and the skill says the chunk waits for it and never gathers it 2026-11-23 15:36:08 +01:00
lilleman 9d2e3f1823 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); record a bench's figures inside the bench with --record-figures, so one that stopped or an older digest is never recorded 2026-11-23 15:36:08 +01:00
lilleman 1f33e37fe5 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-23 15:29:49 +01:00
lilleman 000ad99897 Test that task-bench record-figures says why where no config names the checkout
CI / tests (pull_request) Successful in 5m4s
2026-11-23 15:13:05 +01:00
lilleman 9207a6cf80 Test the environment git runs in, an unreadable digest and the history write of task-bench record-figures
CI / tests (pull_request) Successful in 5m28s
2026-11-23 14:51:11 +01:00
lilleman 5c433ecc9f File item for checking what a new secret's docs say its token reaches
CI / tests (pull_request) Successful in 4m55s
2026-11-23 14:33:34 +01:00
lilleman 65398d5e96 Record a bench in the comprehension history with task-bench record-figures, and run the bench beside a scoring run
CI / tests (pull_request) Failing after 4m58s
2026-11-23 14:29:30 +01:00
Lilleman 9879d8ee67 File items 518 to 522: prose negations, git in tests, shell mutation, secrets in Docker builds, security pass in worktrees
CI / tests (pull_request) Successful in 4m55s
2026-11-23 14:25:27 +01:00
lilleman 6b36f43062 Record a task-bench's figures in the comprehension history with larv-review record-bench, and run the bench beside a scoring run
CI / tests (pull_request) Failing after 5m6s
2026-11-23 14:21:56 +01:00
lilleman 56a82245ad Ship the unreleased changes as 0.16.0, not 0.15.1, since they change what task-bench's All change row means
CI / tests (pull_request) Successful in 6m10s
2026-11-23 13:55:47 +01:00
lilleman fa2ead69c9 Record the comprehension check: paired ruling better at 4dd8b730 against 5b61b476, both seats better on every dimension
CI / tests (pull_request) Successful in 5m14s
2026-11-23 02:34:11 +01:00
lilleman 4dd8b73054 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); note in the changelog that a bench that can't copy, read or write a file names it and keeps the finished runs' table
CI / tests (pull_request) Has been cancelled
2026-11-23 02:31:00 +01:00
lilleman 83194a11a5 Answer prose round 1: 0 🔴, 12 🟡 (0 misread); keep a {} line as an entry, point handed_on and parked_through at the docstrings that hold their rules, split news_after's two kinds of news, say what each parameter is, reword item 517's way out, and report a .tar left behind as its own failure 2026-11-23 02:30:59 +01:00
lilleman ba50eacafe Answer stability round 1: 0 🔴, 4 🟡 (0 misread); test the digest's half surrogate, git's diff settings and literal report rows, and guard the permissions test against root 2026-11-23 02:30:52 +01:00
lilleman cc23e80fb8 Test that each file task-bench cannot copy, read or write fails the bench and names what could not be done
CI / tests (pull_request) Successful in 5m2s
2026-11-23 01:58:57 +01:00
lilleman b7993aaf93 Answer principles round 2: 0 🔴, 0 🟡 (0 misread); every answer holds 2026-11-23 01:40:09 +01:00
lilleman cfe537b3fd Answer principles round 1: 0 🔴, 5 🟡 (0 misread); make a move a union with ToStatus, take only parsed events in figures, catch OSError at each file operation, pass progress through the bench, type the sides, and split the README bullet
CI / tests (pull_request) Successful in 5m4s
2026-11-23 01:37:39 +01:00
lilleman 9fe060575b Answer architecture round 2: 0 🔴, 0 🟡 (0 misread); every answer holds 2026-11-23 01:22:23 +01:00
lilleman 0bf87b736e Answer architecture round 1: 2 🔴, 8 🟡 (0 misread); split task-bench's benched into phases and its table into one column list, parse each stream once, move do-epic's parking out with pure move and news decisions, share the round summaries, rename scoring_due, and file the version question as item 517
CI / tests (pull_request) Successful in 5m2s
2026-11-23 01:20:55 +01:00
lilleman 21200cb698 Record the reading cost
CI / tests (pull_request) Successful in 5m30s
2026-11-23 01:01:56 +01:00
lilleman b490545439 Release review of 0.15.1
CI / tests (pull_request) Has been cancelled
2026-11-23 01:01:42 +01:00
lilleman 4e97930528 Finish item 515 in the plan
CI / tests (pull_request) Successful in 5m22s
2026-11-23 00:55:21 +01:00
lilleman 5b61b47603 Record the comprehension check: two scoring runs at 6322c6e1, overall 6.00 both, and floor item 300 refreshed 2026-11-23 00:55:14 +01:00
lilleman 6322c6e18e Answer prose round 1: 0 🔴, 7 🟡 (0 misread); lead with the conclusion, explain the three thresholds and call the judgment a judgment
CI / tests (pull_request) Successful in 4m59s
2026-11-23 00:43:01 +01:00
lilleman 8830dc6cdf Record that neither paired mutants nor hidden tests make task-bench's pass rate show a chunk-sized change
CI / tests (pull_request) Has been cancelled
2026-11-23 00:40:21 +01:00
lilleman 005bcacbb2 Finish item 516 in the plan
CI / tests (pull_request) Successful in 5m33s
2026-11-22 21:36:13 +01:00
lilleman bd9d9f508b Drop the finished item's number from the decision
CI / tests (pull_request) Has been cancelled
2026-11-22 21:36:08 +01:00
lilleman a40eafa336 Answer prose round 2: 0 🔴, 0 🟡 (0 misread); label the pooled change and the mean once, and say what the filed items are for
CI / tests (pull_request) Has been cancelled
2026-11-22 21:35:58 +01:00
lilleman e25b4fc401 Merge remote-tracking branch 'origin/main' into item-516
CI / tests (pull_request) Has been cancelled
# Conflicts:
#	docs/decisions.md
2026-11-22 21:34:45 +01:00
lilleman 98754352e5 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); make the turns' and reads' figures one reading each 2026-11-22 21:34:09 +01:00
lilleman e47e71167b Record the spread of the reads and the turns beside the tokens' in the task-bench decision
CI / tests (pull_request) Has been cancelled
2026-11-22 21:32:48 +01:00
lilleman ab08c3c238 Finish item 514 in the plan
CI / tests (pull_request) Successful in 5m24s
2026-11-22 17:49:53 +01:00
lilleman a95dd360c8 Merge remote-tracking branch 'origin/main' into item-514
CI / tests (pull_request) Successful in 8m13s
2026-11-22 17:32:09 +01:00
lilleman b65710dca7 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); reword the docstrings, help and decision, and item 516's detail
CI / tests (pull_request) Has been cancelled
2026-11-22 17:32:04 +01:00
lilleman 4612f71592 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); the help calls the noise figures an All change, and the changelog says the row's meaning changed 2026-11-22 17:32:04 +01:00
lilleman f5a691ff07 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); count the passes from the bugs' runs and drop change's duplicate parameters 2026-11-22 17:32:04 +01:00
lilleman f9f96f69ae Build each column's mean change without a no-bugs branch
CI / tests (pull_request) Successful in 5m25s
2026-11-22 17:10:03 +01:00
lilleman 0b6cc71520 Finish item 513 in the plan
CI / tests (pull_request) Successful in 7m50s
2026-11-22 17:09:32 +01:00
lilleman 72c481696d Answer stability round 1: 0 🔴, 0 🟡 (0 misread); approved without findings
CI / tests (pull_request) Has been cancelled
2026-11-22 17:09:21 +01:00
lilleman 5b792514a4 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing found 2026-11-22 17:09:21 +01:00
lilleman e38b6c344b Print the mean of the bugs' own changes as task-bench's All change
CI / tests (pull_request) Successful in 4m28s
2026-11-22 16:52:54 +01:00
lilleman 993295b486 Stop the bench with a Failure on a run that ended on an api_error without a status
CI / tests (pull_request) Successful in 5m21s
2026-11-22 16:50:51 +01:00
lilleman e687860824 Name decision titles in the plan's citations without the heading marker
CI / tests (pull_request) Successful in 4m53s
2026-11-22 16:40:22 +01:00
lilleman 82511b3d0f Finish item 503 in the plan
CI / tests (pull_request) Failing after 6m49s
2026-11-22 16:32:13 +01:00
lilleman f45e06fe9d Merge remote-tracking branch 'origin/main' into item-503
CI / tests (pull_request) Has been cancelled
# Conflicts:
#	todo.md
2026-11-22 16:31:57 +01:00
lilleman e8c123ced0 Record the comprehension check: scoring run at 16d9b3a0, overall 6.13, Locality lowest at 5.63; refresh floor item 300 2026-11-22 16:30:21 +01:00
lilleman 16d9b3a059 Answer prose round 1: 0 🔴, 10 🟡 (0 misread); rewrite the decision conclusions first with corrected figures, and clarify the help's noise paragraph 2026-11-22 16:24:07 +01:00
lilleman 5c3ac81ed7 Calibrate task-bench on fejkdata and record how many tasks and runs a bench takes
CI / tests (pull_request) Failing after 5m1s
2026-11-22 16:16:00 +01:00
lilleman 378dafeef3 Record the reading cost of the chunk before this one 2026-11-22 16:16:00 +01:00
lilleman 0c2f2a5fd1 Cut release 0.15.0
CI / tests (pull_request) Successful in 4m49s
2026-11-22 15:52:21 +01:00
lilleman ec7a161339 Move item 503 to 0.15.1, since 0.15.0 is cut before its release review
CI / tests (pull_request) Successful in 4m16s
2026-11-22 15:50:23 +01:00
lilleman 2a190c7700 File item 512: make stability-reviewer check that composed lookup keys cannot collide
CI / tests (pull_request) Successful in 5m40s
2026-11-21 13:28:23 +01:00
lilleman ed07d6a002 Limit goal 3's backup of a bench's transcripts to the time before its gather
CI / tests (pull_request) Successful in 4m50s
2026-11-21 13:01:59 +01:00
lilleman 78ed3819aa Finish item 502 in the plan
CI / tests (pull_request) Successful in 4m50s
2026-11-21 12:41:35 +01:00
lilleman e2fc5dbfb2 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); test that a gather before any review makes the review folders private; the digest's errors="replace" stays untested, as it takes a lone surrogate in a stream
CI / tests (pull_request) Successful in 5m6s
2026-11-21 12:22:46 +01:00
lilleman de5802e603 Answer prose round 1: 0 🔴, 8 🟡 (0 misread); reword the help, prompt, docstrings and README entries in the commit above
CI / tests (pull_request) Has been cancelled
2026-11-21 12:18:41 +01:00
lilleman d265e242f8 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); in the commit above, name the commits and trees in the digest, keep the folder when claude ends in an error, and say the next bench clears it 2026-11-21 12:18:40 +01:00
lilleman 101c8a7c3d Answer stability round 1: 0 🔴, 5 🟡 (1 misread); keep locks out of compress-archives, count only a search's hits, show an unfinished failing run, and test the walk and the home 2026-11-21 12:18:40 +01:00
lilleman 27e5014322 Test the median pick by tokens, the name of a silent claude and the environment git runs in
CI / tests (pull_request) Successful in 4m13s
2026-11-21 11:57:43 +01:00
lilleman b474ec2f5a Test the digest's cuts, the median pick and gather's refusals, and drop project_rung's checkout parameter 2026-11-21 04:24:52 +01:00
lilleman 7a568f80af Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to fix 2026-11-21 03:57:17 +01:00
lilleman ad11c72016 Distil each task-bench run into a digest and gather plan items from it
CI / tests (pull_request) Failing after 4m49s
2026-11-21 03:56:18 +01:00
lilleman d813fdad5a Finish item 501 in the plan
CI / tests (pull_request) Successful in 6m11s
2026-11-21 03:40:18 +01:00
lilleman 68152c5dec Merge remote-tracking branch 'origin/main' into item-501
CI / tests (pull_request) Has been cancelled
2026-11-21 03:37:59 +01:00
lilleman 1500c52d69 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); take a failed subtest's message over what its parent logged 2026-11-21 03:37:59 +01:00
lilleman 0c17559efe Test a line printed before any test's mark
CI / tests (pull_request) Successful in 3m51s
2026-11-21 03:09:34 +01:00
lilleman 488f1fd698 Answer prose round 1: 0 🔴, 14 🟡 (0 misread); reword the help, docstrings and README entries in the commit above
CI / tests (pull_request) Successful in 3m57s
2026-11-21 02:41:37 +01:00
lilleman 76131e1ee6 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); keep the finished runs and say Bug, the host's gremlins and the reads' median in the commit above 2026-11-21 02:41:36 +01:00
lilleman 8c1edf552a Answer stability round 1: 0 🔴, 10 🟡 (0 misread); take the failed test's last message, fail on a docker run that never started, keep testdata as planted, show finished runs when the API refuses one, and test five survivors 2026-11-21 02:41:36 +01:00
lilleman 1e96a397af Test the value after an equals sign, -h, a line next to a change and the proxy's refusals
CI / tests (pull_request) Successful in 3m54s
2026-11-21 02:04:37 +01:00
lilleman ebbe926ab7 Test task-bench's docker calls, command line and planter where mutants survived
CI / tests (pull_request) Successful in 4m38s
2026-11-21 01:39:12 +01:00
lilleman fed84cc510 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-21 01:07:18 +01:00
lilleman 089e9b683b Add task-bench, which has Haiku fix planted bugs at a base and a head and prints what each side took
CI / tests (pull_request) Failing after 4m9s
2026-11-21 01:05:50 +01:00
lilleman 6953dcb8e0 Finish item 511 in the plan
CI / tests (pull_request) Successful in 5m22s
2026-11-21 00:54:24 +01:00
lilleman 96ee03260e Merge remote-tracking branch 'origin/main' into item-511 2026-11-21 00:54:23 +01:00
lilleman 457c789165 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); reword the claimed-output paragraph and both reviewer checks in the commit above
CI / tests (pull_request) Has been cancelled
2026-11-21 00:51:07 +01:00
lilleman a558908d83 Answer stability round 1: 0 🔴, 3 🟡 (1 misread); name the claimed-output file per round, run as the project runs tools, leave files untouched 2026-11-21 00:51:07 +01:00
lilleman 0874b67b02 Finish item 469 in the plan
CI / tests (pull_request) Successful in 4m54s
2026-11-21 00:49:13 +01:00
lilleman a22fb064f4 Hand reviewers the real output of each claimed command 2026-11-21 00:47:35 +01:00
lilleman 56b73ca37c Append reading-cost figures 2026-11-21 00:47:35 +01:00
lilleman cd45ced8b2 Merge remote-tracking branch 'origin/main' into item-469
CI / tests (pull_request) Has been cancelled
2026-11-21 00:47:25 +01:00
lilleman 6d04954b66 Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); the stability answer of round 2 holds the fix
CI / tests (pull_request) Has been cancelled
2026-11-21 00:47:19 +01:00
lilleman 0f3d42e0e7 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); let the in-memory store, which the dry run uses, take any transition to the first status asked for 2026-11-21 00:47:19 +01:00
lilleman a8933b9ab3 Sort test_mutate_changes.py's imports by their first binding
CI / tests (pull_request) Successful in 3m54s
2026-11-21 00:42:27 +01:00
lilleman 44d5eae6d8 Finish item 500 in the plan
CI / tests (pull_request) Failing after 5m3s
2026-11-21 00:36:50 +01:00
lilleman 245b8262a2 Merge remote-tracking branch 'origin/main' into item-500 2026-11-21 00:36:50 +01:00
lilleman ea75ff3a4a Merge origin/main into item-500: keep main's reading-cost figures
CI / tests (pull_request) Has been cancelled
2026-11-21 00:34:08 +01:00
lilleman d6a54d1ca7 File item for running the commands a changed doc line says print something
CI / tests (pull_request) Successful in 3m52s
2026-11-21 00:32:48 +01:00
lilleman 5ea795c694 Answer prose round 1: 1 🔴, 5 🟡 (0 misread); name each pronoun's referent here, beside the help and README wording in the stability answer 2026-11-21 00:31:37 +01:00
lilleman b0d08a3116 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the stability answer refuses a transition to an unlisted status and says so 2026-11-21 00:31:37 +01:00
lilleman 3273852b58 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); make the landed move only where its transition leads to an unblocking status, read the issue's status first, move parents after planning, and list do_epic's files one per bullet 2026-11-21 00:31:37 +01:00
lilleman e25dd3c531 Answer stability round 2: 1 🔴, 0 🟡 (0 misread); pin diff.interHunkContext too
CI / tests (pull_request) Failing after 4m18s
2026-11-21 00:19:24 +01:00
lilleman e8cd651bb8 Kill the mutants of the move by a transition, and sort the new files' imports
CI / tests (pull_request) Successful in 3m0s
2026-11-21 00:08:45 +01:00
lilleman 83191daf0d Answer prose round 1: 0 🔴, 5 🟡 (0 misread); the help, docstring and test-name wording are in the stability commit
CI / tests (pull_request) Failing after 3m56s
2026-11-21 00:02:27 +01:00
lilleman 86cdf96b28 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the total, the root container's safe.directory and the *_test.go line are in the stability commit 2026-11-21 00:02:27 +01:00
lilleman 846d6c6e36 Answer stability round 1: 1 🔴, 2 🟡 (0 misread); pin the git diff settings Gremlins parses, show the mutant total, and a container prefix that runs as root 2026-11-21 00:02:27 +01:00
lilleman 0e3b0811fb Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-20 23:55:11 +01:00
lilleman d5191410d2 Finish item 479 in the plan
CI / tests (pull_request) Successful in 3m33s
2026-11-20 23:54:55 +01:00
lilleman 9020193e4d Answer prose round 1: 1 🔴, 4 🟡 (0 misread); state what the probes show, not what the loop does yet, and fix negations and unclear referents
CI / tests (pull_request) Has been cancelled
2026-11-20 23:54:45 +01:00
lilleman 0281c78d14 Move a parent whose sub-tasks a person filed once they have landed or are done
CI / tests (pull_request) Failing after 2m53s
2026-11-20 23:54:08 +01:00
lilleman 89f5fcbc16 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-20 23:53:04 +01:00
lilleman fcd6c69cc2 Record the reading cost of item 479's chunk
CI / tests (pull_request) Has been cancelled
2026-11-20 23:52:07 +01:00
lilleman 8117daba6e Record that a Claude home of its own loads the setup and signs in by a long-lived token, but not under --bare 2026-11-20 23:52:07 +01:00
lilleman 49964b5d64 Finish item 472 in the plan
CI / tests (pull_request) Successful in 3m26s
2026-11-20 23:43:29 +01:00
lilleman b6a27cc4dd Pin do-epic's tests to the order that asks origin before the fetch
CI / tests (pull_request) Successful in 3m36s
2026-11-20 23:39:46 +01:00
lilleman e3cc18f04e Test the git settings Gremlins' environment gets
CI / tests (pull_request) Failing after 4m8s
2026-11-20 23:38:39 +01:00
lilleman 49d37891fe Drop the decision's citation of the item this chunk finishes 2026-11-20 23:35:31 +01:00
lilleman b014bec299 Merge remote-tracking branch 'origin/main' into item-472
CI / tests (pull_request) Failing after 3m37s
# Conflicts:
#	docs/reading-cost.md
2026-11-20 23:35:16 +01:00
lilleman 071a350e2b Answer stability round 2: 0 🔴, 1 🟡 (0 misread); ask origin for the epic branch before the fetch, so a branch another chunk makes in between doesn't fail the start 2026-11-20 23:35:07 +01:00
lilleman a430bca9f9 Mutate the Go lines a branch changes with Gremlins in mutate-changes
CI / tests (pull_request) Successful in 3m54s
2026-11-20 23:24:21 +01:00
lilleman e37dafb753 Record the chunk's reading cost
CI / tests (pull_request) Successful in 4m2s
2026-11-20 23:15:43 +01:00
lilleman 1de88b9b20 Block items 469 and 479 on item 472, whose open branch changes the same files
CI / tests (pull_request) Successful in 3m45s
2026-11-20 23:10:50 +01:00
lilleman aa51d5f1be Move item 479 into 0.15.0, ahead of task-bench's container
CI / tests (pull_request) Successful in 3m44s
2026-11-20 23:04:01 +01:00
lilleman d5432d9739 Run task-bench's Haiku in a container with every tool, in place of a Bash allowlist
CI / tests (pull_request) Successful in 3m46s
2026-11-20 22:58:49 +01:00
lilleman b2007553de Plan task-bench: the MVP and Go in mutate-changes in 0.15.0, follow-ups in 0.16.0; drop item 467, move item 469 into 0.15.0 and push 0.16.0 to 0.23.0 one release later
CI / tests (pull_request) Has been cancelled
2026-11-20 22:55:21 +01:00
Lilleman e820a0c87c Kill the mutants that survived the stability round's fixes
CI / tests (pull_request) Successful in 3m27s
2026-11-20 22:00:40 +01:00
Lilleman 3543221235 Answer prose round 1: 0 🔴, 16 🟡 (0 misread); reword the plan's new items and record the code-owns-the-flow decision
CI / tests (pull_request) Successful in 3m56s
2026-11-20 21:58:30 +01:00
Lilleman c0842a5fb8 Record the reading cost of the chunk that plans the standalone install
CI / tests (pull_request) Successful in 3m50s
2026-11-20 21:54:05 +01:00
Lilleman 5d4676ff6b Merge remote-tracking branch 'origin/main' into plan-standalone 2026-11-20 21:53:45 +01:00
Lilleman a9041f9aa0 Plan the standalone install as releases 0.16.0 to 0.21.0, and move 0.16.0 and 0.17.0 to 0.22.0 and 0.23.0 2026-11-20 21:53:40 +01:00
Lilleman d464f271bf Answer stability round 1: 1 🔴, 5 🟡 (0 misread); hold a pull request's base on the forge to the recorded one, ask origin for the epic branch, and name where a chunk's work landed
CI / tests (pull_request) Successful in 3m46s
2026-11-20 21:42:32 +01:00
Lilleman 64e33ae209 Finish item 474 in the plan
CI / tests (pull_request) Successful in 5m27s
2026-11-20 21:26:47 +01:00
Lilleman 73183957ae Answer prose round 1: 0 🔴, 4 🟡 (0 misread); docstrings, help text, message and import order reworded (fixed in the stability commit)
CI / tests (pull_request) Has been cancelled
2026-11-20 21:26:22 +01:00
Lilleman eed81c905a Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); a crash in mutmut is now one report line, so the other folders still report (fixed in the stability commit) 2026-11-20 21:26:22 +01:00
Lilleman ce0344f703 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); tell mutmut's own frames by their site-packages path, take the error from after the last frame, and fix the module docstring and help 2026-11-20 21:26:22 +01:00
Lilleman 8d896d772d Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to answer 2026-11-20 20:51:43 +01:00
Lilleman 525f3f8836 Kill the mutants that survived on the epic branch's changed lines
CI / tests (pull_request) Successful in 3m45s
2026-11-20 20:47:46 +01:00
Lilleman e3a964a73f Answer prose round 1: 0 🔴, 10 🟡 (0 misread); reword the prompts, help and decision entry, and put the entry after do-epic's
CI / tests (pull_request) Successful in 3m46s
2026-11-20 20:15:33 +01:00
Lilleman ce2e9dc0e5 Answer product-owner round 1: 0 🔴, 4 🟡 (0 misread); move through the open status, refuse open-epic without a branch, tell a conflict from git's other failures 2026-11-20 20:15:33 +01:00
Lilleman 9bd385d9cd Kill the surviving mutants of the file-name import move and the mutmut crash line 2026-11-20 20:04:03 +01:00
Lilleman 9f367e90ca Answer security round 1: 0 🔴, 0 🟡 (0 misread); refuse a malformed epic key and a comment that starts with a dash
CI / tests (pull_request) Successful in 3m44s
2026-11-20 19:44:52 +01:00
Lilleman 72a4d346d7 Let a project's config name a working branch per epic that chunks branch off and merge into
CI / tests (pull_request) Successful in 5m4s
2026-11-20 19:32:59 +01:00
Lilleman 91cf86e0cd Run mutate-changes on a script its tests import by file name, and name a crash inside mutmut in one line 2026-11-20 19:12:10 +01:00
Lilleman cd8e335c3e Append the reading-cost figures of the last chunks 2026-11-20 19:12:09 +01:00
Lilleman 9531e5c337 Finish item 454 in the plan
CI / tests (pull_request) Successful in 4m11s
2026-11-20 18:57:54 +01:00
Lilleman 58df9029b6 Merge remote-tracking branch 'origin/main' into item-454 2026-11-20 18:57:53 +01:00
Lilleman 88d9240e65 Take the default branch's reading-cost figures, which hold this chunk's
CI / tests (pull_request) Has been cancelled
2026-11-20 18:55:19 +01:00
Lilleman d7c63a680f Merge remote-tracking branch 'origin/main' into item-454 2026-11-20 18:55:08 +01:00
Lilleman e83b144cce Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); nothing to answer 2026-11-20 18:54:53 +01:00
Lilleman 460f1859fb Answer stability round 2: 0 🔴, 0 🟡 (0 misread); nothing to answer 2026-11-20 18:54:52 +01:00
Lilleman d7f72bd6c5 Move item 474 to 0.15.0 so mutation tests run in docs-and-tools before TW-13503
CI / tests (pull_request) Successful in 3m45s
2026-11-20 18:52:23 +01:00
Lilleman 63bd094ec3 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword the start's settings, docstrings and messages
CI / tests (pull_request) Successful in 3m44s
2026-11-20 18:39:55 +01:00
Lilleman 8a067c8d61 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); say in the help and the dry run that a starting chunk starts its issue in Jira 2026-11-20 18:39:55 +01:00
Lilleman ea58203b1a Answer stability round 1: 0 🔴, 1 🟡 (0 misread); name every step a start could not take, and who else holds the issue 2026-11-20 18:39:55 +01:00
Lilleman 229566e839 Finish item 476 in the plan
CI / tests (pull_request) Successful in 3m42s
2026-11-20 18:33:31 +01:00
Lilleman 19b0c0a372 Answer prose round 1: 0 🔴, 0 🟡 (0 misread); both 🟢 fixed in the stability round's commit
CI / tests (pull_request) Has been cancelled
2026-11-20 18:21:52 +01:00
Lilleman 2fbd5c9f8b Answer stability round 1: 0 🔴, 1 🟡 (0 misread); count each --tools against a --strict-mcp-config 2026-11-20 18:21:52 +01:00
Lilleman 7fcc979b59 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-20 18:12:50 +01:00
Lilleman 6bd146395c Test the start's failure messages and shapes that mutants survived
CI / tests (pull_request) Successful in 3m42s
2026-11-20 18:03:55 +01:00
Lilleman a75826d35a Load no MCP server in the bench's headless claude calls that are denied tools
CI / tests (pull_request) Successful in 3m45s
2026-11-20 18:02:12 +01:00
Lilleman 0b13a7ad44 Finish item 473 in the plan
CI / tests (pull_request) Successful in 5m23s
2026-11-20 17:55:25 +01:00
Lilleman 506fbae5b9 Answer stability round 1: 0 🔴, 0 🟡 (0 misread); no findings
CI / tests (pull_request) Has been cancelled
2026-11-20 17:55:15 +01:00
Lilleman ac6085cc5c Record the reading cost of item 473's chunk
CI / tests (pull_request) Successful in 3m41s
2026-11-20 17:31:23 +01:00
Lilleman 471cdf89e7 File item 476: load no MCP server in the bench's headless claude calls that are denied tools
CI / tests (pull_request) Has been cancelled
2026-11-20 17:31:20 +01:00
Lilleman f40f7eb95c Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to answer 2026-11-20 17:28:53 +01:00
Lilleman c062f8793f Kill the two surviving mutants of the headless claude calls
CI / tests (pull_request) Has been cancelled
2026-11-20 17:27:58 +01:00
Lilleman 5cb0feba07 Sort the imports of the Jira start module
CI / tests (pull_request) Successful in 3m44s
2026-11-20 17:27:58 +01:00
Lilleman 1b127da3db Record the reading cost before item 454's first commit
CI / tests (pull_request) Failing after 3m44s
2026-11-20 17:23:58 +01:00
Lilleman 653fcbe3f1 Start a do-epic chunk's issue in Jira: assigned, moved by a start transition and added to a board's active sprint 2026-11-20 17:23:58 +01:00
Lilleman b612e43276 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-20 17:16:26 +01:00
Lilleman 700ac3e2ce Load no MCP server in a headless claude call that is denied tools
CI / tests (pull_request) Successful in 3m45s
2026-11-20 17:15:42 +01:00
Lilleman 00b87e3fb9 Merge remote-tracking branch 'origin/main' into item-470
CI / tests (pull_request) Successful in 3m48s
2026-11-20 17:10:30 +01:00
Lilleman 3febd12063 Finish item 470 in the plan
CI / tests (pull_request) Successful in 3m46s
2026-11-20 17:05:25 +01:00
Lilleman aaecb98671 Merge remote-tracking branch 'origin/main' into item-470
CI / tests (pull_request) Has been cancelled
2026-11-20 17:04:59 +01:00
Lilleman c5b5ec78ef Test the names of three items that block each other in a loop
CI / tests (pull_request) Has been cancelled
2026-11-20 17:04:43 +01:00
lilleman 8465886566 File item 475: have stability-reviewer report a lookup outside data can make fail without naming what was missing
CI / tests (pull_request) Successful in 3m43s
2026-11-20 17:02:30 +01:00
Lilleman 9ac35a4699 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); name an issue by its key where the ranking words the failure
CI / tests (pull_request) Successful in 3m44s
2026-11-20 16:40:43 +01:00
Lilleman b01b799743 Name an item by its key without a fallback no ranking reaches
CI / tests (pull_request) Successful in 4m3s
2026-11-20 16:36:34 +01:00
Lilleman 113ec64f89 File item 474: run mutate-changes where tests import a script by its file name
CI / tests (pull_request) Successful in 3m30s
2026-11-20 16:19:44 +01:00
Lilleman 27b6433f7d Answer stability round 1: 0 🔴, 5 🟡 (0 misread); order issues whose keys share a number, and test the goals that fail, a malformed held score and the scoring call's folder
CI / tests (pull_request) Successful in 5m10s
2026-11-20 16:09:06 +01:00
Lilleman abe7226baa Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); print a status without cloning a repo, and say in the contract that the comment goes first
CI / tests (pull_request) Successful in 4m30s
2026-11-20 15:48:27 +01:00
Lilleman 481e13253a Test the scoring call, its answer and the refusals a mutant survived
CI / tests (pull_request) Has been cancelled
2026-11-20 15:45:45 +01:00
Lilleman af81dcdcbc File item 473: headless claude calls that are denied tools load no MCP server
CI / tests (pull_request) Successful in 3m40s
2026-11-20 15:18:22 +01:00
Lilleman fdbb007e21 Merge remote-tracking branch 'origin/main' into item-470 2026-11-20 15:18:18 +01:00
Lilleman 922d26de09 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change
CI / tests (pull_request) Has been cancelled
2026-11-20 15:14:50 +01:00
Lilleman 6016f6554c Answer prose round 1: 0 🔴, 9 🟡 (0 misread); say when issues are scored, what the comment tells, and who chose the start order 2026-11-20 15:14:50 +01:00
Lilleman 4557dced58 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); comment before the scores are set, score no issue whose work has landed, and say after which issues one starts 2026-11-20 15:14:14 +01:00
Lilleman 6c406b2609 Sort the imports and type the step that sets an issue's scores
CI / tests (pull_request) Successful in 3m39s
2026-11-20 14:39:10 +01:00
Lilleman 5f2a4b6385 Start an epic's issues in order of score, scoring each that holds none 2026-11-20 14:30:30 +01:00
Lilleman fbe133831f File item 472: chunks merge into a working branch per epic, which a person merges into main
CI / tests (pull_request) Successful in 3m39s
2026-11-20 14:27:09 +01:00
Lilleman abaf54bc46 Move item 469 to 0.15.1 so 0.15.0 ships sooner
CI / tests (pull_request) Successful in 3m37s
2026-11-20 14:11:51 +01:00
Lilleman f1ae4d63b1 Finish item 453 in the plan
CI / tests (pull_request) Successful in 6m14s
2026-11-20 14:00:24 +01:00
Lilleman 5f340d96a3 Merge remote-tracking branch 'origin/main' into item-453
CI / tests (pull_request) Has been cancelled
2026-11-20 13:57:44 +01:00
Lilleman 0e386f8ca3 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Has been cancelled
2026-11-20 13:57:40 +01:00
Lilleman a0e1d2aea2 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-11-20 13:57:40 +01:00
Lilleman 3991b0276e Finish item 468 in the plan
CI / tests (pull_request) Successful in 4m47s
2026-11-20 13:47:24 +01:00
Lilleman 31f9360b9c Kill the mutant that always named the review setting
CI / tests (pull_request) Has been cancelled
2026-11-20 13:47:16 +01:00
Lilleman b8fce0113a Answer prose round 1: 2 🔴, 5 🟡 (0 misread); reword the issue type text and tests
CI / tests (pull_request) Successful in 3m4s
2026-11-20 13:40:07 +01:00
Lilleman 3d3f8c9a66 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); read the issue types in one place, skip the epic type, and say what todo-item add files 2026-11-20 13:40:07 +01:00
Lilleman 98d1fc1eba Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); name the setting to change where the Jira project lacks the issue type 2026-11-20 13:40:07 +01:00
Lilleman 92b0acb5c6 Merge remote-tracking branch 'origin/main' into item-468
CI / tests (pull_request) Has been cancelled
2026-11-20 13:22:38 +01:00
Lilleman 719bebe37f Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-11-20 13:22:31 +01:00
Lilleman a9702c1f2f Kill the mutants of the issue type settings 2026-11-20 12:40:02 +01:00
Lilleman 422ed13f2e Answer prose round 1: 0 🔴, 1 🟡 (0 misread); sort the repos, reword the docstring and test names, in 868169cc
CI / tests (pull_request) Successful in 3m1s
2026-11-20 12:30:23 +01:00
Lilleman 6e162d2536 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the next pull request's label comes from label_of, in 868169cc 2026-11-20 12:30:23 +01:00
Lilleman 868169ccb6 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); pin the sentence once at worked_by, and the product-owner and prose fixes beside it 2026-11-20 12:30:23 +01:00
Lilleman a84c39d798 File item 471: ship jira-rest as a claude-config tool
CI / tests (pull_request) Successful in 2m49s
2026-11-20 12:26:13 +01:00
Lilleman a7d034acb9 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings
CI / tests (pull_request) Successful in 3m39s
2026-11-20 12:08:40 +01:00
Lilleman df224cc82a File items 469 and 470: move do-epic's parent issues and start issues by score
CI / tests (pull_request) Successful in 2m50s
2026-11-20 11:56:19 +01:00
Lilleman ff16a80546 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-20 11:47:02 +01:00
Lilleman ecff566bc6 Say in the decision that a project config may name the issue type an item is filed as 2026-11-20 11:32:00 +01:00
Lilleman d83d39dd2d Append the reading-cost figures
CI / tests (pull_request) Successful in 2m58s
2026-11-20 11:31:44 +01:00
Lilleman 34328b11b9 File findings, release reviews and added items as the issue types the settings name, and refuse a type the Jira project lacks 2026-11-20 11:31:44 +01:00
Lilleman 2078ba0185 Append reading-cost figures
CI / tests (pull_request) Successful in 2m57s
2026-11-20 11:18:07 +01:00
Lilleman 9f09912a02 Name the team's label for each repo in do-epic's finding and release-review prompts 2026-11-20 11:18:07 +01:00
Lilleman 88fee92dcb Finish item 449 in the plan
CI / tests (pull_request) Successful in 2m50s
2026-11-20 11:13:03 +01:00
Lilleman 44ba6569b2 Merge remote-tracking branch 'origin/main' into item-449
CI / tests (pull_request) Successful in 3m26s
# Conflicts:
#	todo.md
2026-11-20 11:08:36 +01:00
Lilleman 5f814a8a89 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-11-20 11:07:09 +01:00
Lilleman e0b2068230 Answer stability round 2: 0 🔴, 2 🟡 (0 misread); keep Python's reason in the unreadable-template message and pin fragments of the messages
CI / tests (pull_request) Has been cancelled
2026-11-20 11:07:02 +01:00
Lilleman 4a8b8b3e9d Finish item 450 in the plan
CI / tests (pull_request) Successful in 2m29s
2026-11-20 10:52:00 +01:00
Lilleman 0fd5e91c2e Merge remote-tracking branch 'origin/main' into item-450 2026-11-20 10:51:59 +01:00
Lilleman 51d3f9bc90 File item 467: cut 0.15.0 before its release review, and run that review in 0.15.1
CI / tests (pull_request) Successful in 2m50s
2026-11-20 10:47:52 +01:00
Lilleman c39d23a1b3 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); name each template fault truly and pass the template to split
CI / tests (pull_request) Successful in 2m33s
2026-11-20 10:46:19 +01:00
Lilleman 3e8910f573 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); reword the README bullets and the template's messages 2026-11-20 10:46:19 +01:00
Lilleman d004fde8ce Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the first line of the table stands for a repo it names twice 2026-11-20 10:46:19 +01:00
Lilleman 5fb0f95e0c File item 467: tell a do-epic worker the team's label for each repo 2026-11-20 10:46:12 +01:00
Lilleman 12ace75f15 Sort the dry run's imports by their first binding
CI / tests (pull_request) Successful in 2m29s
2026-11-20 10:43:14 +01:00
Lilleman acb3371bbe Merge remote-tracking branch 'origin/main' into item-450
CI / tests (pull_request) Failing after 3m40s
2026-11-20 10:28:15 +01:00
Lilleman 7639933f99 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); put the dry-run note before the reason and warn in --help that another repo's chunk may take a place
CI / tests (pull_request) Failing after 3m38s
2026-11-20 10:16:54 +01:00
Lilleman aed6a84abc Type the template that DoEpicConfig takes
CI / tests (pull_request) Successful in 2m58s
2026-11-20 10:15:58 +01:00
Lilleman 388f726613 Pin the real run's not-planned-in-full line, which carries no dry-run note
CI / tests (pull_request) Has been cancelled
2026-11-20 10:14:53 +01:00
Lilleman ec2779ad1c Answer prose round 1: 0 🔴, 8 🟡 (0 misread); the prose fixes are in the product-owner commit
CI / tests (pull_request) Failing after 2m33s
2026-11-20 09:53:07 +01:00
Lilleman 4853922d55 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); the dry run says what a missing repo does, in the previous commit 2026-11-20 09:53:07 +01:00
Lilleman 5630c3ba2e Answer product-owner round 1: 1 🔴, 1 🟡 (0 misread); say when planning stops at a missing repo, mark what the dry run would do, and reword its text and docs (the stability and prose answers are in this commit too) 2026-11-20 09:53:06 +01:00
Lilleman 194acd07f7 Kill the surviving mutants of the summary template's checks
CI / tests (pull_request) Failing after 2m39s
2026-11-20 09:34:19 +01:00
Lilleman 2c0673f5bf Kill the surviving mutants of the dry run: pin the tmux and git wrappers, the write log and the printed output
CI / tests (pull_request) Failing after 2m36s
2026-11-20 09:24:49 +01:00
Lilleman af2593370a Log a label among the writes a dry run prints
CI / tests (pull_request) Failing after 2m39s
2026-11-20 09:13:36 +01:00
Lilleman 798f08dc98 Finish item 466 in the plan
CI / tests (pull_request) Successful in 2m51s
2026-11-20 09:12:35 +01:00
Lilleman 0c44db8442 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Has been cancelled
2026-11-20 09:12:19 +01:00
Lilleman 2199a08df8 Answer stability round 1: 0 🔴, 0 🟡 (0 misread); the two 🟢s are fixed in the prose round's rewrite 2026-11-20 09:12:16 +01:00
Lilleman 31610254d8 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); name the separator-as-data case and say last part for leaf 2026-11-20 09:12:16 +01:00
Lilleman 15c978b708 Record do-epic's repo picks and sub-task summaries in the team's own spelling
CI / tests (pull_request) Failing after 2m33s
2026-11-20 09:10:55 +01:00
Lilleman 1b022f4505 Add do-epic --dry-run, which prints the Jira writes planning would make and the chunks that would start, and makes none
CI / tests (pull_request) Failing after 2m36s
2026-11-20 09:09:15 +01:00
Lilleman 55e855983f Have stability-reviewer check a separator split against a value holding the separator
CI / tests (pull_request) Successful in 3m40s
2026-11-20 09:01:35 +01:00
Lilleman e9e11f10a0 Cut release 0.14.0
CI / tests (pull_request) Successful in 2m47s
2026-11-20 08:57:52 +01:00
Lilleman ff1fd7596f Move 0.14.0's open items to 0.15.0 and every later release up one, so 0.14.0 ships the judge's transcript fix now 2026-11-20 08:57:52 +01:00
lilleman f75c13013d File item 466: stability-reviewer checks a separator split against a value holding the separator
CI / tests (pull_request) Successful in 3m39s
2026-11-20 08:21:59 +01:00
Lilleman afbaa953e6 Finish item 465 in the plan
CI / tests (pull_request) Successful in 5m50s
2026-11-20 01:51:11 +01:00
Lilleman 713d559c5b Finish item 464 in the plan 2026-11-20 01:51:10 +01:00
Lilleman 1774bb4274 Finish item 463 in the plan 2026-11-20 01:51:10 +01:00
Lilleman dbe275e59f Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); every round 1 answer stands
CI / tests (pull_request) Has been cancelled
2026-11-20 01:41:42 +01:00
Lilleman 5e54057f9e Answer stability round 2: 0 🔴, 2 🟡 (0 misread); report each fact of the shortfall in a subTest, and check that a transcript longer than the floor is shown whole where the records leave room
CI / tests (pull_request) Successful in 2m51s
2026-11-20 01:41:21 +01:00
Lilleman ee44c99f28 Test that the judge's failure names a room of 0 where the records overflow its prompt
CI / tests (pull_request) Successful in 3m41s
2026-11-20 01:36:22 +01:00
Lilleman 840cb21fbc Answer prose round 1: 0 🔴, 4 🟡 (0 misread); the wording is fixed in e062f71d
CI / tests (pull_request) Successful in 2m54s
2026-11-20 01:24:24 +01:00
Lilleman b76a3bcf24 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the failure names the shortfall in e062f71d, and item 298 records claude-config's judge room 2026-11-20 01:24:24 +01:00
Lilleman e062f71d47 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); tie the help's transcript floor to TRANSCRIPT_FLOOR, split the floor test, and name the shortfall in the judge's failure, with the prose round's wording 2026-11-20 01:24:21 +01:00
Lilleman 32a81b0257 Test that a head leaving exactly the floor still shows the transcript
CI / tests (pull_request) Successful in 3m7s
2026-11-20 00:59:11 +01:00
Lilleman 105e723617 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-20 00:50:04 +01:00
Lilleman 4fe37104aa Say that a record is read once where its text equals an earlier one's
CI / tests (pull_request) Successful in 2m49s
2026-11-20 00:48:51 +01:00
Lilleman 9e41a4fc64 Name the judge's transcript floor in loop-claude's help and sort the effects test's imports 2026-11-20 00:48:42 +01:00
Lilleman f3af5e23fd Stop the judge rather than show it under 50,000 characters of the transcript, read a twice-named record once, test the forge timeout and decide the merge stop from the pull requests found 2026-11-20 00:45:49 +01:00
Lilleman 5ed3a55e3a File items 464 and 465 from item 457's mutation run and paired ruling
CI / tests (pull_request) Successful in 2m55s
2026-11-20 00:33:41 +01:00
Lilleman d516a28750 Finish item 457 in the plan
CI / tests (pull_request) Successful in 3m2s
2026-11-20 00:28:46 +01:00
Lilleman 20b13065ea Name the forge read in release_standing's docstring 2026-11-20 00:28:29 +01:00
Lilleman 45115ef5e4 Record the comprehension check: same 2026-11-20 00:28:29 +01:00
Lilleman 2797e11080 Check the awaited-merges stop in one place and name the pull-request listing in the package notes
CI / tests (pull_request) Successful in 3m1s
2026-11-20 00:25:37 +01:00
Lilleman 500bd126a4 Merge remote-tracking branch 'origin/main' into item-457
CI / tests (pull_request) Successful in 3m44s
2026-11-20 00:19:09 +01:00
Lilleman fb0a7ac8cf Answer stability round 2: 0 🔴, 0 🟡 (0 misread); every answer holds
CI / tests (pull_request) Has been cancelled
2026-11-20 00:16:35 +01:00
Lilleman 7f9237e91e Test the forge runner's folder and timeout message, and the loop's forge effect
CI / tests (pull_request) Has been cancelled
2026-11-20 00:12:55 +01:00
Lilleman 6e22149334 Finish item 460 in the plan
CI / tests (pull_request) Successful in 4m32s
2026-11-20 00:10:43 +01:00
Lilleman ee296c332a Merge remote-tracking branch 'origin/main' into item-460 2026-11-20 00:10:42 +01:00
Lilleman a9bdef6fcb Merge remote-tracking branch 'origin/main' into item-460
CI / tests (pull_request) Has been cancelled
2026-11-20 00:06:58 +01:00
Lilleman 4586bfcbea Finish item 452 in the plan
CI / tests (pull_request) Successful in 3m0s
2026-11-20 00:04:15 +01:00
Lilleman 3d19ec9c6c Merge remote-tracking branch 'origin/main' into item-452 2026-11-20 00:04:14 +01:00
Lilleman 6fda959b52 Parenthesize the condition under which do-epic only reads an issue
CI / tests (pull_request) Has been cancelled
2026-11-20 00:03:18 +01:00
Lilleman 04c67d958e Answer stability round 2: 0 🔴, 0 🟡 (0 misread); tests and mutants clean at 3cce4043
CI / tests (pull_request) Successful in 3m23s
2026-11-20 00:02:03 +01:00
Lilleman afc51efb1b Answer stability round 1: 0 🔴, 0 🟡 (0 misread); decline the 🟢 on a NUL in the evidence, which the judge does not write 2026-11-20 00:01:03 +01:00
Lilleman ecc69835b8 File item 463: show the judge the transcript's tail whatever the size of the records
CI / tests (pull_request) Successful in 3m21s
2026-11-19 23:59:38 +01:00
Lilleman 3d34411e24 Merge remote-tracking branch 'origin/main' into item-452
CI / tests (pull_request) Successful in 3m1s
2026-11-19 23:54:56 +01:00
Lilleman 535ad7fd6a Answer stability round 1: 0 🔴, 1 🟡 (1 misread); leave a human's task unmoved and unawaited where the team's automation moves issues 2026-11-19 23:54:55 +01:00
Lilleman 5108ab97b9 File item 462: run under mutate-changes the tests mutmut's copy leaves out
CI / tests (pull_request) Successful in 3m29s
2026-11-19 23:46:34 +01:00
Lilleman 3cce40437e Let prepare-scoring read claude-config's scoring-run values from seat-prompts.md where docs/decisions.md holds none
CI / tests (pull_request) Successful in 3m53s
2026-11-19 23:39:54 +01:00
Lilleman 69cf298597 Finish item 459 in the plan
CI / tests (pull_request) Successful in 5m33s
2026-11-19 23:39:46 +01:00
Lilleman b559775455 Finish item 458 in the plan 2026-11-19 23:39:46 +01:00
Lilleman 3d6227009d Merge remote-tracking branch 'origin/main' into item-458
CI / tests (pull_request) Has been cancelled
2026-11-19 23:39:12 +01:00
Lilleman 2efe914521 Finish item 461 in the plan
CI / tests (pull_request) Successful in 3m47s
2026-11-19 23:34:00 +01:00
Lilleman 04852c3417 Record the comprehension check: Navigation 7.00, Locality 6.00, Shape 6.13, Self-sufficiency 6.00, Overall 6.38
CI / tests (pull_request) Has been cancelled
2026-11-19 23:33:46 +01:00
Lilleman 0c52688ff8 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); bound the forge's CLI with a timeout in one runner, and read a pull request from a deleted fork
CI / tests (pull_request) Successful in 3m20s
2026-11-19 23:30:30 +01:00
Lilleman 356ae263e1 Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); exit 0 on awaited merges, so the finished chunk's window closes and the next run reads the plan 2026-11-19 23:30:30 +01:00
Lilleman 29b1be3fd7 Test how grounds_of splits an archived prompt, to kill the mutants that survived on its changed lines
CI / tests (pull_request) Successful in 3m49s
2026-11-19 23:25:38 +01:00
Lilleman 1a23aa05b0 Test that loop-claude starts no chunk where every item left awaits a person's merge
CI / tests (pull_request) Successful in 3m25s
2026-11-19 23:17:04 +01:00
Lilleman daee3c671f Test the human's task under the automation switch, a repeated failed read and the list of statuses in the wait line
CI / tests (pull_request) Successful in 2m55s
2026-11-19 23:05:10 +01:00
Lilleman a357cc7b18 Answer prose round 1: 0 🔴, 1 🟡 (0 misread); state the repo's fact in the comment and drop the one that restates the pattern
CI / tests (pull_request) Successful in 3m23s
2026-11-19 22:55:34 +01:00
Lilleman 4c109b3411 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); test the unreadable seat-prompts.md and correct prepare-scoring's help 2026-11-19 22:55:34 +01:00
Lilleman 7605094623 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-19 22:52:56 +01:00
Lilleman f9959d25c5 Test that an unblocking status frees a human's task and the issue it blocks
CI / tests (pull_request) Successful in 3m50s
2026-11-19 22:40:00 +01:00
Lilleman 1845d8ff37 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); say that the task and the transcript are searched, and where a quote may not run across them 2026-11-19 22:36:14 +01:00
Lilleman b940f902b8 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); read the epic again where a read fails during the wait, and reword two lines
CI / tests (pull_request) Successful in 3m56s
2026-11-19 22:35:03 +01:00
Lilleman 9caac90a62 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); the wait reasons and the settings' wording are fixed in the product-owner answer
CI / tests (pull_request) Has been cancelled
2026-11-19 22:32:53 +01:00
Lilleman 24bcb9060b Answer product-owner round 1: 1 🔴, 2 🟡 (0 misread); move a chunk's issue where no pull request carries it, wait for the automation's move, and match statuses in any case 2026-11-19 22:32:53 +01:00
Lilleman 7c178038c5 Take the scoring run's values from seat-prompts.md where the working rules hold none
CI / tests (pull_request) Successful in 4m17s
2026-11-19 22:27:29 +01:00
Lilleman 8c693ea5de Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 3m32s
2026-11-19 22:24:57 +01:00
Lilleman 427a2cb7c3 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-19 22:24:56 +01:00
Lilleman d954fb0026 Answer security round 1: 0 🔴, 0 🟡 (0 misread); keep a judge's evidence quote from running across the task and the tail, and name the task in the schema and the rejection message 2026-11-19 22:24:24 +01:00
Lilleman 56c579bd54 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); stop loop-claude where every item left awaits a person's merge
CI / tests (pull_request) Successful in 3m23s
2026-11-19 22:20:43 +01:00
Lilleman 470be28759 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); take the reviewer's rewrites 2026-11-19 22:20:43 +01:00
Lilleman 0f5e8897e2 Answer prose round 1: 0 🔴, 3 🟡 (1 misread); drop the flags a do-epic worker never passes, and reword the added sentences
CI / tests (pull_request) Successful in 3m55s
2026-11-19 22:04:59 +01:00
Lilleman e2c4993cc6 Answer product-owner round 1: 1 🔴, 0 🟡 (1 misread); the stability round's answer fixes the same handed-on chunk 2026-11-19 22:04:59 +01:00
Lilleman 547afc6cf2 Answer stability round 1: 1 🔴, 0 🟡 (1 misread); tell a finished chunk's worker of a pull request that no longer merges, in place of handing the chunk on 2026-11-19 22:04:59 +01:00
Lilleman fc4b0387d6 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 3m19s
2026-11-19 21:58:17 +01:00
Lilleman ceacc86a88 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing found 2026-11-19 21:56:07 +01:00
Lilleman 00975177ad Pass over an item whose pull request awaits a person's merge, and hold a sentence about several named things to each
CI / tests (pull_request) Failing after 3m42s
2026-11-19 21:54:43 +01:00
Lilleman 18d28fa472 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-19 21:46:22 +01:00
Lilleman 6d7c8b5c25 Sort the scheduler's imports and type the statuses list
CI / tests (pull_request) Successful in 3m22s
2026-11-19 21:45:44 +01:00
Lilleman 111cb9248e Let do-epic's config name the statuses that unblock an issue and leave the moves to a team's automation 2026-11-19 21:44:08 +01:00
Lilleman 06a1398196 Re-score item 457: scores hold, Touches names the shared pick and the forge 2026-11-19 21:38:20 +01:00
Lilleman 11ee0f7bbf Resume a chunk that awaits a person's merge once its pull request no longer merges into its base
CI / tests (pull_request) Successful in 3m29s
2026-11-19 21:37:01 +01:00
187 changed files with 14520 additions and 970 deletions
+6
View File
@@ -155,6 +155,10 @@
!bin/subagent-rung
!bin/subagent_rung/
!bin/subagent_rung/*.py
!bin/task-bench
!bin/task_bench/
!bin/task_bench/*.py
!bin/task_bench/gather-prompt.md
!bin/test_*.py
!bin/text_files/
!bin/text_files/*.py
@@ -198,6 +202,8 @@
!stability-skip-count/
!stability-skip-count/README.md
!stability-skip-count/count.py
!task-bench-image/
!task-bench-image/Dockerfile
!workflow-bench/
!workflow-bench/advisor-judge-prompt.md
!workflow-bench/advisor-run-prompt.md
+56
View File
@@ -1,5 +1,61 @@
# Changelog
## Unreleased
- `task-bench` plants bugs in PHP, from the mutants Infection logs as killed, and reads the task it gives from the message PHPUnit prints.
- `task-bench` plants bugs in TypeScript and JavaScript, from the mutants Stryker reports as killed, and reads the task it gives from the error `node --test` prints.
- Testing principles now say that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete.
- task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart.
- loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human.
- larv-review's prose pass takes a second round after a fix that rewrites a claim a command or a source file can check, such as generated output, a number or a licence term.
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for a release later than the last cut.
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself.
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
- This repo documents its own `task-bench` command in the README → Test, with `task-bench-image/Dockerfile`, an image that holds pytest, git and tmux, so each scoring run in `larv-review` benches claude-config and records its figures.
- The stability reviewer now checks a lookup key built by joining path segments, or matched by prefix, for two inputs that give one key, such as a column named like its own table or the namespaces `ns` and `ns.sub`.
- The release review now goes over a project's bench features: it reapplies each reference patch and rewrites one that no longer applies, deletes a feature that no longer breaks a goal, and adds features until each place the comprehension seats find hardest has one.
- `task-bench` plants bugs in Python files too, from the mutants mutmut 3 kills, and tells Haiku the error pytest prints. Where the seats' places name both Go and Python files, one `--prefix` runs both tools; `task-bench --help` shows one.
- `task-bench --tasks data-sources` benches adding a data source: Haiku gets a made-up register that the task's seeded `generate-register` writes, and acceptance tests check the importer, the data and whatever else the spec asks.
- `task-bench --tasks features` has Haiku build features instead of fixing planted bugs: each folder in the folder the project's config names as the new optional `bench-tasks` holds a `spec.md`, a `reference.patch` and acceptance tests Haiku never sees. A feature counts only where those tests fail before it is built and pass with the reference patch, at the base and at the head; the report names each feature passed over and why.
- A bench started with `task-bench --record-figures` appends its figures over every bug to the comprehension history once it finishes, and a scoring run in `larv-review` starts the project's bench that way where its README documents a `task-bench` command. The figures are a report beside the panel's scores: none blocks a merge.
- `task-bench`'s table prints the mean of the bugs' own head/base changes as its All change, in place of the change of the two All rows' medians, which swung up to three times as far in tokens. The All rows per side stay, so the change row is no longer their difference, and a change from before 0.16.0 can't be compared with one from after it.
- `task-bench` now stops with a Failure on a run whose final result says `terminal_reason: "api_error"`, even where it holds no `api_error_status`, so a token the API refuses no longer lets the bench run on for hours with empty runs.
- `task-bench`'s `--help` now says how far a bench of a commit against itself swings, in 19 cases of 20, with the default 5 bugs and 5 runs, and that a Gremlins run on a large project needs 16 GB of memory.
- When `task-bench` can't copy, read or write a file in the middle of a bench, it now names that file and still prints the table of the runs that finished, where 0.15.0 lost them all behind `could not write under <folder>`.
## 0.15.1
- `do-epic` and `todo-item edit` save an issue's scores in a Jira epic again. Jira refuses an edit that holds only issue properties, so 0.15.0 posted the comment with the scores but lost the scores themselves, and scored the issue again on the next run; each score now goes through the issue property's own endpoint.
## 0.15.0
- `task-bench` writes `digest.md`, with each bug's decoys and up to two traces of its runs, and `task-bench gather` starts a claude on the project's rung that files a plan item for each place the digest shows to be hard, then removes the bench's folder. Each bench removes the folders earlier benches left, and `compress-archives` leaves lock files alone.
- `task-bench` is new: it plants bugs that a Go project's tests catch, at the places the comprehension seats found hardest, and has Haiku fix each in a container at a base commit and at a head. It prints for each side how often the fix passes, with the median tokens, turns, wall time and reads before Haiku opens the file the bug is in. `task-bench --help` says how to run it.
- larv-review now runs each command that a changed doc line says prints something and hands the real output to the product-owner and prose reviewers, so a claim about output is checked by running it.
- `do-epic` moves a parent issue whose sub-tasks a person filed: to done by `jira-finish-transition` once every sub-task is done, and before that by the transition the new setting `jira-sub-tasks-landed-transition` names, once each sub-task is done or in one of `jira-unblocking-statuses`. The transition must lead to one of those statuses. `--dry-run` prints each such move.
- mutate-changes now mutates the Go lines a branch changes with Gremlins, as it does Python, Rust, TypeScript and PHP, and prints each mutant the tests do not kill.
- A project's config may set `epic-branch`, such as `epic-branch = "{epic}"`: do-epic then keeps one working branch per epic, level with the default branch by merge commits, and each chunk branches off it and merges into it without waiting for a person, even under `merge = "human"`. `chunk-pr open-epic` opens the finished epic's pull request into the default branch for a person to merge. `review-request-comment` names a comment `chunk-pr` posts after each push to ask a forge's reviewer for a review, and `jira-pull-request-open-status` and `jira-pull-request-merged-status` name the statuses do-epic moves an issue to as its pull request opens and merges.
- `mutate-changes` mutates a Python script from its own folder where a test beside it imports it by its file name, as in `import run_harness`, so mutmut finds the tests' calls to it. A crash inside mutmut now becomes one report line that names mutmut's error, not a traceback, and the other folders still report.
- do-epic starts an issue in Jira as its chunk starts: it assigns the issue to the account it works as, unless someone else holds it, and the new settings `jira-start-transition` and `jira-sprint-board` in its `config.toml` move the issue and add it to a board's active sprint.
- Load no MCP server in the bench's headless `claude -p` judge and in the reviewer-merge trials' new-findings call either, so text an outsider wrote cannot reach one. A new check fails any Python file that passes `--tools` more often than `--strict-mcp-config`.
- Load no MCP server in the six headless `claude -p` calls that deny the model tools, so text an outsider wrote cannot reach one.
- `do-epic` starts an epic's runnable issues in order of score alone, not in Jira's backlog order. It scores each open issue that holds no scores, the ones people filed included, and comments on the issue why.
- do-epic and `todo-item add` file issues as the Jira issue types the settings `jira-finding-type` and `jira-review-type` name, Task by default, and refuse before filing where the Jira project lacks the type, naming the types it has.
- do-epic names the team's own label for each repo, from the `[label-repos]` table, when it tells a chunk's worker how to file a finding or a release review, and keeps `repo:<name>` for a repo the table doesn't name.
- do-epic records a repo pick, and the summary of each sub-task it files, in the team's own spelling: a label from the `[label-repos]` table of its config, and a `sub-task-summary` template with `{label}` and `{Summary}`.
- Add `do-epic <EPIC-KEY> --dry-run`, which prints every Jira write planning would make and each chunk that would start, and makes none of them.
- The stability reviewer checks each parser that splits text on a separator or strips a suffix against a value that holds the separator, and reports a row the parse misplaces or drops.
## 0.14.0
- `loop-claude`'s judge stops, naming how much to cut the records by, rather than judge a prompt that leaves it less than the transcript's last 50,000 characters. A file the project's config names for two records is read once.
- Under `merge = "human"`, `loop-claude` and `chunk-preflight` pass over an item whose ready pull request awaits a person's merge, and `loop-claude` stops, naming those pull requests, once every item left awaits one.
- do-epic reads two new settings from a project's config: `jira-unblocking-statuses` names the statuses at which an issue unblocks the issues it blocks, and `jira-automation-moves-issues` leaves the move out of "In Progress" to the team's own automation.
- The prose standard asks that a sentence about several named things holds for each of them.
- `do-epic` resumes a chunk parked on `your merge` when its pull request no longer merges into its base, so the worker runs `chunk-pr merge` again to level the branch; a finished chunk in that state stays open until its pull request merges.
- `larv-review prepare-scoring` takes the scoring run's project values from the checkout's `skills/comprehension-panel/seat-prompts.md` where the working-rules file holds no "Scoring run" section, not only where that file is missing.
## 0.13.0
- Fix loop-claude stopping after a finished chunk: its judge may now quote the worker's task as evidence, so the loop starts the next chunks instead of exiting.
+54 -15
View File
@@ -30,7 +30,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instru
- Counter-signal: defects where a backend loses or misreads a plan item, a premise or a record rise.
- Why: fitting in isn't worth anything if the loop then works from wrong facts.
2. **Maintain:** Make my claude setup shareable between computers.
3. **Maintain:** Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
3. **Maintain:** Keep my claude setup and the transcripts of unattended runs backed up. A bench's transcripts are the exception: they stay only until `task-bench gather` has filed plan items from their digest, or the next bench starts.
4. **Maintain:** Don't leak anything: no credentials, transcripts or memory files to this repo's remote, and no client's code, transcripts or credentials to another client or to this repo.
## Audience
@@ -109,6 +109,8 @@ A project may also set `env-file`, the file of `KEY=value` credentials its tools
A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record.
A project may also set `bench-tasks`, a path spelt the same way, such as `bench-tasks = "checkout:testdata/bench-tasks"`: the folder of the features `task-bench --tasks features` has Haiku build, and of the data sources `--tasks data-sources` has it add. `task-bench --help` says what the folder holds, and where to keep it so the project's own tests don't run its acceptance tests.
A project whose team wrote its own coding conventions lists the files in `coding-conventions`, each spelt as `principles` is, such as `coding-conventions = ["checkout:CONVENTIONS.md"]`. Each reviewer agent larv-review launches reads them beside the principles and the standards, and the team's rule wins where they conflict.
A project may also set `notifier` to `"mattermost"` or `"slack"`, the service that sends loop-claude's DMs. The `env-file` then holds that service's keys. A project that sets none gets no DMs, whatever its env file holds. `project-config notifier` prints the setting.
@@ -119,7 +121,9 @@ A legacy project with no container setup sets `tooling-on-host = true`, so the l
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. While it waits, other chunks merge. It stops where a reviewer's comment waits for an answer, on an approved pull request too; answer it and run it again. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. Left out, the setting is `"chunk"`: the chunk merges.
A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once; where you close the pull request unmerged, file the item again. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. The chunk resumes and brings the branch level again once the pull request conflicts with the default branch. It does so too once the branch is behind a default branch whose protection, on GitHub, requires an up-to-date branch. loop-claude doesn't start a chunk for an item that a ready pull request finishes. Once no item left in the release can start and one awaits a merge, loop-claude stops and names the pull requests to merge; run it again after you merge one. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged pull request left, where nobody pushed to the pull request after the chunk did. Nobody works on a pull request that awaits your merge. To have a reviewer's comment answered, turn the pull request back into a draft: a chunk then takes its item up again. Left out, the setting is `"chunk"`: the chunk merges.
A project whose team wants an epic's work in one pull request sets `epic-branch`, a template with `{epic}` for the epic's key, such as `epic-branch = "{epic}"`. Under loop-claude the epic is the Jira epic the config's `plan` names, so a plan kept in a file gets no working branch. Under do-epic it is the epic do-epic drives. Each chunk then branches off the epic's working branch, here `ABC-123` for the epic ABC-123, and `chunk-pr` opens its pull request into that branch and merges it there without a person, also under `merge = "human"` and `wait-for-approval`: those two keep guarding the default branch. A pull request that was open into the default branch when you set `epic-branch` stays yours to settle: `chunk-pr ready` and `merge` fail on it, naming both branches, until you change its base on the forge to the working branch, or merge it yourself. `chunk-preflight`, and do-epic as a chunk starts, make the branch on origin off the default branch, or merge the default branch into it with a merge commit, which needs git 2.38 or later. Where that merge conflicts, they stop, and a person merges it. Once the epic's last issue has landed, do-epic's finishing chunk runs `chunk-pr open-epic <epic's key> <title>`, which brings the branch level once more and opens the pull request from it into the default branch. Under loop-claude, run it yourself. A person merges that pull request, and its checks and reviews are theirs to answer. An auto-reviewer that reviews only pull requests into the default branch is asked by a comment: set `review-request-comment` to the comment's text, such as `"@reviewbot review"`. `chunk-pr ready` then posts it on a pull request into the working branch, and `chunk-pr push` pushes later commits and posts it again.
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
@@ -134,7 +138,7 @@ A client that plans in Jira Cloud names an epic as its project's plan: `plan = "
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it.
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 each item into it as a Task under the epic. A Jira project that has no Task type, such as TW, sets `jira-finding-type` to a type it has, such as `"Feature"`. `todo-item add` fails, naming the project's types, where the project lacks the type set. `todo-item add` also 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 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.
@@ -155,10 +159,18 @@ The last line prints each setting's path once the config is complete.
`do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic:
- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason.
- `config.toml` may end with a `[label-repos]` table, for a team that already labels its issues by repo. Give it one line for each such label: the label, then the repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. Where the label is the repo's name, map the name to itself, as in `core-4 = "core-4"`. Write every other setting above the table.
- `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. `do-epic <EPIC-KEY>` uses it to pick where each open issue without such a label is worked, and records the pick as a label: `repo:<name>` for its repo, `do-epic-claude` for work of Claude's that changes no repo, and `do-epic-human` for a task of yours. Where the rule leaves an issue unclear, do-epic asks you on the terminal. Answer with the label, or with Enter alone to leave the issue waiting. Change a pick by editing the label in Jira.
- `config.toml` fits do-epic to a team whose own automation moves issues, such as a CI job that moves an issue when its pull request merges. Two settings do:
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks, and `--status` names the statuses beside each blocker. A status Jira counts as done always does both. The release reviews, which are the epic's last chunk, still wait until Jira counts every issue done: run `do-epic <EPIC-KEY>` then, to start them.
- `jira-automation-moves-issues = true` keeps do-epic from moving the issue of a finished chunk in a repo: the automation moves it, and do-epic waits for that move before it starts what the issue blocks. An issue without a repo has no pull request, so do-epic still moves it, with `jira-finish-transition`. The setting needs `jira-unblocking-statuses`, which names the status the automation gives an issue whose pull request merged.
- `config.toml` names the statuses do-epic itself gives an issue whose chunk merges into an epic's working branch, in a repo whose config sets `epic-branch`. A team's automation moves an issue only for a pull request into the default branch, so there do-epic makes both moves, whatever `jira-automation-moves-issues` says. `jira-pull-request-open-status`, such as `"Code Review"`, is the status of an issue whose chunk parks with its pull request open; a pull request that opens and merges within one run of the worker skips it, unless the workflow leads to the merged status only through it. `jira-pull-request-merged-status`, such as `"Release Ready"`, is the status once the pull request has merged into the working branch. `jira-unblocking-statuses` must list it, and an issue that has it counts as done when the release reviews and the finishing chunk fall due, since both come before a person merges the working branch. Without it, do-epic moves a finished chunk's issue to done. Where `jira-automation-moves-issues` is set, it stops instead and asks you to move the issue.
- `config.toml` names how do-epic moves a parent issue whose sub-tasks a person filed. Once every sub-task is done, the parent moves to done by `jira-finish-transition`; without that setting it stays. Before that, once each sub-task is done or in one of `jira-unblocking-statuses`, the parent moves by the transition `jira-sub-tasks-landed-transition` names, such as `"Release Ready"`; without that setting it stays. The transition must lead to one of `jira-unblocking-statuses`, or do-epic doesn't make it. do-epic makes these moves as each run plans and as each chunk finishes, and `--dry-run` prints them. A parent that is done, or already in one of `jira-unblocking-statuses`, never moves back. A move that is not made is said, and the run goes on.
- `config.toml` also says how a starting chunk's issue shows on its team's board. A starting chunk always assigns its issue to the account do-epic works as, unless someone else holds it; that issue keeps its assignee, and moves and joins the sprint like any other. `jira-start-transition` names the workflow transition that then moves the issue, such as `"In Progress"`; an issue whose work has started already keeps its status. `jira-sprint-board` is the ID of the board whose active sprint the issue joins, such as `6`. Where a setting is left out, do-epic doesn't take its step.
- `config.toml` may set `jira-finding-type`, the issue type do-epic files a finding as, and `jira-review-type`, the one it files a repo's release review as, such as `"Feature"` and `"Chore"`. Both are Task where left out. do-epic doesn't file anything where the Jira project lacks the type, and says which types it has.
- `config.toml` may set `sub-task-summary`, which shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `sub-task-summary = "{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Without it a summary is `[<repo>] <the issue's summary>`.
- `config.toml` may end with a `[label-repos]` table, for a team that already labels its issues by repo. Give it one line for each such label: the label, then the repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. Where the label is the repo's name, map the name to itself, as in `core-4 = "core-4"`. Where several lines name one repo, do-epic writes the label of the first. Write every other setting above the table.
- `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. `do-epic <EPIC-KEY>` uses it to pick where each open issue without such a label is worked, and records the pick as a label. For a repo that is the team's own label from `[label-repos]`, else `repo:<name>`; for work of Claude's that changes no repo, `do-epic-claude`; for a task of yours, `do-epic-human`. Where the rule leaves an issue unclear, do-epic asks you on the terminal. Answer with the label, or with Enter alone to leave the issue waiting. Change a pick by editing the label in Jira.
An epic's description states the formula that ranks the issues do-epic files in it: once under `## Scoring`, on a line of its own and inside backticks, such as `` `Score = 100 * V / (2**S + 32)` ``. Without that line do-epic says so and leaves the backlog's order as it is.
An epic's description states the formula that puts its issues in order: once under `## Scoring`, on a line of its own and inside backticks, such as `` `Score = 100 * V / (2**S + 32)` ``. do-epic starts the epic's issues by that score, highest first, with each blocker before what it blocks, whatever their order on the board. Where two or more issues may start, it scores each of them that holds no scores, a person's included, against the epic's goals and the goals of the issue's repo, and tells the team the scores in a comment on the issue. It doesn't score a task of yours, and it keeps the scores an issue already holds. On the board it re-ranks only the issues it filed, so a person's issue keeps the rank the team gave it. Without that line do-epic says so, doesn't score anything and starts the issues in the backlog's order.
Each repo an epic changes has a project config of its own, as in the rest of this section. `do-epic` fails and names each setting or file that is missing or invalid.
@@ -186,16 +198,24 @@ bin/deploy-release --cut
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first:
```sh
bin/deploy-release --cut-patch 794ce37..1aa2367
```
It applies only those commits on the newest tag, tests them with `ci.sh`, tags and pushes the release, then merges the tag back into `main` through a pull request and moves `~/.claude` to it. A patch skips the release review. Until it is cut, `chunk-preflight` calls the patch's release review due, and loop-claude would run it. `deploy-release --help` lists the steps.
## 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`. 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. Under `merge = "human"` it then marks the pull request ready and leaves the merge to a person. 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|push|merge|clean|open-epic` 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. Where the project's config sets `epic-branch`, the pull request goes into the epic's working branch instead, `push` pushes later commits and asks the auto-reviewer for a review, and `open-epic` opens the pull request from that branch into the default branch. 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. Under `merge = "human"` it then marks the pull request ready and leaves the merge to a person. 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.
- `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.
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. It plans no issue your team filed a sub-task under: those sub-tasks run instead, each under a label of its own, and your team closes the issue. Then it puts the scored issues that do-epic itself filed in order of score. An open issue runs once a label names its repo or marks it as Claude's, in Jira's backlog order, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
- `deploy-release [--cut | --cut-patch <commits>] [<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, and with `--cut-patch`, a patch release of only the commits named, as Release says.
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. It plans no issue your team filed a sub-task under: those sub-tasks run instead, each under a label of its own, and your team closes the issue. Then, where two or more issues may start, it scores each of them that holds no scores, and moves the issues that do-epic itself filed into order of score on the board. An open issue runs once a label names its repo or marks it as Claude's, in order of score, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. `do-epic <EPIC-KEY> --dry-run` prints what `do-epic <EPIC-KEY>` would write to Jira and which chunks it would start, and does neither; run it before the first real run on a team's epic. `--help` lists what it prints and leaves out. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
- `do-epic-e2e` runs `do-epic` against a sandbox epic on a real Jira site, as Test says.
- `judge-replay <model> [--offline]` replays loop-claude's judge on archived verdicts of the projects run on the model. It prints what each rung a review climbs to misses, and the lowest rung below those that returns every verdict, as each candidate above it does. With `--offline` it doesn't call a judge: it counts what a "?" rule, a decision table and a classifier trained on the archive decide of each verdict's kind from the worker's final message, and how many interrupts each misses. `judge-replay --help` states both replays.
- `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.
@@ -216,6 +236,7 @@ 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.
- `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.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, PHP, Python, Rust, TypeScript and JavaScript files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `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.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
@@ -227,16 +248,31 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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.
- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either.
- `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. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
- `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`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path.
- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included.
- `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 `release_plan`'s `release_standing`.
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `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, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`.
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` 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`).
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic:
- `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what stays the same through one run of do-epic, such as its config, its Jira store and its paths, and starts the chunks that may start now.
- `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`.
- `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks.
- `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `parking.py` parks such a chunk after a cycle and polls the gate until its worker has something to do.
- `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`.
- `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it.
- `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, language line and cap line, through `record_store`'s `EpicDescription`.
- `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`.
- `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue.
- `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several.
- `parent_moves.py` moves a parent whose sub-tasks a person filed, once those have landed or are done.
- `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`.
- `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic.
- `e2e/` holds `do-epic-e2e`.
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `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`, `do_epic`, 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`.
@@ -244,12 +280,13 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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.
- `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, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`.
- `repo_checks/` tests the repo itself.
- `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.
- `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 `agent_cycle`'s retry count and `chunk_driver`'s 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.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, 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.
@@ -264,6 +301,8 @@ CI runs `ci.sh` on every pull request, and `main` doesn't merge anything until i
To mutation-test the lines a branch changes, run `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"'` in its checkout.
To bench how hard the code is to fix a bug in, build the image first, with `~/.claude/bin/run-heavy docker build --quiet --memory 2g --memory-swap 2g -t claude-config-task-bench task-bench-image`. Then run `~/.claude/bin/task-bench --image claude-config-task-bench --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"' --test 'python -m pytest -q -p no:cacheprovider -n 4 bin --ignore=bin/adf_codec --ignore=bin/run_tests --ignore=bin/repo_checks/test_types.py --deselect bin/plan/test_touches.py::PredictedTest --deselect bin/loop_effects/test_effects.py::ChildShells'` in this checkout, under `~/.claude/bin/run-heavy`. A scoring run starts it with `--record-figures` added. The bench runs the tests with no network, so the image holds everything they need. The `--test` leaves out the tests that need docker or `uvx`, and `ChildShells`, which needs `docker run --init` to reap its processes: `bin/run-tests` on the host runs those.
## Tracking a new file
`.gitignore` is an allowlist. Track a file by negating it and its parent directories, then confirm with `git check-ignore -v <path>`:
+2
View File
@@ -45,6 +45,8 @@ Before anything else, **read the technical principles** in the folder your promp
6. **Assess reasonableness of usage paths**: Are there paths that exist but no real persona would use?
7. **Check each claim about output against its run.** A changed doc line that says what a command, flag or error prints is true only if the real output says so. Where your prompt has a `Claimed output:` line, that file holds each such claim's command and real output. Report a claim the output doesn't bear out, such as an error said to name the fix that doesn't, and name the missing words. Never settle one by reading code. A claim marked `not run`, or one you find that the prompt doesn't hand you a run of, is a ❓ naming the command that would run it.
## Your Output Format
Report only a defect a persona hits; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle, or of a coding convention, which counts as one. Friction that is none of these is not a finding.
+4
View File
@@ -28,6 +28,10 @@ Run them in this order. A fix for a later check never breaks an earlier one.
Also report a list whose order carries no meaning and is not sorted (the technical principles' "Deterministic order", in the folder your prompt's `Technical principles:` line names; without one, open your report by saying so), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
Where your prompt hands you claims a fix rewrote, judge each claim afresh, not only the finding it answered. Look for a counter-example: one input or case where it is false. Then check it against every term of the source it names, such as each credit and notice a licence file lists. Report a claim you can't check as a ❓ naming what would check it.
Where your prompt has a `Claimed output:` line, that file holds the command and real output of each changed line that says what a command prints. Report a claim its output doesn't bear out, and name the missing words. A claim marked `not run` is a ❓ naming the command that would run it.
## Growth
Report the lines each file gained and lost. A line an earlier pass's fix added that names no reader need is a finding.
+2
View File
@@ -72,6 +72,8 @@ Catch behavior that is unclear or under-specified — "building in ambiguousness
- Are there potential off-by-one errors?
- Zero and absent are different values: `empty('0')`, `if ($amount)`, `$x ?: $default`, JS `||` conflate them one way; null coerced to `'0'` conflates them the other (a past prod bug: phantom 0-amount reversals). Both directions are findings.
- Multibyte text (åäö): truncation, length checks, and comparisons must be mb-safe; encoding consistent end-to-end.
- Where the change splits text on a separator or strips a suffix, look in the fixtures and a sample of the source data for a value where the separator or suffix also occurs as data, such as an address split on `,` whose last part holds a comma. Report a row the parse then misplaces or drops, silently or with only a log line.
- Where the change builds a lookup key by joining path segments, look for two inputs that join to one key, such as a column named like its own table. Where it matches a key by prefix, look for a key that two prefixes match, such as `ns` and `ns.sub`. Report the input the lookup resolves to the wrong entry.
- Are payload and collection sizes bounded at the boundary?
### 6. Concurrency & State Management
+22 -12
View File
@@ -20,6 +20,8 @@ from claude_code.tokens import tokens_of
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
JUDGE_PROMPT_CHARS = 400000
# The judge reads the transcript's last 50,000 characters at least, about 15,000 tokens, or all of a shorter one. Where the rest of its prompt leaves less room, the judge doesn't run, since a cut record could hide the rule that makes it interrupt.
TRANSCRIPT_FLOOR = 50000
INTERRUPT_RULES = (
"""Decide whether the human must now be interrupted. ~/.claude/CLAUDE.md → "Working loop", "Ask, don't guess" says """
"which choices are reserved for the human. interrupt=true when any of these appear:\n"
@@ -74,6 +76,8 @@ def judge_rules(answer_destinations: str, driver: str) -> str:
# 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"
# Between the task and the tail that quotes_checked searches, so that no fragment of a quote runs across the join. plain() keeps it, and the judge's quotes hold no NUL.
PASSAGE_BREAK = "\x00"
def transcript_heading(driver: str) -> str:
@@ -85,7 +89,7 @@ class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of the premises or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: agent_cycle/escalation_mark.py.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends {asks_higher_rung}, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. {quote_after_step} Never a later mention of the trigger, and never the request itself."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one passage of the task or the transcript the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
answered_before: str = dataclasses.field(metadata={"description": "With interrupt true, a [human] line from earlier in the chunk that answered the question the worker asks now, quoted verbatim, without elisions. Empty otherwise."})
@@ -184,7 +188,10 @@ def judge(root: str, brief: Brief, rung: Rung, effects: Effects, keep: typing.Ca
def judge_once(root: str, brief: Brief, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on the brief, as judge retries it; judge-replay replays it."""
prompt, grounds = judge_prompt(brief)
built = judge_prompt(brief)
if isinstance(built, Failure):
return built
prompt, grounds = built
verdict = run_judge(root, judge_args(rung, brief.driver), prompt, grounds, effects)
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(brief.entries))
@@ -201,7 +208,7 @@ def judge_args(rung: Rung, driver: str) -> list[str]:
return [
"--json-schema", json.dumps(judge_schema(driver)),
*rung.flags(),
"--tools", "",
"--tools", "", "--strict-mcp-config",
]
@@ -248,20 +255,20 @@ def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
Only a misquoted evidence fails. A Failure for any other would exit an unattended loop, so each changes the verdict instead.
"""
if not grounded(verdict.evidence, f"{grounds.task}\n\n{grounds.shown}"):
if not grounded(verdict.evidence, f"{grounds.task}{PASSAGE_BREAK}{grounds.shown}"):
return misquoted_evidence(verdict)
verdict = re_ask_checked(verdict, grounds.shown)
verdict = answer_checked(verdict, grounds.quotable)
return escalation_mark.checked(verdict, after=grounds.after_mark, shown=grounds.shown)
def grounded(evidence: str, rendered_transcript: str) -> bool:
"""Whether the transcript holds the evidence word for word, once emphasis marks are stripped and whitespace is reflowed in both. The judge joins passages with an ellipsis though told to quote one, so each fragment between ellipses must come after the one before it."""
transcript = plain(rendered_transcript)
def grounded(evidence: str, searched: str) -> bool:
"""Whether the searched text holds the evidence word for word, once emphasis marks are stripped and whitespace is reflowed in both. The judge joins passages with an ellipsis though told to quote one, so each fragment between ellipses must come after the one before it."""
searched = plain(searched)
fragments = [fragment.strip() for fragment in re.split(r"\.\.\.|…", plain(evidence)) if fragment.strip()]
after = 0
for fragment in fragments:
at = transcript.find(fragment, after)
at = searched.find(fragment, after)
if at < 0:
return False
after = at + len(fragment)
@@ -271,7 +278,7 @@ def grounded(evidence: str, rendered_transcript: str) -> bool:
def misquoted_evidence(verdict: Verdict) -> Failure:
asked = f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript{asked}")
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the task or the transcript{asked}")
def re_ask_checked(verdict: Verdict, shown: str) -> Verdict:
@@ -290,8 +297,8 @@ def answer_checked(verdict: Verdict, quotable: str) -> Verdict:
return verdict
def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
"""The prompt, and what the judge's quotes are checked against."""
def judge_prompt(brief: Brief) -> tuple[str, Grounds] | Failure:
"""The prompt, and what the judge's quotes are checked against; a Failure where the premises, the records, the task and the rules leave room for less than the transcript's last TRANSCRIPT_FLOOR characters, or all of a shorter transcript."""
head = (
f"From the goals file, {brief.premises}\n\n"
f"The records: {brief.records_named}:\n{brief.records or 'none'}\n\n"
@@ -299,8 +306,11 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
f"{transcript_heading(brief.driver)}"
)
rules = judge_rules(brief.answer_destinations, brief.driver)
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(rules) - 2)
room = JUDGE_PROMPT_CHARS - len(head) - len(rules) - 2
transcript = escalation_mark.transcript(brief.entries, brief.escalated_at, typed_answer, brief.driver)
needed = min(len(transcript), TRANSCRIPT_FLOOR)
if room < needed:
return Failure(f"the premises, the records, the task and the judge's rules leave {max(0, room):,} of the judge's {JUDGE_PROMPT_CHARS:,} characters for the transcript, less than the last {needed:,} characters of it that the judge must read. Cut the records, which take {len(brief.records):,}, by at least {needed - room:,}.")
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
shown = transcript[max(0, len(transcript) - room):]
grounds = Grounds(
+15 -5
View File
@@ -7,7 +7,7 @@ from transcript_archive.write import archive
from agent_cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
from claude_code.output_limits import BASH_CEILING, BASH_CEILING_CHARACTERS
from agent_cycle.judge import Brief, judge, Rejected
from claude_code.session import delete_session, Session, session_open, transcript_file
from claude_code.session import delete_session, discard_empty_transcript, Session, session_open, transcript_file
from loop_effects.effects import Effects, say
from claude_code.entries import Entry
from failure import Failure
@@ -15,6 +15,7 @@ from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Take
from agent_cycle.interrupt import interrupt, Talked, WorkerSession
from transcript_archive.judge_run import JudgeRun
from transcript_archive.read import last_spent
from claude_code.reply import Limited
from agent_cycle.routing import next_route, step_up, StepUp
from transcript_archive import outcomes
from model_routing.ladder import ProjectRung, Rung
@@ -100,7 +101,7 @@ def archived_stop(project_archive: pathlib.Path, session: Session, task: str, ro
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 chunk_driver.chunk_run.closed_cycle, which has no Cycle, both archive through it."""
return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run, replace=effects.replace_file)
@@ -121,8 +122,7 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> WorkerRan | Stop:
if isinstance(answered, QuotedAnswer):
say(f"\n=== {cycle.prompts.quote_sources} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True)
# worker_start runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.project_archive, cycle.project.rung if cycle.project else cycle.route.rung, cycle.effects), cycle.effects):
if stop := retried("worker", lambda: started_worker(cycle, answered, stepped), cycle.effects):
return stop
path = transcript_file(cycle.session)
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
@@ -137,13 +137,23 @@ def worker_session(cycle: Cycle, transcript_path: str, stepped_from: Rung | None
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, stepped_from or cycle.route.rung, transcript_path, worker_environment(cycle))
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
def started_worker(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> Failure | Limited | None:
"""One run of the worker. worker_start runs on each attempt: a failed one may have opened the session, or left it empty."""
args = worker_start(cycle, answered, stepped)
if isinstance(args, Failure):
return args
return run_worker(cycle.root, args, worker_environment(cycle), cycle.project_archive, cycle.project.rung if cycle.project else cycle.route.rung, cycle.effects)
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str] | Failure:
if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, cycle.prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, cycle.prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, cycle.prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
if failure := discard_empty_transcript(cycle.session):
return failure
return worker_args(cycle.session, cycle.route.rung, cycle.prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
+1 -1
View File
@@ -104,7 +104,7 @@ def command_of(pid: int, shells: list[Shell]) -> str:
def investigated(shells: list[Shell], rung: Rung, root: str, effects: Effects) -> dict[str, typing.Any] | Failure:
"""A headless claude's verdict on the worker holding shells, as SCHEMA has it, or why there is none. It runs without tools, so it judges only the evidence it is handed."""
evidence = "\n\n".join(f"Shell {shell.pid}: {shell.command}\nIts processes, as pid, state, CPU and command line:\n{chr(10).join(shell.processes) or 'none'}\nThe end of its output:\n{shell.output or 'none'}" for shell in shells)
reply = claude_reply(effects.claude, ["--json-schema", json.dumps(SCHEMA), *rung.flags(), "--tools", ""], root, PROMPT + "\n" + evidence, "the stuck check")
reply = claude_reply(effects.claude, ["--json-schema", json.dumps(SCHEMA), *rung.flags(), "--tools", "", "--strict-mcp-config"], root, PROMPT + "\n" + evidence, "the stuck check")
if isinstance(reply, Limited):
return Failure(f"claude hit a limit: {reply.said}")
if isinstance(reply, Failure):
+44 -3
View File
@@ -124,19 +124,25 @@ class Verdict(unittest.TestCase):
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 1, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
def test_takes_the_task_as_evidence_where_the_tail_it_shows_cuts_off_the_workers_first_prompt(self):
def test_takes_the_task_as_evidence_where_the_tail_it_shows_cuts_off_the_workers_first_prompt_but_no_quote_across_the_join(self):
entries = [human("Do the next chunk. " + "x" * judge.JUDGE_PROMPT_CHARS), assistant({"type": "text", "text": "Merged."})]
def judged_on(evidence):
return judge.judge_once("/r", judge.Brief("Do the next chunk.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 0, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence=evidence)] * 3).effects())
self.assertEqual(judged_on("Do the next chunk."), Unfinished("Do the next chunk.", entries_read=2))
self.assertEqual(judged_on("Do the next chunk. ... Merged."), Unfinished("Do the next chunk. ... Merged.", entries_read=2))
self.assertIsInstance(judged_on("Do the next release."), Failure)
self.assertIsInstance(judged_on("next chunk. xxx"), Failure)
class JudgePrompt(unittest.TestCase):
def brief(self, entries, escalated_at, answer_destinations="the plan or a comment"):
def brief(self, entries, escalated_at, answer_destinations="the plan or a comment", records=""):
"""What the judge of a-driver reads of a transcript holding entries."""
return judge.Brief("Do it.", "## Goals", "", "the project's decisions", answer_destinations, kinds(*entries), escalated_at, "a-driver")
return judge.Brief("Do it.", "## Goals", records, "the project's decisions", answer_destinations, kinds(*entries), escalated_at, "a-driver")
def test_runs_with_no_tools_and_loads_no_mcp_server(self):
args = judge.judge_args(Rung("claude-opus-5-5", "medium"), "a-driver")
self.assertEqual(args[args.index("--tools") + 1 :], ["", "--strict-mcp-config"])
self.assertNotIn("--mcp-config", args)
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
@@ -148,6 +154,41 @@ class JudgePrompt(unittest.TestCase):
self.assertEqual(grounds.after_mark, "old " + "x" * judge.JUDGE_PROMPT_CHARS + "\n\nnew")
self.assertEqual(grounds.quotable, "## Goals\n\n")
# A transcript longer than the floor: an old message, then the last one.
LONG = [assistant({"type": "text", "text": "old " + "x" * judge.TRANSCRIPT_FLOOR}), assistant({"type": "text", "text": "Merged."})]
def overhead(self):
"""The characters of the judge's prompt that are neither the records nor the transcript."""
prompt, grounds = judge.judge_prompt(self.brief(self.LONG, 0, records="r"))
return len(prompt) - len(grounds.shown) - 1
def test_fails_naming_the_shortfall_where_the_records_leave_less_than_the_transcripts_floor(self):
failed = judge.judge_prompt(self.brief(self.LONG, 0, records="r" * (judge.JUDGE_PROMPT_CHARS + 1)))
self.assertIsInstance(failed, Failure)
for fact in ("leave 0 of the judge's 400,000", "400,001", f"{judge.TRANSCRIPT_FLOOR:,}", f"by at least {judge.TRANSCRIPT_FLOOR + self.overhead() + 1:,}"):
with self.subTest(fact=fact):
self.assertIn(fact, failed.reason)
def test_judge_once_returns_that_failure_without_starting_claude(self):
failed = judge.judge_once("/r", self.brief(self.LONG, 0, records="r" * judge.JUDGE_PROMPT_CHARS), Rung("judge-model"), FakeEffects(claude=[]).effects())
self.assertIsInstance(failed, Failure)
self.assertIn(f"{judge.TRANSCRIPT_FLOOR:,}", failed.reason)
def test_shows_the_whole_of_a_transcript_longer_than_the_floor_where_the_records_leave_room_for_it(self):
whole = "old " + "x" * judge.TRANSCRIPT_FLOOR + "\n\nMerged."
prompt, grounds = judge.judge_prompt(self.brief(self.LONG, 0, records="r" * (judge.JUDGE_PROMPT_CHARS - self.overhead() - len(whole))))
self.assertEqual(grounds.shown, whole)
self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS)
def test_shows_the_floor_where_the_records_leave_exactly_that(self):
at_floor = judge.JUDGE_PROMPT_CHARS - self.overhead() - judge.TRANSCRIPT_FLOOR
self.assertEqual(len(judge.judge_prompt(self.brief(self.LONG, 0, records="r" * at_floor))[1].shown), judge.TRANSCRIPT_FLOOR)
self.assertIsInstance(judge.judge_prompt(self.brief(self.LONG, 0, records="r" * (at_floor + 1))), Failure)
def test_shows_a_transcript_shorter_than_the_floor_whole(self):
_, grounds = judge.judge_prompt(self.brief([assistant({"type": "text", "text": "Merged."})], 0, records="r" * (judge.JUDGE_PROMPT_CHARS - 10000)))
self.assertEqual(grounds.shown, "Merged.")
def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self):
prompt, _ = judge.judge_prompt(self.brief([assistant({"type": "text", "text": "done"})], 1))
self.assertNotRegex(prompt + json.dumps(judge.judge_schema("a-driver")), r"\b[Aa]gent")
+38 -1
View File
@@ -172,6 +172,43 @@ Worker: {OFF_LADDER}
self.assertEqual(workers[1][workers[1].index("-p") + 1], "Resumed: working")
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
def test_a_session_whose_transcript_is_empty_starts_fresh_with_its_session_id(self):
path = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl"
path.parent.mkdir(parents=True)
path.touch()
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
worker, = fake.made("stream_claude")
self.assertIn("--session-id", worker)
self.assertNotIn("--resume", worker)
def test_a_worker_that_fails_leaving_an_empty_transcript_is_retried_with_a_fresh_session(self):
path = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl"
def fails_leaving_it_empty(args):
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
return Streamed(1)
fake = FakeEffects(streams=[fails_leaving_it_empty, Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
self.assertIn("retrying the worker in a minute", said.getvalue())
self.assertEqual(["--session-id" in worker and "--resume" not in worker for worker in fake.made("stream_claude")], [True, True])
def test_a_worker_stops_where_it_cannot_remove_the_empty_transcript_of_its_session(self):
assert_not_root(self)
path = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl"
path.parent.mkdir(parents=True)
path.touch()
path.parent.chmod(0o500)
self.addCleanup(path.parent.chmod, 0o700)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)])
with contextlib.redirect_stderr(io.StringIO()):
stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop, Stop(1, f"the worker failed three times running: could not remove the empty transcript {path}: Permission denied; claude refuses to start the session while that file stands"))
self.assertEqual(fake.made("stream_claude"), [])
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1)
@@ -188,7 +225,7 @@ Worker: {OFF_LADDER}
self.assertEqual(self.archived_outcomes(), [
"Task: Do it.\n\n"
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.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} Judge reply rejected: the judge quoted 'never said', which is not in the task or 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"])
def test_archives_each_judge_runs_prompt_and_reply_beside_the_rejection_interrupt_and_verdict_it_gave(self):
+7 -2
View File
@@ -36,7 +36,11 @@ class StuckWorkers(unittest.TestCase):
if each_check:
streamed.shells = lambda: [each_check.pop(0)]
fake = FakeEffects(streams=[streamed], claude=replies)
effects = dataclasses.replace(fake.effects(), now=lambda: clock[0])
self.claude_folders = []
def claude(args, cwd, stdin):
self.claude_folders.append(cwd)
return fake.effects().claude(args, cwd, stdin)
effects = dataclasses.replace(fake.effects(), now=lambda: clock[0], claude=claude)
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said, contextlib.redirect_stderr(io.StringIO()) as failed:
archive = archive or pathlib.Path(folder, "transcripts", "project")
worker.run_worker("/r", [], {}, archive, RUNG, effects)
@@ -47,7 +51,8 @@ class StuckWorkers(unittest.TestCase):
streamed, fake, said, _, record = self.worker_with(ASSISTANT, None, None, None, held=[shell()], replies=[verdict()])
[(args, prompt)] = fake.made("claude")
self.assertEqual(args[args.index("--model") + 1 :][:3], ["claude-opus-5-5", "--effort", "medium"])
self.assertEqual(args[args.index("--tools") + 1], "")
self.assertEqual(args[args.index("--tools") + 1 :][:2], ["", "--strict-mcp-config"])
self.assertEqual(self.claude_folders, ["/r"])
self.assertEqual(json.loads(args[args.index("--json-schema") + 1])["properties"]["verdict"]["enum"], ["working", "waiting on a person", "stuck"])
self.assertTrue(prompt.endswith("\n\nShell 7: bin/run-tests\nIts processes, as pid, state, CPU and command line:\n8 S 2.0 s python3 -m pytest\n9 S 0.0 s sh -c trap '' INT; sleep 999\nThe end of its output:\ncollected 40 items"))
line = "stuck check: a headless claude judged the worker stuck, naming process 8 (python3 -m pytest): pytest waits on a shell that ignores SIGINT" + sign(1600, 1600)
+1 -1
View File
@@ -38,7 +38,7 @@ class Interrupt:
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
entries_read: int | None = None
judged: Judged = Judged()
# The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them.
# The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. agent_cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them.
answered_before: str = ""
left_open: str = ""
+50 -4
View File
@@ -6,6 +6,7 @@ import typing
from failure import Failure
from project_config.settings import Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from atlassian.client import Http
from text_files.markdown_text import listed
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
PAGE = 100
@@ -13,6 +14,8 @@ PAGE = 100
MAX_PAGES = 100
# The key of the status category Jira Cloud gives every done status.
DONE = "done"
# The hierarchyLevel of the epic issue type in the issue types Jira lists.
EPIC_LEVEL = 1
# How a Failure names an answer in which a field is missing or of another type.
SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents"
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
@@ -73,6 +76,15 @@ def offer_of(raw: object) -> tuple[str, str, str, str] | None:
return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None
def offers_of(offered: object, key: str) -> list[tuple[str, str, str, str]] | Failure:
"""The transitions Jira offers the issue named key from its present status, each as offer_of answers one. A Failure where offered, Jira's answer, is in another shape."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
return found
def status_category(issue: object) -> str | Failure:
"""The key of the category of the status in Jira's answer about one issue, or how the answer is not in the shape Jira documents."""
fields = issue.get("fields") if isinstance(issue, dict) else None
@@ -98,10 +110,9 @@ def move_refusal(site: str, key: str, transition: str, finish: Finish, authoriza
def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
found = offers_of(offered, key)
if isinstance(found, Failure):
return found
named = [each for each in found if each[1] == finish.transition]
if not named:
others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found)
@@ -115,11 +126,46 @@ def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
return id_
def issue_types_of(site: str, project: str, authorization: str, http: Http) -> list[dict[str, typing.Any]] | Failure:
"""The issue types Jira lists for the project, each with a name, or why it listed none."""
answered = http("GET", f"{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) or not all(isinstance(each, dict) and isinstance(each.get("name"), str) for each in types):
return Failure(f"Jira answered {project}'s issue types in a shape its REST API version 3 doesn't document")
return types
def issue_type_refusal(site: str, project: str, kind: str, setting: str, authorization: str, http: Http) -> str | None:
"""Why the project can't file a new issue under an epic as the type named kind, which the setting `setting` names; None where it can."""
types = issue_types_of(site, project, authorization, http)
if isinstance(types, Failure):
return types.reason
# An issue under an epic is a standard one: Jira refuses a sub-task there, and an epic under an epic.
names: list[str] = [each["name"] for each in types if each.get("subtask") is not True and each.get("hierarchyLevel") != EPIC_LEVEL]
if kind in names:
return None
return f"{project} has no issue type {kind!r} for an issue under an epic; " + (f"it has {listed(names, 'and')}: name one in `{setting}`" if names else "it has no other type for one")
def project_of(key: str) -> str:
"""The key of the Jira project an issue key lies in."""
return key.rpartition("-")[0]
def edit_issue(site: str, key: str, body: dict[str, typing.Any], authorization: str, http: Http) -> None | Failure:
"""Sends body, an edit of the issue named key, and returns None, or the Failure of the request that failed. An edit that holds fields or update goes in one request, with its properties. Jira refuses an edit that holds neither, so such an edit sets each property through the property's own endpoint, one request each, and stops at the first that fails."""
if "fields" in body or "update" in body:
answer = http("PUT", f"{site}/rest/api/3/issue/{key}", authorization, body)
return answer if isinstance(answer, Failure) else None
for entry in body.get("properties", []):
answer = http("PUT", f"{site}/rest/api/3/issue/{key}/properties/{entry['key']}", authorization, entry["value"])
if isinstance(answer, Failure):
return answer
return None
def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> 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."""
answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
+77
View File
@@ -70,5 +70,82 @@ class TheCategoryOfAnIssuesStatus(unittest.TestCase):
self.assertEqual(jira.status_category(wrong), Failure("its status category has no key that is text"))
class TheRefusalOfAnIssueType(unittest.TestCase):
TYPES = {"issueTypes": [{"name": "Feature", "subtask": False, "hierarchyLevel": 0}, {"name": "Bug", "subtask": False, "hierarchyLevel": 0}, {"name": "Epic", "subtask": False, "hierarchyLevel": 1}, {"name": "Subtask", "subtask": True, "hierarchyLevel": -1}]}
def refusal(self, kind: str, answer: object) -> str | None:
asked: list[tuple[str, str, object]] = []
def http(method: str, url: str, authorization: str, body: object) -> object:
asked.append((method, url, body))
return answer
refused = jira.issue_type_refusal("https://acme.atlassian.net", "ABC", kind, "jira-finding-type", "Basic x", http)
self.assertEqual(asked, [("GET", "https://acme.atlassian.net/rest/api/3/issue/createmeta/ABC/issuetypes", None)])
return refused
def test_is_none_where_the_project_has_the_type(self):
self.assertIsNone(self.refusal("Bug", self.TYPES))
def test_names_the_types_the_project_has_and_the_setting_where_it_lacks_the_type(self):
self.assertEqual(self.refusal("Task", self.TYPES), "ABC has no issue type 'Task' for an issue under an epic; it has Feature and Bug: name one in `jira-finding-type`")
def test_a_sub_task_type_and_the_epic_type_are_not_ones_for_an_issue_under_an_epic(self):
for kind in ("Subtask", "Epic"):
with self.subTest(kind=kind):
self.assertEqual(self.refusal(kind, self.TYPES), f"ABC has no issue type {kind!r} for an issue under an epic; it has Feature and Bug: name one in `jira-finding-type`")
def test_says_the_project_has_no_other_type_where_it_has_only_sub_task_types(self):
self.assertEqual(self.refusal("Bug", {"issueTypes": [{"name": "Subtask", "subtask": True}]}), "ABC has no issue type 'Bug' for an issue under an epic; it has no other type for one")
def test_says_why_where_jira_fails(self):
self.assertEqual(self.refusal("Bug", Failure("Jira answered 403")), "cannot read ABC's issue types: Jira answered 403")
def test_says_so_where_jira_answers_in_another_shape(self):
for wrong in ([], {}, {"issueTypes": "Bug"}, {"issueTypes": [{"subtask": False}]}):
with self.subTest(wrong=wrong):
self.assertEqual(self.refusal("Bug", wrong), "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document")
class AnIssueEdit(unittest.TestCase):
def setUp(self) -> None:
self.calls: list[tuple[str, str, object]] = []
self.answer: object = None
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, body))
return self.answer
def edit(self, body: dict[str, object]) -> None | Failure:
return jira.edit_issue("https://acme.atlassian.net", "ABC-1", body, "Basic x", self.http)
def test_sends_fields_update_and_properties_in_one_request(self):
body = {"fields": {"summary": "Count."}, "update": {"labels": [{"add": "security"}]}, "properties": [{"key": "plan", "value": {"L": 2}}]}
self.assertIsNone(self.edit(body))
self.assertEqual(self.calls, [("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1", body)])
def test_sets_each_property_of_an_edit_without_fields_or_update_through_the_property_endpoint(self):
# Jira's edit refuses such a body: "one of 'fields' or 'update' required".
self.assertIsNone(self.edit({"properties": [{"key": "plan", "value": {"L": 2}}, {"key": "seen", "value": True}]}))
self.assertEqual(self.calls, [
("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/plan", {"L": 2}),
("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/seen", True),
])
def test_an_answer_jira_sends_on_success_counts_as_success(self):
self.answer = {"id": "10001"}
self.assertIsNone(self.edit({"fields": {"summary": "Count."}}))
def test_an_empty_edit_doesnt_send_a_request(self):
self.assertIsNone(self.edit({}))
self.assertEqual(self.calls, [])
def test_a_request_jira_refuses_is_its_failure_and_stops_the_later_properties(self):
self.answer = Failure("Jira answered 503")
self.assertEqual(self.edit({"fields": {"summary": "Count."}}), Failure("Jira answered 503"))
self.assertEqual(self.edit({"properties": [{"key": "plan", "value": {}}, {"key": "seen", "value": True}]}), Failure("Jira answered 503"))
self.assertEqual(len(self.calls), 2)
if __name__ == "__main__":
unittest.main()
+13 -6
View File
@@ -1,9 +1,10 @@
import pathlib
from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes
from branch_chunks.cut import BranchChunk, cut_branch, LOG, NOT_WORK, plan_revisions, shipped_by
from branch_chunks.cut import Branch, BranchChunk, cut_branch, LOG, NOT_WORK, plan_revisions, shipped_by
from failure import Failure
from git_cli.git_repo import git, Git, text_at
from plan.todo_table import Item
from project_config.main import located
from project_config.settings import ProjectConfig
from record_store.stores import store
@@ -37,6 +38,16 @@ def branch_chunks(default: str, run: Git, titles: templates.Titles) -> list[Bran
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
titles holds the project's title templates, which each commit's title is read through. run must run git in the checkout's top: the diff names each path from the top, while blame and a pathspec read a path from the current directory."""
cut = cut_with_shipped(default, run, titles)
if isinstance(cut, Failure):
return cut
branch, shipped = cut
traced = traces(fixing_changes(branch, shipped), run)
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
def cut_with_shipped(default: str, run: Git, titles: templates.Titles) -> tuple[Branch, list[tuple[Item, ...]]] | Failure:
"""The first-parent line of default, a branch or a commit, cut into chunks, and the todo.md items each chunk shipped, in the order of the branch's chunks, newest first. run and titles are branch_chunks' own."""
# The -- keeps a file named like the branch from making it ambiguous.
log = run(*LOG, default, "--")
if isinstance(log, Failure):
@@ -45,11 +56,7 @@ def branch_chunks(default: str, run: Git, titles: templates.Titles) -> list[Bran
if isinstance(branch, Failure):
return branch
plans = plans_at(plan_revisions(branch), run)
if isinstance(plans, Failure):
return plans
shipped = shipped_by(branch, plans)
traced = traces(fixing_changes(branch, shipped), run)
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
return plans if isinstance(plans, Failure) else (branch, shipped_by(branch, plans))
def plans_at(revisions: list[str], run: Git) -> dict[str, str] | Failure:
+5 -4
View File
@@ -22,7 +22,7 @@ CONSEQUENCE = "the judge cannot read the records"
def read_records(root: str | None, home: pathlib.Path, claude_dir: pathlib.Path, first: tuple[tuple[str, str], ...] = ()) -> str | Failure:
"""The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
"""The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name. One that does not exist, or is empty, is left out. A text that several of them hold appears once, headed by all their names.
`AGENTS.md` is read where the config under home of root's project puts it, and the decision log from the store that config names. Each is headed by its name in RECORD_FILES wherever it is kept.
@@ -37,13 +37,14 @@ def read_records(root: str | None, home: pathlib.Path, claude_dir: pathlib.Path,
decisions = store(config, DECISIONS[1]).read()
texts += [(WORKING_RULES[0], file_text(config.paths[WORKING_RULES[1]])), (DECISIONS[0], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules]
records = []
# Each text, with the names of the records that hold it: a config may keep the working rules in the decision log.
records: dict[str, list[str]] = {}
for heading, text in texts:
if isinstance(text, Failure):
return text
if text.strip():
records.append(f"From {heading}:\n{text.strip()}")
return "\n\n".join(records)
records.setdefault(text.strip(), []).append(heading)
return "\n\n".join(f"From {' and '.join(headings)}:\n{text}" for text, headings in records.items())
def file_text(path: pathlib.Path) -> str | Failure:
+4
View File
@@ -40,6 +40,10 @@ class Records(unittest.TestCase):
pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n")
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full")
config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"checkout:docs/decisions.md"'))
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From AGENTS.md and docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global"), "a file the config names for two records appears once")
config.write_text(config.read_text().replace('"checkout:docs/decisions.md"', '"checkout:AGENTS.md"', 1))
config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"'))
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'")
pathlib.Path(config.parent, "log").mkdir()
+159 -18
View File
@@ -3,12 +3,28 @@
usage: chunk-pr open <title> [<body>]
chunk-pr sync
chunk-pr ready [<title>]
chunk-pr push
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
chunk-pr clean
chunk-pr open-epic <epic's key> <title> [<body>]
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
pull request only while its head is the commit checked out, so push before you run them.
Where the project's config sets `epic-branch` (`project-config --help`), a chunk's pull request
goes into its epic's working branch, which chunk-preflight or do-epic recorded for the chunk's
branch as it started or continued the chunk. There, each step below reads "origin's default
branch" as that branch, with these differences:
- merge merges the pull request itself, whatever `merge` and `wait-for-approval` say: those
govern the pull request into the default branch, which open-epic opens;
- ready and push ask for a review, where the config sets `review-request-comment`, by making
that comment on the pull request;
- clean still fast-forwards the main checkout to origin's default branch.
ready and merge fail, naming both branches, where the forge merges the pull request into another
branch than the one recorded, or than the default branch where the checkout records none. A person
then settles which holds: they change the pull request's base on the forge, or the record, which
is `branch.<branch>.chunk-base` in git's config.
open pushes the branch, setting its upstream, and opens a draft pull request into origin's
default branch. <title> is one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs"
says, and <body> is the pull request's summary. On a branch that fits the config's `branch`
@@ -25,6 +41,9 @@ ready marks the pull request ready for review. On Gitea a draft is a pull req
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, which it holds
to the template as open does, it sets that
as the pull request's title first; where that fails, the pull request stays a draft.
push pushes the branch, setting its upstream. Where its pull request is open and goes into an
epic's working branch, it then asks for a review as ready does. Use it for each push
after ready there, and wait for that review as for any other.
merge merges the pull request in its turn: the chunks of one project on this machine take
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;
@@ -78,6 +97,14 @@ clean acts once the forge reports the branch's pull request merged at the com
doesn't touch anything. Where the main checkout has uncommitted or untracked files, another
branch checked out, or commits origin's default branch lacks, it leaves that as it was,
still removes the worktree and the branch, and fails saying why.
open-epic runs in any checkout of the repository, once the epic's last chunk has merged. It
fetches origin and brings the working branch of the epic named level with origin's
default branch, by a merge commit pushed to origin. Then it opens the pull request from
that branch into the default branch, ready and titled <title>, and leaves it to a person
to merge. Where the two don't merge cleanly it doesn't open anything and says how a
person merges them. Where the pull request is open already, it doesn't open a second
one. It fails where the config sets no `epic-branch`, or origin has no such branch, as
once its pull request has merged and the forge deleted it.
It prints what it did, exit 0, or why it failed, exit 1.
"""
@@ -93,9 +120,12 @@ import time
import typing
from chunk_pr.approval import approval, approved, awaited, left_to_a_person, left_to_park, PARKS, unanswered
from forge.pulls import checks_passed, merged_pull, open_pull, required_checks
from forge.pulls import checks_passed, merged_pull, open_pull, other_base, required_checks
from git_cli.git_repo import CHUNK_BASE, Git
from git_cli import epic_branch
from failure import Failure
from forge.commands import Forge, forge_of, gitea, Run, runner
from atlassian.jira import ISSUE_KEY
from project_config.main import located
from project_config.settings import ProjectConfig
from plan_store.plans import says_no_item
@@ -113,7 +143,7 @@ QUEUE_POLL_SECONDS = 10
RULING = "^Ruling: "
# The project's config, loaded once per step, on the first call that needs it.
Config = typing.Callable[[], ProjectConfig | Failure]
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr push | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean | chunk-pr open-epic <epic's key> <title> [<body>]"
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
@@ -142,7 +172,12 @@ def step(argv: list[str], run: Run, config: Config, parks: bool = False) -> str
case ["sync"]:
return synced(run, config)
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None)
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or readied(run, title[0] if title else None, config)
# Three readers, seated as those who run `chunk-pr`, picked the spellings `push`, 3-0, and `open-epic`, 2-1.
case ["push"]:
return pushed(run, config)
case ["open-epic", epic, title, *body] if len(body) <= 1 and not any(given.startswith("-") for given in (epic, title)):
return Failure("give a title of one line") if not one_line(title) else epic_opened(epic, title, body[0] if body else "", run, config)
case ["merge", *given]:
finishes = finishes_of(given)
return Failure(USAGE) if finishes is None else merged(run, config, time.sleep, finishes=finishes, parks=parks)
@@ -192,8 +227,24 @@ def default_branch(run: Run) -> str | Failure:
return default.strip().removeprefix("origin/")
@dataclasses.dataclass(frozen=True)
class Base:
"""The branch a chunk's pull request merges into. to_epic says it is an epic's working branch, which the chunk merges into whatever the config says of the default branch: `merge = "human"` and `wait-for-approval` govern only the epic branch's own pull request (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
branch: str
to_epic: bool
def base_of(branch: str, run: Run) -> Base | Failure:
"""The Base of the pull request from branch: the epic's working branch the checkout records for it (`git_repo.record_chunk_base`), else origin's default branch."""
recorded = run(["git", "config", "--get", f"branch.{branch}.{CHUNK_BASE}"])
if not isinstance(recorded, Failure) and recorded.strip():
return Base(recorded.strip(), True)
default = default_branch(run)
return default if isinstance(default, Failure) else Base(default, False)
def pull(run: Run) -> tuple[Forge, str, str] | Failure:
"""The forge, the number of the branch's open pull request at its head, and that head."""
"""The forge, the number of the branch's open pull request at its head, and that head. A Failure where the forge merges that pull request into another branch than `base_of` names: that base says whether a person merges, so no step acts while the two differ."""
found = checkout(run)
if isinstance(found, Failure):
return found
@@ -201,7 +252,12 @@ def pull(run: Run) -> tuple[Forge, str, str] | Failure:
number = open_pull(forge, branch, head, run)
if number is None:
return Failure(f"no pull request from origin's {branch} is open at {head[:12]}; push the branch, or open one with chunk-pr open")
return number if isinstance(number, Failure) else (forge, number, head)
if isinstance(number, Failure):
return number
base = base_of(branch, run)
if isinstance(base, Failure):
return base
return other_base(forge, number, base.branch, run) or (forge, number, head)
def opened(title: str, body: str, run: Run) -> str | Failure:
@@ -209,10 +265,10 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
if isinstance(found, Failure):
return found
forge, branch, head = found
base = default_branch(run)
base = base_of(branch, run)
if isinstance(base, Failure):
return base
if branch == base:
if branch == base.branch:
return Failure(f"{branch} is origin's default branch; open the pull request from the chunk's branch")
pushed = run(["git", "push", "--quiet", "--set-upstream", "origin", branch])
if isinstance(pushed, Failure):
@@ -223,7 +279,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
if isinstance(number, Failure):
return number
command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"]
created = run([*command, "--draft", "--head", branch, "--base", base, "--title", title, "--body" if forge == "gh" else "--description", body])
created = run([*command, "--draft", "--head", branch, "--base", base.branch, "--title", title, "--body" if forge == "gh" else "--description", body])
if isinstance(created, Failure):
return created
number = open_pull(forge, branch, head, run)
@@ -237,15 +293,15 @@ def synced(run: Run, config: Config) -> str | Failure:
if isinstance(found, Failure):
return found
_, branch, _ = found
base = default_branch(run)
base = base_of(branch, run)
if isinstance(base, Failure):
return base
if branch == base:
if branch == base.branch:
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
level = levelled(run, branch, base)
level = levelled(run, branch, base.branch)
if isinstance(level, Failure):
return level
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
done = f"Merged origin/{base.branch} into {branch}." if level else f"{branch} already holds origin/{base.branch}."
loaded = config()
if isinstance(loaded, Failure):
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}")
@@ -278,6 +334,18 @@ def levelled(run: Run, branch: str, base: str, resolve: str = "resolve them and
return True
def readied(run: Run, title: str | None, config: Config) -> str | Failure:
"""Mark the branch's pull request ready, then ask for a review of it as `review_asked` does."""
found = pull(run)
marked = found if isinstance(found, Failure) else marked_ready(run, title)
if isinstance(found, Failure) or isinstance(marked, Failure):
return marked
asked = review_asked(found[0], found[1], run, config)
if isinstance(asked, Failure):
return Failure(f"marked pull request #{found[1]} ready, but could not ask for a review: {asked.reason}")
return f"{marked[:-1]}, and asked for a review with “{asked}”." if asked else marked
def marked_ready(run: Run, title: str | None) -> str | Failure:
found = pull(run)
if isinstance(found, Failure):
@@ -295,6 +363,72 @@ def marked_ready(run: Run, title: str | None) -> str | Failure:
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
def pushed(run: Run, config: Config) -> str | Failure:
"""Push the branch checked out, and ask for a review of its open pull request as `review_asked` does."""
found = checkout(run)
if isinstance(found, Failure):
return found
forge, branch, head = found
sent = run(["git", "push", "--quiet", "--set-upstream", "origin", branch])
number = sent if isinstance(sent, Failure) else open_pull(forge, branch, head, run)
if isinstance(number, Failure):
return number
asked = review_asked(forge, number, run, config) if number is not None else None
if isinstance(asked, Failure):
return Failure(f"pushed {branch}, but could not ask for a review: {asked.reason}")
return f"Pushed {branch}, and asked for a review of pull request #{number} with “{asked}”." if asked else f"Pushed {branch}."
def review_asked(forge: Forge, number: str, run: Run, config: Config) -> str | None | Failure:
"""Comment on the pull request numbered number with the config's `review-request-comment`, where the pull request goes into an epic's working branch: a forge's auto-reviewer may review only pull requests into the default branch unless asked. The comment made; None where the config names none or the pull request goes into the default branch."""
branch = answers(run, ["symbolic-ref", "--short", "HEAD"])
base = branch if isinstance(branch, Failure) else base_of(branch[0], run)
if isinstance(base, Failure):
return base
if not base.to_epic:
return None
loaded = config()
if isinstance(loaded, Failure) or loaded.review_request_comment is None:
return loaded if isinstance(loaded, Failure) else None
comment = loaded.review_request_comment
made = run(["gh", "pr", "comment", number, "--body", comment] if forge == "gh" else ["tea", "comment", number, comment])
return made if isinstance(made, Failure) else comment
def epic_opened(epic: str, title: str, body: str, run: Run, config: Config) -> str | Failure:
"""Bring the working branch of the epic with the key epic level with origin's default branch, then open its pull request into that branch, ready, for a person to merge."""
if not ISSUE_KEY.fullmatch(epic):
return Failure(f"{epic!r} is no epic's key, such as ABC-123")
loaded = config()
if isinstance(loaded, Failure):
return loaded
if loaded.epic_branch is None:
return Failure("the project's config sets no `epic-branch`, so the epic has no branch to open a pull request from (`project-config --help`)")
branch = templates.epic_branch(loaded.epic_branch, epic)
found = answers(run, ["remote", "get-url", "origin"])
if isinstance(found, Failure):
return found
default = default_branch(run)
if isinstance(default, Failure):
return default
forge = forge_of(found[0])
git: Git = lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": run(["git", *args])
# `levelled` makes a branch origin lacks, which here would be a stray one: a mistyped key, or a branch its merge deleted.
held = epic_branch.on_origin(branch, None, None, git)
if not held:
return Failure(f"origin has no branch {branch}, so no chunk of {epic} has merged into one: check the epic's key, and whether the branch's pull request merged already")
level = held if isinstance(held, Failure) else epic_branch.levelled(branch, f"origin/{default}", run=git)
head = level if isinstance(level, Failure) else answers(run, ["rev-parse", f"origin/{branch}"])
number = head if isinstance(head, Failure) else open_pull(forge, branch, head[0], run)
if isinstance(number, Failure):
return number
if number is not None:
return f"{level} Pull request #{number} from {branch} is open already."
command = ["gh", "pr", "create"] if forge == "gh" else ["tea", "pulls", "create"]
created = run([*command, "--head", branch, "--base", default, "--title", title, "--body" if forge == "gh" else "--description", body])
return created if isinstance(created, Failure) else f"{level} Opened the pull request from {branch} into {default}, which a person merges."
def finishes_of(given: list[str]) -> list[list[str]] | None:
"""`todo-item finish`'s arguments for each item that merge's flags name, in their order; None where the flags are malformed."""
finishes, rest = [], given
@@ -320,15 +454,18 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
loaded = config()
if isinstance(loaded, Failure):
return loaded
by_human = loaded.merge == "human"
waits = awaited(forge, loaded.wait_for_approval, by_human)
branch = answers(run, ["symbolic-ref", "--short", "HEAD"])
base = branch if isinstance(branch, Failure) else base_of(branch[0], run)
if isinstance(base, Failure):
return base
by_human = loaded.merge == "human" and not base.to_epic
waits = awaited(forge, loaded.wait_for_approval and not base.to_epic, by_human)
if isinstance(waits, Failure):
return waits
method = merge_method(forge, run)
if isinstance(method, Failure):
return method
base = default_branch(run)
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
required = required_checks(forge, base.branch, run)
if isinstance(required, Failure):
return required
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
@@ -338,7 +475,7 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
if isinstance(absent, Failure):
return absent
file = pathlib.Path(queue[0]) / QUEUE
pull_request = Merging(forge, number, method, str(base), required, waits, by_human)
pull_request = Merging(forge, number, method, base.branch, required, waits, by_human)
while True:
with turn(file, number, sleep) as untaken:
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
@@ -356,7 +493,7 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
@dataclasses.dataclass(frozen=True)
class Merging:
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
"""A pull request that merge takes turns for: its forge and number, the merge method, the branch it merges into (`Base`) with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
forge: Forge
number: str
method: str
@@ -393,6 +530,9 @@ def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], conf
asked = unanswered(pull_request.number, run) if pull_request.waits else None
if asked is not None:
return asked
# A person may have changed the pull request's base since the turn began, as while its checks ran.
if moved := other_base(pull_request.forge, pull_request.number, pull_request.base, run):
return moved
if pull_request.forge == "gh":
done = run(["gh", "pr", "merge", pull_request.number, pull_request.method, "--match-head-commit", str(head)])
else:
@@ -476,6 +616,7 @@ def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) ->
if isinstance(finishing, Failure):
return finishing
title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan")
# Under `merge = "human"` a plan or changelog outside the checkout is finished here, before the person merges, since no run follows that merge.
# A plan in Jira, or a changelog on a Confluence page, is no file to commit.
records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()]
return committed(run, title, records)
+246 -4
View File
@@ -38,6 +38,8 @@ WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "w
# The settings a fake checkout's answers hold, each under `project-config <setting>` as the tool once read it.
PROJECT_CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
GH_BASE = ["gh", "pr", "view", "12", "--json", "baseRefName"]
TEA_PULL = ["tea", "api", "repos/{owner}/{repo}/pulls/12"]
GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"]
BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"]
COMMON = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]
@@ -55,6 +57,10 @@ class Checkout:
self.open = open
self.allowed = allowed
self.statuses: list[str] = []
# The epic's working branch the checkout records for the branch checked out; empty where it records none. Reading it is the one command the fake doesn't record.
self.chunk_base = ""
# The branch the forge merges the pull request into on each read; the last one repeats. Empty where the forge has the checkout's: chunk_base, else main.
self.bases: list[str] = []
# What GitHub reports as the pull request's review decision on each read; the last one repeats.
self.decisions = ["APPROVED"]
# Set, what GitHub prints instead of a decision's JSON.
@@ -82,9 +88,11 @@ class Checkout:
return failed
texts = {name: str(answer).strip() for name, answer in named.items()}
paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")}
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", merge=texts.get("merge", "chunk"), commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", merge=texts.get("merge", "chunk"), commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"), epic_branch=texts.get("epic-branch"), review_request_comment=texts.get("review-request-comment"))
def __call__(self, command: list[str]) -> str | Failure:
if command[:3] == ["git", "config", "--get"] and command[3].endswith(".chunk-base"):
return self.chunk_base if command[3] == f"branch.{str(self.answers[('git', 'symbolic-ref', '--short', 'HEAD')]).strip()}.chunk-base" else ""
self.ran.append(command)
if command[0] == ("tea" if self.github else "gh"):
return Failure(f"{command[0]} on the wrong forge")
@@ -98,6 +106,9 @@ class Checkout:
return json.dumps([{"number": 12, "head": {"ref": "item-7", "label": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else [])
if command == TEA_STATUS:
return self.statuses.pop(0) if self.statuses else json.dumps({"total_count": 1, "state": "success", "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]})
if command in (GH_BASE, TEA_PULL):
base = (self.bases.pop(0) if len(self.bases) > 1 else self.bases[0]) if self.bases else self.chunk_base.strip() or "main"
return json.dumps({"baseRefName": base, "base": {"ref": base}})
if command == GH_DECISION and self.unreadable is not None:
return self.unreadable
if command == GH_DECISION:
@@ -112,7 +123,7 @@ class Checkout:
def acted(self) -> list[list[str]]:
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS, GH_THREADS]
reads = [GH_LIST, GH_DECISION, GH_BASE, TEA_LIST, TEA_PULL, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS, GH_THREADS]
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
@@ -331,7 +342,7 @@ class Merge(unittest.TestCase):
def test_github_waits_for_the_checks_before_merging(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_BASE, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_failed_check_on_github_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
@@ -424,7 +435,7 @@ class Merge(unittest.TestCase):
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
checkout = self.requiring_approval()
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
self.assertEqual(checkout.ran[-5:], [GH_CHECKS, GH_DECISION, GH_THREADS, GH_BASE, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
@@ -1025,6 +1036,237 @@ class Clean(unittest.TestCase):
self.assert_kept()
def elsewhere(forge: str, checkout: str) -> str:
"""Why a step fails on pull request #12 where the forge merges it into the branch forge and the checkout takes the branch checkout as its base."""
return f"pull request #12 merges into {forge} on the forge, but this checkout takes {checkout} as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config"
class EpicBranch(unittest.TestCase):
"""A chunk whose branch the checkout records as merging into the epic's working branch ABC-1, in a project whose config sets `epic-branch`."""
COMMENT_GH = ["gh", "pr", "comment", "12", "--body", "@reviewer review"]
COMMENT_TEA = ["tea", "comment", "12", "@reviewer review"]
def checkout(self, origin: str = GITHUB, open: bool = True, comment: bool = True) -> Checkout:
checkout = Checkout(origin, open=open)
checkout.chunk_base = "ABC-1\n"
checkout.answers[(PROJECT_CONFIG, "epic-branch")] = "{epic}\n"
if comment:
checkout.answers[(PROJECT_CONFIG, "review-request-comment")] = "@reviewer review\n"
checkout.answers[("git", "rev-list", "--count", "HEAD..origin/ABC-1")] = "0\n"
return checkout
def test_open_opens_the_draft_into_the_epic_branch(self):
for origin, create in ((GITHUB, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "ABC-1", "--title", "Do it", "--body", ""]), (GITEA, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "ABC-1", "--title", "Do it", "--description", ""])):
with self.subTest(origin):
checkout = self.checkout(origin, open=False)
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.")
self.assertIn(create, checkout.ran)
def test_sync_merges_the_epic_branch_not_the_default_branch(self):
checkout = self.checkout()
checkout.answers[("git", "rev-list", "--count", "HEAD..origin/ABC-1")] = "2\n"
self.assertIn("Merged origin/ABC-1 into item-7.", str(step(["sync"], checkout, checkout.config)))
self.assertIn(["git", "merge", "--quiet", "--no-edit", "origin/ABC-1"], checkout.ran)
self.assertNotIn(MERGE, checkout.ran)
def test_merge_merges_without_a_person_whatever_the_config_says_of_the_default_branch(self):
checkout = self.checkout()
checkout.answers[(PROJECT_CONFIG, "merge")] = "human\n"
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertEqual(step(["merge"], checkout, checkout.config, parks=True), "Merged pull request #12 (merge).")
self.assertNotIn(GH_DECISION, checkout.ran)
def test_merge_fails_naming_both_branches_where_the_forge_merges_the_pull_request_into_another_branch_than_the_checkout_records(self):
for origin in (GITHUB, GITEA):
with self.subTest(origin):
checkout = self.checkout(origin)
checkout.answers[(PROJECT_CONFIG, "merge")] = "human\n"
checkout.bases = ["main"]
self.assertEqual(step(["merge"], checkout, checkout.config), Failure(elsewhere("main", "ABC-1")))
self.assertEqual(changes(checkout), [], "neither levelled, merged nor marked ready")
def test_merge_fails_naming_both_branches_where_the_forge_merges_into_an_epic_branch_a_pull_request_the_checkout_records_no_base_for(self):
checkout = self.checkout()
checkout.chunk_base, checkout.bases = "", ["ABC-1"]
self.assertEqual(step(["merge"], checkout, checkout.config), Failure(elsewhere("ABC-1", "main")))
self.assertEqual(changes(checkout), [])
def test_merge_merges_no_pull_request_whose_base_a_person_changed_while_its_checks_ran(self):
for origin in (GITHUB, GITEA):
with self.subTest(origin):
checkout = self.checkout(origin)
checkout.answers[(PROJECT_CONFIG, "merge")] = "human\n"
checkout.bases = ["ABC-1", "main"]
checkout.answers[("tea", "api", "repos/{owner}/{repo}/branches/ABC-1")] = json.dumps({"enable_status_check": False})
self.assertEqual(step(["merge"], checkout, checkout.config), Failure(elsewhere("main", "ABC-1")))
self.assertEqual(changes(checkout), [])
self.assertEqual([command for command in checkout.ran if command in (GH_BASE, TEA_PULL, GH_CHECKS, TEA_STATUS)][-2:], [GH_CHECKS, GH_BASE] if origin == GITHUB else [TEA_STATUS, TEA_PULL], "read again once the checks passed")
def test_ready_marks_no_pull_request_ready_that_the_forge_merges_into_another_branch_than_the_checkout_records(self):
checkout = self.checkout()
checkout.bases = ["main"]
self.assertEqual(step(["ready"], checkout, checkout.config), Failure(elsewhere("main", "ABC-1")))
self.assertEqual(checkout.acted(), [])
def test_a_pull_requests_base_the_forge_cannot_tell_fails_the_merge(self):
checkout = self.checkout()
checkout.answers[tuple(GH_BASE)] = Failure("gh pr view: no network")
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr view: no network"))
self.assertEqual(changes(checkout), [])
def test_ready_asks_for_the_review_the_config_names(self):
for origin, comment in ((GITHUB, self.COMMENT_GH), (GITEA, self.COMMENT_TEA)):
with self.subTest(origin):
checkout = self.checkout(origin)
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready, and asked for a review with “@reviewer review”.")
self.assertEqual(checkout.acted()[-1], comment)
def test_ready_asks_for_no_review_where_the_config_names_none_or_the_pull_request_goes_into_the_default_branch(self):
unnamed = self.checkout(comment=False)
self.assertEqual(step(["ready"], unnamed, unnamed.config), "Marked pull request #12 ready.")
into_default = self.checkout()
into_default.chunk_base = ""
self.assertEqual(step(["ready"], into_default, into_default.config), "Marked pull request #12 ready.")
for checkout in (unnamed, into_default):
self.assertNotIn(self.COMMENT_GH, checkout.ran)
def test_a_review_request_the_forge_refuses_fails_after_the_pull_request_is_ready(self):
checkout = self.checkout()
checkout.answers[tuple(self.COMMENT_GH)] = Failure("gh pr comment: denied")
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("marked pull request #12 ready, but could not ask for a review: gh pr comment: denied"))
def test_a_pull_request_the_forge_does_not_mark_ready_gets_no_review_request(self):
checkout = self.checkout()
checkout.answers[("gh", "pr", "ready", "12")] = Failure("gh pr ready: denied")
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("gh pr ready: denied"))
self.assertNotIn(self.COMMENT_GH, checkout.ran)
def test_a_push_whose_review_request_fails_says_the_branch_was_pushed_and_why_no_review_was_asked_for(self):
refused = self.checkout()
refused.answers[tuple(self.COMMENT_GH)] = Failure("gh pr comment: denied")
unconfigured = self.checkout()
unconfigured.answers[(PROJECT_CONFIG, "review-request-comment")] = Failure("no config names the checkout")
for checkout, reason in ((refused, "gh pr comment: denied"), (unconfigured, "no config names the checkout")):
with self.subTest(reason):
self.assertEqual(step(["push"], checkout, checkout.config), Failure(f"pushed item-7, but could not ask for a review: {reason}"))
self.assertIn(PUSH, checkout.ran)
def detached_on_second_read(self, checkout: Checkout) -> Run:
"""checkout, whose HEAD reads as detached from the second time the branch checked out is read."""
reads: list[list[str]] = []
def run(command: list[str]) -> str | Failure:
if command == ["git", "symbolic-ref", "--short", "HEAD"]:
reads.append(command)
if len(reads) > 1:
return Failure("git symbolic-ref: HEAD is detached")
return checkout(command)
return run
def test_a_branch_that_cannot_be_read_again_fails_the_push_review_request_and_the_merge(self):
checkout = self.checkout()
self.assertEqual(step(["push"], self.detached_on_second_read(checkout), checkout.config), Failure("pushed item-7, but could not ask for a review: git symbolic-ref: HEAD is detached"))
self.assertNotIn(self.COMMENT_GH, checkout.ran)
checkout = self.checkout()
self.assertEqual(step(["merge"], self.detached_on_second_read(checkout), checkout.config), Failure("git symbolic-ref: HEAD is detached"))
self.assertNotIn(["gh", "pr", "merge"], [command[:3] for command in checkout.ran])
def test_push_pushes_the_branch_and_asks_for_a_review_of_the_new_head(self):
checkout = self.checkout()
self.assertEqual(step(["push"], checkout, checkout.config), "Pushed item-7, and asked for a review of pull request #12 with “@reviewer review”.")
self.assertEqual(checkout.acted(), [PUSH, self.COMMENT_GH])
def test_push_only_pushes_where_no_review_is_to_ask_for(self):
unopened, unnamed, into_default = self.checkout(open=False), self.checkout(comment=False), self.checkout()
into_default.chunk_base = ""
for checkout in (unopened, unnamed, into_default):
self.assertEqual(step(["push"], checkout, checkout.config), "Pushed item-7.")
self.assertEqual(checkout.acted(), [PUSH])
def test_a_failed_push_asks_for_no_review(self):
checkout = self.checkout()
checkout.answers[tuple(PUSH)] = Failure("git push: rejected")
self.assertEqual(step(["push"], checkout, checkout.config), Failure("git push: rejected"))
self.assertNotIn(self.COMMENT_GH, checkout.ran)
ON_ORIGIN = ("git", "ls-remote", "--heads", "origin", "refs/heads/ABC-1")
def epic(self, origin: str = GITHUB) -> Checkout:
"""A Checkout whose origin holds the epic branch ABC-1, level with main."""
checkout = self.checkout(origin)
checkout.answers[self.ON_ORIGIN] = "abc123\trefs/heads/ABC-1\n"
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "0\n"
checkout.answers[("git", "rev-parse", "origin/ABC-1")] = "abc123\n"
return checkout
def test_open_epic_levels_the_epic_branch_and_opens_its_pull_request_into_the_default_branch_ready_for_a_person(self):
for origin, create in ((GITHUB, ["gh", "pr", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--body", "What it holds"]), (GITEA, ["tea", "pulls", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--description", "What it holds"])):
with self.subTest(origin):
checkout = self.epic(origin)
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic", "What it holds"], checkout, checkout.config), "origin/ABC-1 already holds origin/main. Opened the pull request from ABC-1 into main, which a person merges.")
self.assertEqual(checkout.acted()[-1], create)
self.assertIn(FETCH, checkout.ran)
def test_open_epic_merges_a_newer_default_branch_into_the_epic_branch_first(self):
checkout = self.epic()
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "3\n"
checkout.answers[("git", "merge-tree", "--write-tree", "origin/ABC-1", "origin/main")] = "7ree\n"
checkout.answers[("git", "commit-tree", "7ree", "-p", "origin/ABC-1", "-p", "origin/main", "-m", "Merge remote-tracking branch 'origin/main' into ABC-1")] = "c0mm17\n"
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config), "Merged origin/main into origin/ABC-1. Opened the pull request from ABC-1 into main, which a person merges.")
self.assertIn(["git", "push", "--quiet", "origin", "c0mm17:refs/heads/ABC-1"], checkout.ran)
self.assertEqual(checkout.acted()[-1], ["gh", "pr", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--body", ""])
def test_open_epic_returns_a_failed_fetch_or_create(self):
unfetched = self.epic()
unfetched.answers[tuple(FETCH)] = Failure("git fetch: offline")
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], unfetched, unfetched.config), Failure("git fetch: offline"))
uncreated = self.epic()
uncreated.answers[("gh", "pr", "create", "--head", "ABC-1", "--base", "main", "--title", "Ship the epic", "--body", "")] = Failure("gh pr create: denied")
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], uncreated, uncreated.config), Failure("gh pr create: denied"))
def test_open_epic_leaves_a_conflict_with_the_default_branch_to_a_person_and_opens_nothing(self):
checkout = self.epic()
checkout.answers[("git", "rev-list", "--count", "origin/ABC-1..origin/main")] = "3\n"
checkout.answers[("git", "merge-tree", "--write-tree", "origin/ABC-1", "origin/main")] = Failure("git merge-tree --write-tree: " + "a" * 40 + "\nCONFLICT (content): Merge conflict in a.txt")
done = step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config)
self.assertIsInstance(done, Failure)
self.assertIn("a person merges it", done.reason)
self.assertFalse(any(command[:3] == ["gh", "pr", "create"] for command in checkout.ran))
def test_open_epic_makes_no_branch_where_origin_has_none_for_the_epic_though_the_checkout_still_tracks_one_its_merge_deleted(self):
checkout = self.epic()
checkout.answers[self.ON_ORIGIN] = ""
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config), Failure("origin has no branch ABC-1, so no chunk of ABC-1 has merged into one: check the epic's key, and whether the branch's pull request merged already"))
self.assertFalse(any(command[:2] in (["git", "push"], ["gh", "pr"]) for command in checkout.ran))
def test_open_epic_fails_with_gits_reason_where_origin_cannot_say_whether_it_has_the_branch(self):
checkout = self.epic()
checkout.answers[self.ON_ORIGIN] = Failure("git ls-remote: offline")
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config), Failure("git ls-remote: offline"))
self.assertFalse(any(command[:2] in (["git", "push"], ["gh", "pr"]) for command in checkout.ran))
self.assertEqual([command[1] for command in checkout.ran if command[1] in ("fetch", "ls-remote")], ["ls-remote"])
def test_open_epic_opens_no_second_pull_request(self):
checkout = self.epic()
checkout.answers[("gh", "pr", "list", "--head", "ABC-1", *GH_LIST[5:])] = "31\tabc123\tfalse\n"
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], checkout, checkout.config), "origin/ABC-1 already holds origin/main. Pull request #31 from ABC-1 is open already.")
self.assertFalse(any(command[:3] == ["gh", "pr", "create"] for command in checkout.ran))
def test_open_epic_refuses_where_the_config_names_no_epic_branch_or_the_title_is_not_one_line(self):
unset = Checkout(GITHUB, open=False)
self.assertEqual(step(["open-epic", "ABC-1", "Ship the epic"], unset, unset.config), Failure("the project's config sets no `epic-branch`, so the epic has no branch to open a pull request from (`project-config --help`)"))
self.assertEqual(unset.ran, [])
checkout = self.epic()
self.assertEqual(step(["open-epic", "ABC-1", "Ship\nit"], checkout, checkout.config), Failure("give a title of one line"))
for malformed in (["open-epic", "ABC-1"], ["open-epic", "ABC-1", "Ship it", "Body", "More"], ["open-epic", "--help", "Ship it"], ["open-epic", "ABC-1", "-Ship it"]):
with self.subTest(malformed):
self.assertEqual(step(malformed, checkout, checkout.config), Failure(USAGE))
self.assertEqual(step(["open-epic", "abc/../1", "Ship it"], checkout, checkout.config), Failure("'abc/../1' is no epic's key, such as ABC-123"))
self.assertEqual(checkout.ran, [])
class Launcher(unittest.TestCase):
def test_help_exits_0_and_a_wrong_step_exits_1(self):
self.assertEqual(subprocess.run([str(TOOL), "--help"], capture_output=True, env=isolated_env()).returncode, 0)
+7 -5
View File
@@ -9,11 +9,13 @@ PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": (
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
for block in porcelain.split("\n\n"):
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
if fields.get("branch") == f"refs/heads/{branch}":
return pathlib.Path(fields["worktree"])
return None
return next((path for path, on, _ in worktrees(porcelain) if on == branch), None)
def worktrees(porcelain: str) -> list[tuple[pathlib.Path, str, str]]:
"""Each worktree on a branch, in what `git worktree list --porcelain` printed: its path, its branch and its head commit."""
blocks = [dict(line.partition(" ")[::2] for line in block.splitlines()) for block in porcelain.split("\n\n")]
return [(pathlib.Path(fields["worktree"]), fields["branch"].removeprefix("refs/heads/"), fields.get("HEAD", "")) for fields in blocks if fields.get("branch", "").startswith("refs/heads/")]
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
+11 -1
View File
@@ -19,7 +19,7 @@ def render(found: Gathered) -> list[str]:
"""One `- ` line per fact, then the item's tagline and detail, the detail of each item that may join its chunk, and what each tool printed."""
note = [f"- {found.note}"] if found.note else []
unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else []
head = [*note, f"- {last_release(found.default, found.cut)}", *unseen]
head = [*note, f"- {last_release(found.default, found.cut)}", *unseen, *merge_lines(found)]
paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}."
texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}."
if isinstance(found.item, NoItem):
@@ -28,6 +28,16 @@ def render(found: Gathered) -> list[str]:
return [*head, *lines[:2], paths, texts, *lines[2:]]
def merge_lines(found: Gathered) -> list[str]:
"""What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, or why those pull requests could not be read."""
left = [f"- The worktree {worktree.path}, on the branch {worktree.branch}, is left from pull request #{worktree.pull}, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step." for worktree in found.left]
items = found.item.plan.items if isinstance(found.item, ItemFacts) else []
passed = [f"item {item.id}, by pull request {item.awaits_merge}" for item in items if item.awaits_merge]
over = [f"- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: {'; '.join(passed)}. No chunk takes one."] if passed else []
unread = [f"- The pull requests that await a person's merge cannot be read, so no item is passed over for one: {found.merges_unread.reason}"] if found.merges_unread else []
return [*left, *over, *unread]
def last_release(default: str, release: LastCut) -> str:
if isinstance(release.tag, Failure):
return f"Last version cut: cannot be read: {release.tag.reason}"
+13
View File
@@ -44,6 +44,15 @@ class ItemFacts:
tools: list[tuple[str, Ran | Failure]]
@dataclasses.dataclass(frozen=True)
class LeftWorktree:
"""A worktree on a branch whose pull request has merged."""
path: pathlib.Path
branch: str
# The merged pull request's number.
pull: str
@dataclasses.dataclass(frozen=True)
class Gathered:
"""Everything the preflight read and ran, for facts.render to state."""
@@ -62,3 +71,7 @@ class Gathered:
plan_outside: bool
# The language and the templates the project's config names, by their settings.
texts: dict[str, str]
# Why the pull requests that await a person's merge could not be read; None where they were read or not asked for.
merges_unread: Failure | None = None
# The worktrees `chunk-pr clean` is still to remove.
left: tuple[LeftWorktree, ...] = ()
+55 -14
View File
@@ -16,10 +16,15 @@ and prints that the release reviews and the cuts are the human's to call. It pri
newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count.
Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how
many commits followed the cut: the tag, or the commit that added that heading;
- under `merge = "human"` (`project-config --help`), each worktree beside the checkout whose pull
request has merged, for the worker to run `chunk-pr clean` in, and each item passed over: one
finished on the branch of an open pull request that is not a draft, where the checkout holds
the plan. Where no item of the release can start and one awaits such a merge, it names those
pull requests and says the working loop stops there;
- the next release and its first item that does not wait, the item loop-claude routes on, with its L
and E + I; with --item <ID>, the plan item of that ID instead, which loop-claude names in a window
named for an item. An item waits while it is marked question, or while an item still in todo.md
blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
named for an item. An item waits while it is marked question, while an item still in todo.md
blocks it, or while it awaits such a merge. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed.
Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a
release whose items are all done still reads as next.
@@ -36,7 +41,11 @@ and prints that the release reviews and the cuts are the human's to call. It pri
each / of the branch a dash, on the branch the config's `branch` template names, which is
item-<ID> where the config names none. It continues a worktree already on that branch; else it adds one on the
local branch, else on a new branch tracking origin's, else on a new branch off the default
branch. Without --worktree, it prints that none was made;
branch. Without --worktree, it prints that none was made. Where the config sets `epic-branch`
(`project-config --help`), it first makes the working branch of the plan's epic on origin, off
the default branch, or merges the default branch into it; a new branch is then made off that
branch, and the checkout records that the chunk's pull request goes into it, for `chunk-pr`.
Where the two don't merge cleanly, it makes no worktree and says how a person merges them;
- each path the project's config sets, as `project-config` prints them in that worktree, or else
in the checkout;
- the language the config names for the project's prose, and its templates for commit titles,
@@ -76,16 +85,20 @@ import subprocess
import sys
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, record_chunk_base, top
from git_cli import epic_branch
from failure import Failure
from forge.commands import Forge, forge_of
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
from forge.commands import Forge, forge_of, Run, runner
from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree
from chunk_preflight.facts import JOINING_DETAILS, render
from project_config.main import located
from forge.pulls import merged_pull
from plan.named_paths import named_paths
from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned
from release_plan.release_standing import project_plan
from chunk_preflight.choices import pulls_command, worktree_add, worktree_on
from project_config.settings import ProjectConfig
from chunk_preflight.choices import pulls_command, worktree_add, worktree_on, worktrees
from project_config import templates
BIN = pathlib.Path(__file__).resolve().parents[1]
# Each tool run in the item's worktree, {item} standing for the item's ID.
@@ -143,22 +156,41 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non
if isinstance(config, Failure):
return config
outside = None if config.tracked("plan") else config.plan_label
held = project_plan(config, ref, str(root))
forge_run = runner(str(root), timeout)
held = project_plan(config, ref, str(root), forge_run=forge_run)
plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make, epic_branch_of(config))
# A `checkout:` path lands in the worktree the chunk works in.
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts))
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, merges_unread=held.merges_unread, left=left_worktrees(root, forge_run) if config.merge == "human" else ()))
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts:
worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.")
def epic_branch_of(config: ProjectConfig) -> str | None | Failure:
"""The working branch of the plan's epic, as the config's `epic-branch` names it; None where the config sets none."""
if config.epic_branch is None:
return None
if config.epic is None:
return Failure("none made: the config sets `epic-branch`, but its `plan` names no Jira epic to name the branch by; chunk-preflight makes an epic's chunks only from a plan kept in Jira")
return templates.epic_branch(config.epic_branch, config.epic.key)
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool, epic: str | None | Failure = None) -> ItemFacts:
worktree = Failure(f"none made, since it ran without {WORKTREE}.") if not make else epic if isinstance(epic, Failure) else item_worktree(root, plan.branch, default, timeout, epic)
path = worktree.path if isinstance(worktree, Worktree) else None
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure:
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else."""
def item_worktree(root: pathlib.Path, branch: str, default: str, timeout: float | None = None, epic: str | None = None) -> Worktree | Failure:
"""The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else.
epic names the working branch of the chunk's epic, where the project keeps one. The worktree then branches off that branch, which is first made on origin or brought level with default (`epic_branch.levelled`), and the checkout records that the chunk merges into it."""
if epic is not None:
level = epic_branch.levelled(epic, default, timeout=timeout)
recorded = level if isinstance(level, Failure) else record_chunk_base(branch, epic)
if isinstance(recorded, Failure):
return Failure(f"none made: {recorded.reason}")
made = item_worktree(root, branch, f"origin/{epic}")
return made if isinstance(made, Failure) else Worktree(made.path, f"{made.how} {level} The chunk's pull request goes into {epic}.")
listing = git("worktree", "list", "--porcelain")
if isinstance(listing, Failure):
return listing
@@ -173,6 +205,15 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | F
return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how)
def left_worktrees(root: pathlib.Path, forge_run: Run) -> tuple[LeftWorktree, ...]:
"""Each worktree but root that is on a branch whose pull request merged with the worktree's head commit as its head: under `merge = "human"` a person merges after the chunk's run has ended, so its worker never ran `chunk-pr clean`. Where the forge can't be asked, no worktree counts as left."""
listing, url = git("worktree", "list", "--porcelain"), git("remote", "get-url", "origin")
if isinstance(listing, Failure) or isinstance(url, Failure):
return ()
merged = [(path, branch, merged_pull(forge_of(url), branch, head, forge_run)) for path, branch, head in worktrees(listing) if path != root]
return tuple(LeftWorktree(path, branch, pull) for path, branch, pull in merged if isinstance(pull, str))
def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None:
url = git("remote", "get-url", "origin")
if isinstance(url, Failure):
+118 -3
View File
@@ -1,3 +1,4 @@
import contextlib
import dataclasses
import os
import pathlib
@@ -11,15 +12,18 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.templates import BRANCH
from release_plan.next_chunk import CarriedOver, NoItem
from project_config.settings import Epic, ProjectConfig
from chunk_preflight.main import epic_branch_of, item_facts as facts_made, item_worktree, line_count, ran, seconds, TIMEOUT
from failure import Failure
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree
from git_cli import git_repo
from test_env import isolated_env
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from release_plan.awaiting_merge import marked
from release_plan import next_chunk
from chunk_preflight.facts import open_pulls, render
from plan_store.todo_md import plan_of
from chunk_preflight.choices import worktree_add
from chunk_preflight.choices import worktree_add, worktree_on, worktrees
from project_config.doubles import write_config
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -135,6 +139,34 @@ class Repo:
class ChunkPreflightTool(unittest.TestCase):
def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_and_names_a_worktree_a_merged_one_left(self):
repo = Repo(self, origin="github.com/o/r.git")
config = repo.temp / "home" / ".claude-projects" / "proj" / "config.toml"
config.write_text(config.read_text() + 'merge = "human"\n')
repo.git(repo.root, "worktree", "add", "--quiet", "-b", "item-3", str(repo.temp / "proj-item-3"), "main")
repo.write(repo.temp / "proj-item-3", "todo.md", TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", ""))
repo.commit(repo.temp / "proj-item-3", "Finish item 3 in the plan")
ready = repo.git(repo.temp / "proj-item-3", "rev-parse", "HEAD").strip()
repo.git(repo.root, "worktree", "add", "--quiet", "-b", "item-2", str(repo.temp / "proj-item-2"), "main")
left = repo.git(repo.temp / "proj-item-2", "rev-parse", "HEAD").strip()
(repo.fake / "gh").write_text(f"""#!{sys.executable}
import sys
args = sys.argv[1:]
if args[:4] == ["pr", "list", "--limit", "100"]:
print("12\\thttps://github.com/o/r/pull/12\\t{ready}\\tfalse\\tfalse")
elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]:
print("11\\t{left}\\tfalse")
""")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(f"- The worktree {repo.temp}/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.\n", done.stdout)
self.assertNotIn("proj-item-3, on the branch", done.stdout, "an open pull request leaves no worktree to clean")
self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.", done.stdout)
(repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n")
unread = repo.preflight()
self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: gh pr list: not logged in\n", unread.stdout)
self.assertIn("Its first item that does not wait: item 3,", unread.stdout)
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self):
repo = Repo(self)
folder = repo.temp / "home" / ".claude-projects" / "proj"
@@ -408,6 +440,20 @@ def rendered(item, release=CUT, note=None):
class Render(unittest.TestCase):
def test_reads_each_worktree_on_a_branch_from_gits_listing(self):
porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/my proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n"
self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/my proj-item-2"), "item-2", "bbb")])
self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/my proj-item-2"), None))
def test_states_what_a_persons_merge_leaves_only_where_there_is_something(self):
self.assertNotIn("merge", rendered(item_facts()))
found = gathered(NoItem("the plan holds none."))
left = dataclasses.replace(found, left=(LeftWorktree(pathlib.Path("/c/proj-item-2"), "item-2", "11"),), merges_unread=Failure("`gh pr list` exited 1: no"))
passed = "\n".join(render(gathered(item_facts(marked(plan_of(TODO), {7: "#12 https://github.com/o/r/pull/12", 8: "#13 https://github.com/o/r/pull/13"})))))
self.assertIn("\n- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: item 7, by pull request #12 https://github.com/o/r/pull/12; item 8, by pull request #13 https://github.com/o/r/pull/13. No chunk takes one.\n", passed)
self.assertIn("- No other item of release 0.2.0 may join item 3's chunk.", passed)
self.assertEqual(render(left)[1:3], ["- The worktree /c/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.", "- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: no"])
def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
said = rendered(item_facts())
self.assertIn("origin/main's todo.md: 0.2.0", said)
@@ -542,6 +588,75 @@ class Render(unittest.TestCase):
self.assertIn("`larv-review places` could not finish: timed out", said)
class EpicBranchWorktree(unittest.TestCase):
"""A chunk's worktree in a project whose config names an epic's working branch, here ABC-1."""
def setUp(self):
self.repo = Repo(self)
self.enterContext(contextlib.chdir(self.repo.root))
# item_worktree runs git in this process's environment, so the identity its merge commit needs is the checkout's own.
for name, value in (("user.name", "t"), ("user.email", "t@example.com")):
self.repo.git(self.repo.root, "config", name, value)
def test_the_first_chunk_makes_the_epic_branch_on_origin_and_branches_off_it_recording_where_it_merges(self):
made = item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
self.assertEqual(made, Worktree(self.repo.temp / "proj-ABC-7", "added on the new branch ABC-7, made off origin/ABC-1. Made origin/ABC-1 off origin/main. The chunk's pull request goes into ABC-1."))
self.assertEqual(self.repo.git(self.repo.origin, "rev-parse", "ABC-1"), self.repo.git(self.repo.root, "rev-parse", "origin/main"))
self.assertEqual(git_repo.default_ref(str(made.path)), "origin/ABC-1")
def test_a_later_chunk_branches_off_what_the_epic_branch_holds(self):
item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
first = self.repo.temp / "proj-ABC-7"
self.repo.write(first, "src/first.py", "FIRST = 1\n")
self.repo.commit(first, "first")
self.repo.git(first, "push", "--quiet", "origin", "ABC-7:ABC-1")
made = item_worktree(self.repo.root, "ABC-8", "origin/main", 30, "ABC-1")
self.assertIn("origin/ABC-1 already holds origin/main.", made.how)
self.assertTrue((made.path / "src/first.py").exists())
def test_a_default_branch_that_conflicts_with_the_epic_branch_makes_no_worktree_and_leaves_it_to_a_person(self):
item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1")
first = self.repo.temp / "proj-ABC-7"
self.repo.write(first, "src/app.py", "def run():\n\treturn 2\n\n")
self.repo.commit(first, "first")
self.repo.git(first, "push", "--quiet", "origin", "ABC-7:ABC-1")
self.repo.push_from_elsewhere("src/app.py", "def run():\n\treturn 3\n\n")
made = item_worktree(self.repo.root, "ABC-8", "origin/main", 30, "ABC-1")
self.assertIsInstance(made, Failure)
self.assertTrue(made.reason.startswith("none made: origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it"), made.reason)
self.assertFalse((self.repo.temp / "proj-ABC-8").exists())
def test_a_worktree_path_that_holds_something_else_makes_no_worktree_off_the_epic_branch(self):
taken = self.repo.temp / "proj-ABC-7"
taken.mkdir()
self.assertEqual(item_worktree(self.repo.root, "ABC-7", "origin/main", 30, "ABC-1"), Failure(f"none made, since {taken} exists and holds no worktree on the branch ABC-7"))
def test_names_the_epic_branch_by_the_plans_epic_and_none_where_the_config_sets_no_template(self):
config = ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), {}, epic=Epic("https://acme.atlassian.net", "ABC-1"), epic_branch="epic/{epic}")
self.assertEqual(epic_branch_of(config), "epic/ABC-1")
self.assertIsNone(epic_branch_of(dataclasses.replace(config, epic_branch=None)))
self.assertEqual(epic_branch_of(dataclasses.replace(config, epic=None)), Failure("none made: the config sets `epic-branch`, but its `plan` names no Jira epic to name the branch by; chunk-preflight makes an epic's chunks only from a plan kept in Jira"))
def test_the_facts_of_an_item_put_its_worktree_on_the_epic_branch_they_are_given(self):
facts = facts_made(self.repo.root, "origin/main", planned(TODO, CUT, "origin/main", BRANCH), 30, True, "ABC-1")
self.assertEqual(facts.worktree.path, self.repo.temp / "proj-item-3")
self.assertTrue(facts.worktree.how.endswith("The chunk's pull request goes into ABC-1."), facts.worktree.how)
self.assertEqual(self.repo.git(self.repo.root, "config", "--get", "branch.item-3.chunk-base"), "ABC-1\n")
def test_the_facts_of_an_item_make_no_worktree_where_the_epic_branch_cannot_be_named(self):
unnamed = Failure("none made: the plan names no epic")
self.assertEqual(facts_made(self.repo.root, "origin/main", planned(TODO, CUT, "origin/main", BRANCH), 30, True, unnamed).worktree, unnamed)
self.assertFalse((self.repo.temp / "proj-item-3").exists())
def test_the_tool_makes_no_worktree_where_the_config_sets_an_epic_branch_and_keeps_its_plan_in_a_file(self):
config = self.repo.temp / "home" / ".claude-projects" / "proj" / "config.toml"
config.write_text(config.read_text() + 'epic-branch = "{epic}"\n')
done = self.repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("none made: the config sets `epic-branch`, but its `plan` names no Jira epic to name the branch by", done.stdout)
self.assertFalse((self.repo.temp / "proj-item-3").exists())
class OpenPulls(unittest.TestCase):
def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self):
self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"])
+10
View File
@@ -84,6 +84,16 @@ def parse_entry(raw: str | bytes) -> Entry | None:
return None if found is None else entry_from(found)
def json_objects(raw: bytes) -> list[dict]:
"""The lines of a transcript or a stream-json stream that are JSON objects, parsed."""
return [found for line in raw.splitlines() if (found := json_object(line)) is not None]
def entries_of(raw: bytes) -> list[Entry]:
"""The entries of a transcript or a stream-json stream, one per line that is a JSON object."""
return [entry_from(found) for found in json_objects(raw)]
def entry_from(found: dict) -> Entry:
"""A transcript entry, or a stream-json event, as its kind."""
carried = Carried(uuid=field(found, "uuid"), parent_uuid=field(found, "parentUuid"), timestamp=field(found, "timestamp"), cwd=field(found, "cwd"), git_branch=field(found, "gitBranch"))
+15 -2
View File
@@ -12,7 +12,7 @@ NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@dataclasses.dataclass(frozen=True)
class Session:
"""Exists while its transcript does."""
"""Open while its transcript holds something: claude cannot resume an empty one."""
id: uuid.UUID
claude_code_transcripts: pathlib.Path
name: str
@@ -29,7 +29,20 @@ def transcript_file(session: Session) -> str | None:
def session_open(session: Session) -> bool:
return transcript_file(session) is not None
path = transcript_file(session)
return path is not None and os.path.getsize(path) > 0
def discard_empty_transcript(session: Session) -> Failure | None:
"""Removes the 0-byte transcript a failed run can leave: claude refuses `--session-id` for an id whose file stands, and cannot `--resume` it."""
path = transcript_file(session)
if path is None or os.path.getsize(path) > 0:
return None
try:
os.remove(path)
except OSError as failure:
return Failure(f"could not remove the empty transcript {path}: {failure.strerror or failure}; claude refuses to start the session while that file stands")
return None
# <session id>.jsonl, <session id>/subagents/, and from older Claude Code versions <session id>.superseded-*/ and <session id>.orphaned-*.jsonl
+41 -1
View File
@@ -2,11 +2,13 @@ import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from claude_code import entries, reply, transcript
from test_env import assert_not_root
from claude_code import entries, reply, session, transcript
from failure import Failure
@@ -99,6 +101,11 @@ class Parse(unittest.TestCase):
self.assertEqual(entries.parse_entry('{"type": "user", "message": {"content": "do it"}}'), entries.HumanTurn(text="do it"))
self.assertIsNone(entries.parse_entry("[1, 2]"))
def test_a_stream_parses_into_an_entry_per_line_that_is_a_json_object(self):
raw = b'{"type": "user", "message": {"content": "do it"}}\nnot json\n\n{"type": "summary"}\n{}\n'
self.assertEqual(entries.entries_of(raw), [entries.HumanTurn(text="do it"), entries.Entry(), entries.Entry()])
self.assertEqual(entries.entries_of(b""), [])
class EntryKinds(unittest.TestCase):
def test_names_who_wrote_each_user_entry_and_queued_prompt(self):
@@ -219,5 +226,38 @@ class ClaudeReply(unittest.TestCase):
self.assertEqual(reply.claude_reply(self.claude(FileNotFoundError(2, "No such file or directory")), [], "/r", "p", "claude"), Failure("could not start claude: No such file or directory"))
class EmptyTranscript(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.session = session.session_named("A proj a-driver", pathlib.Path(temp.name))
self.path = pathlib.Path(temp.name) / "-home-me-code-log" / f"{self.session.id}.jsonl"
self.path.parent.mkdir()
def test_a_session_is_open_only_where_its_transcript_holds_something(self):
self.assertFalse(session.session_open(self.session))
self.path.touch()
self.assertFalse(session.session_open(self.session))
self.path.write_text("{")
self.assertTrue(session.session_open(self.session))
def test_discarding_removes_an_empty_transcript_and_keeps_one_that_holds_something(self):
self.path.touch()
self.assertIsNone(session.discard_empty_transcript(self.session))
self.assertFalse(self.path.exists())
self.path.write_text("{")
self.assertIsNone(session.discard_empty_transcript(self.session))
self.assertEqual(self.path.read_text(), "{")
def test_discarding_fails_naming_the_file_it_could_not_remove(self):
assert_not_root(self)
self.path.touch()
self.path.parent.chmod(0o500)
self.addCleanup(self.path.parent.chmod, 0o700)
failure = session.discard_empty_transcript(self.session)
self.assertIsInstance(failure, Failure)
self.assertEqual(failure.reason, f"could not remove the empty transcript {self.path}: Permission denied; claude refuses to start the session while that file stands")
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -4,7 +4,7 @@ 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
in the review folders, ~/.local/state/larv-review, every file but a lock, *.lock. 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
@@ -47,10 +47,11 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, now
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."""
"""Each plain file under root that pattern matches and that last changed before the cutoff, sorted; a lock, `*.lock`, is left alone, and so is a link, since its target lies elsewhere."""
found = []
for path in root.rglob(pattern):
if path.name.endswith(SUFFIX) or path.is_symlink():
# A lock file is held by its name and never written, so its age doesn't say that it is out of use: task-bench.lock.
if path.name.endswith((SUFFIX, ".lock")) or path.is_symlink():
continue
try:
status = path.stat()
@@ -70,6 +70,11 @@ class Main(unittest.TestCase):
self.assertEqual(out, "Compressed 4 files.\n")
self.assertEqual(self.run_main(), (0, "Compressed 0 files.\n", ""))
def test_keeps_a_lock_plain_however_old(self):
self.write(self.reviews / "task-bench.lock", OLD)
self.run_main()
self.assertEqual([path.name for path in self.reviews.glob("task-bench.lock*")], ["task-bench.lock"])
def test_keeps_a_file_last_written_exactly_30_days_ago_plain(self):
self.write(self.archive / "b.jsonl", 30 * DAY)
self.run_main()
+56 -21
View File
@@ -2,6 +2,7 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import contextlib
import pathlib
import shutil
import sys
@@ -16,12 +17,15 @@ from failure import Failure
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from forge.commands import forge_of, runner
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
from plan.release import newest_tag, Release, tagged, UNRELEASED_HEADING, version
from forge import pulls
from deploy_release import release_pull
from project_config import templates
CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version."
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
if isinstance(same := same_origin(clone, checkout), Failure):
@@ -37,10 +41,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
if isinstance(release, Failure):
return release
named = version(release)
title, tag = f"Cut release {named}", f"v{named}"
if isinstance(patched := patch_refusal(clone, ref, release), Failure):
return patched
title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}"
merged = commit_titled(title, ref, clone)
if merged is None:
landed = land(clone, ref, named, title, sleep)
build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep)
if isinstance(landed, Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
@@ -58,13 +65,24 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
delete_release_branch(clone, f"release-{named}")
delete_release_branch(clone, branch)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None:
"""A Failure where release is a patch of the newest tag ref holds: a cut of all of ref would ship its other work under a patch number."""
tag = newest_tag(clone, merged_into=ref)
if isinstance(tag, Failure):
return tag
cut_release = tagged(tag)
if cut_release is not None and release[:2] == cut_release[:2]:
return Failure(f"{version(release)} is a patch of {tag}: cut it with --cut-patch <commits>, so it holds only the fix and not all of {ref}")
return None
def said(step: str) -> None:
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
print(f"deploy-release: {step}", file=sys.stderr)
@@ -100,13 +118,13 @@ def drop_unpushed_cut_tags(clone: str) -> Failure | None:
def same_origin(clone: str, checkout: str) -> Failure | None:
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so --cut never cuts another project."""
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so a cut never cuts another project."""
urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)]
failed = next((url for url in urls if isinstance(url, Failure)), None)
if failed is not None:
return failed
if urls[0] != urls[1]:
return Failure(f"run --cut in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
return Failure(f"run deploy-release in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
return None
@@ -116,8 +134,8 @@ def clone_plan(clone: str) -> FilePlan:
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased."""
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
if isinstance(plan.plan, Failure):
@@ -129,6 +147,8 @@ def ready_release(clone: str, ref: str) -> Release | Failure:
return Failure("todo.md names no release after the last one cut")
case Next(release=release) if release is not None:
return Failure(f"release {version(release)} still holds items in todo.md")
case ReviewDue(release=release) if not review and release is not None:
return release
case ReviewDue(release=release):
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
case Unplanned():
@@ -150,12 +170,14 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[float], None]) -> Failure | None:
"""Push the branch release-<named> with the cut commit and open its pull request, where an earlier run hasn't; then wait for its checks and merge it."""
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None]) -> Failure | None:
"""Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it.
build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet."""
url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure):
return url
on, run, branch, base = forge_of(url), runner(clone), f"release-{named}", ref.removeprefix("origin/")
on, run, base = forge_of(url), runner(clone), ref.removeprefix("origin/")
head = branch_head(branch, clone)
if isinstance(head, Failure):
return head
@@ -164,7 +186,7 @@ def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[f
return behind
if head is None or behind:
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure):
if isinstance(pushed := build(head), Failure):
return pushed
said(f"pushed the branch {branch}")
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
@@ -172,7 +194,7 @@ def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[f
return head
number = pulls.open_pull(on, branch, head, run)
if number is None:
if isinstance(created := release_pull.create_pull(on, branch, base, title, run), Failure):
if isinstance(created := release_pull.create_pull(on, branch, base, title, body, run), Failure):
return created
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):
@@ -206,11 +228,10 @@ def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure:
def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, replacing: str | None) -> Failure | None:
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own so the clone's checkout stays as it is, and push it as branch: a new one, or in place of replacing, the commit origin's branch points at."""
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "cut"
try:
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
return added
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own, and push it as branch, replacing the commit origin's branch points at, where there is one."""
with scratch_worktree(clone, ref) as worktree:
if isinstance(worktree, Failure):
return worktree
changelog = worktree / "CHANGELOG.md"
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
@@ -218,9 +239,23 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
changelog.write_text(renamed)
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
return committed
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
return pushed if isinstance(pushed, Failure) else None
return push_branch(worktree, branch, replacing)
@contextlib.contextmanager
def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]:
"""A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it."""
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "worktree"
try:
added = git("worktree", "add", "--quiet", "--detach", str(worktree), at, cwd=clone)
yield added if isinstance(added, Failure) else worktree
finally:
git("worktree", "remove", "--force", str(worktree), cwd=clone)
shutil.rmtree(worktree.parent, ignore_errors=True)
def push_branch(worktree: pathlib.Path, branch: str, replacing: str | None) -> Failure | None:
"""Push worktree's HEAD to origin as branch: a new one, or in place of replacing, only while origin's branch still points at it."""
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
return pushed if isinstance(pushed, Failure) else None
+37 -8
View File
@@ -1,6 +1,6 @@
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release.
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release, and with --cut-patch, a patch release of only the commits named.
usage: deploy-release [--cut] [<checkout>]
usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]
<checkout> defaults to ~/.claude. The tool fetches origin's tags and checks out the newest v* tag,
detached, so the checkout holds only what a release holds. Development happens in another clone,
@@ -18,7 +18,9 @@ memory, stay as they are.
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
refuses without changing anything, unless that release holds no item in todo.md, its release review has
landed and changes are unreleased. The release names the version; the tool doesn't choose one.
landed and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
release that is a patch of the newest tag, such as 0.15.2 after v0.15.1, since it would ship all of main: cut that
with --cut-patch.
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
@@ -35,6 +37,28 @@ Where a step fails it stops, exit 1, with git's or the forge's reason, and leave
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
move stopped, fix what it names and run a bare deploy-release.
--cut-patch <commits> runs in the development clone too, for a fix that must ship before main's other unreleased work. It
cuts the newest tag's next patch release, holding only <commits> on top of the tag. <commits> is a range as git log reads
it, such as 794ce37..1aa2367, which leaves out 794ce37 as git's `..` does, or one commit, which it reads as that commit
alone. Name the commits the fix's chunk merged, including the one that finished its item: the entries that commit added
under ## Unreleased in CHANGELOG.md become the release's. Each commit must be on origin's main and not in the tag. Merge
commits are left out, and so are the commits a merge of main brought into the range. todo.md must name the release and
file no item under it; a patch skips the release review. Cut it as soon as the fix merges: until then chunk-preflight calls
the patch's release review due, and loop-claude would run it. It refuses without changing anything where any of that
doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from main's history.
1. It says on stderr which commits the release ships.
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
3. It runs ci.sh on that commit, and stops where it fails, before anything is tagged.
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
release-<version> and a pull request as --cut does. Then it checks main holds the tag.
6. It moves <checkout> to the tag as above, and ends stdout as --cut does.
A rerun takes a tag origin holds already, once it checks the tag lists the same changelog entries, and the merge-back's open
pull request. Once the merge-back has merged, the release is cut: where only the move stopped, run a bare deploy-release.
"""
import os
import pathlib
@@ -42,6 +66,7 @@ import sys
import time
from deploy_release.cut import cut
from deploy_release.patch import cut_patch
from deploy_release.deploy import deploy
from failure import Failure
@@ -50,13 +75,17 @@ def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
cutting = argv[:1] == ["--cut"]
rest = argv[1:] if cutting else argv
if len(rest) > 1 or rest[:1] and rest[0].startswith("-"):
print("deploy-release: usage: deploy-release [--cut] [<checkout>]", file=sys.stderr)
cutting, patching = argv[:1] == ["--cut"], argv[:1] == ["--cut-patch"]
commits = argv[1] if patching and len(argv) > 1 else None
rest = argv[2:] if patching else argv[1:] if cutting else argv
if len(rest) > 1 or rest[:1] and rest[0].startswith("-") or patching and (commits is None or commits.startswith("-")):
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
return 1
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
if commits is not None:
moved = cut_patch(os.getcwd(), checkout, commits, time.sleep)
else:
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
return 1
+235
View File
@@ -0,0 +1,235 @@
"""`deploy-release --cut-patch <commits>`: cut the newest tag's next patch release holding only the commits named, test it with ci.sh, tag it, merge the tag back into main through a pull request, then move ~/.claude to it.
A rerun takes the tag an earlier run pushed, once it checks the tag lists the same changelog entries, and the merge-back's open pull request.
"""
import dataclasses
import pathlib
import re
import subprocess
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
from deploy_release.deploy import deploy
from failure import Failure
from forge.commands import forge_of
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
LEFT_AS_TAGGED = ("CHANGELOG.md", "docs/comprehension-history.md", "docs/reading-cost.md", "todo.md")
MERGE_BACK_BODY = "Merge the patch release's tag into main, keeping main's files, and list its changelog entries under its version."
@dataclasses.dataclass(frozen=True)
class Patch:
"""A patch release ready to cut."""
# origin's default branch, as default_ref names it.
ref: str
# The newest tag ref holds, which the patch goes on top of.
base: str
# The patch's version, the base's next patch.
named: str
# The commits the patch ships, oldest first.
commits: list[str]
# The CHANGELOG.md entries the commits added under ref's ## Unreleased, in ref's order.
entries: list[str]
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit."""
patch = planned(clone, checkout, commits)
if isinstance(patch, Failure):
return patch
for commit in patch.commits:
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
tag, branch = f"v{patch.named}", f"release-{patch.named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
if isinstance(made, Failure):
return made
build = lambda replacing: push_merge_back(clone, patch, replacing)
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
return fetched
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
delete_release_branch(clone, branch)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
"""The patch commits names, once the clone, the plan and the commits allow it; a Failure saying why not, before anything changes on origin."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure):
return url
if forge_of(url) == "gh":
return Failure("--cut-patch merges the tag back fast-forward, which GitHub can't, since its rebase merge drops the merge commit: cut the patch by hand there")
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
return fetched
if isinstance(dropped := drop_unpushed_cut_tags(clone), Failure):
return dropped
ref = default_ref(cwd=clone)
if isinstance(ref, Failure):
return ref
base = newest_tag(clone, merged_into=ref)
if isinstance(base, Failure):
return base
cut = tagged(base)
if base is None or cut is None:
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
named = version((cut[0], cut[1], cut[2] + 1))
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
if version(release) != named:
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
picked = patch_commits(clone, ref, base, commits)
if isinstance(picked, Failure):
return picked
entries = changelog_entries(clone, ref, picked)
return entries if isinstance(entries, Failure) else Patch(ref, base, named, picked, entries)
def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | Failure:
"""The commits commits names, oldest first: merge commits, and the commits a merge brought into a range, are left out. A Failure where one is missing from ref or the tag base already holds it."""
listed = git("rev-list", "--reverse", "--no-merges", "--first-parent", commits if ".." in commits else f"{commits}^!", "--", cwd=clone)
if isinstance(listed, Failure):
return listed
picked = listed.split()
if not picked:
return Failure(f"{commits} names no commit that isn't a merge: write a range as <older>..<newer>")
for commit in picked:
if isinstance(git("merge-base", "--is-ancestor", commit, ref, cwd=clone), Failure):
return Failure(f"{commit[:12]} isn't on {ref}: merge it there first")
if not isinstance(git("merge-base", "--is-ancestor", commit, base, cwd=clone), Failure):
return Failure(f"{commit[:12]} is in {base} already")
return picked
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
added: set[str] = set()
for commit in commits:
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
if isinstance(diff, Failure):
return diff
added |= {line[1:] for line in diff.splitlines() if line.startswith("+- ")}
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
def tagged_entries(clone: str, patch: Patch) -> Failure | None:
"""A Failure unless the tag an earlier run pushed lists patch's entries under its version, so a rerun with other commits doesn't merge back entries the tag doesn't ship."""
changelog = git("show", f"v{patch.named}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
listed = [line for line in section(changelog, re.escape(patch.named)) or [] if line.strip()]
if listed != patch.entries:
return Failure(f"origin's v{patch.named} lists other changelog entries under ## {patch.named} than the commits named added under ## Unreleased. The tag lists:\n" + "\n".join(listed) + "\nThe commits added:\n" + "\n".join(patch.entries))
return None
def tag_patch(clone: str, patch: Patch) -> Failure | None:
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
with scratch_worktree(clone, patch.base) as worktree:
if isinstance(worktree, Failure):
return worktree
for commit in patch.commits:
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref), Failure):
return tested
said("ci.sh passed")
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
return made
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
return None
def headed(changelog: str, entries: list[str], named: str) -> str:
"""changelog with a ## named section holding entries before its first ## section, or at its end where it has none."""
added = f"## {named}\n\n" + "\n".join(entries) + "\n"
first = re.search(r"^## ", changelog, flags=re.M)
if first is None:
return changelog.rstrip() + "\n\n" + added
return changelog[:first.start()] + added + "\n" + changelog[first.start():]
def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) -> Failure | None:
"""Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the base tag's files differ from commit's parent."""
diff = git("diff", "--binary", f"{commit}^", commit, "--", ".", *(f":(exclude){path}" for path in LEFT_AS_TAGGED), cwd=clone)
if isinstance(diff, Failure):
return diff
if not diff:
return None
patch_file = worktree.parent / "commit.patch"
patch_file.write_text(diff)
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), cwd=str(worktree)), Failure):
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
return Failure(
f"{commit[:12]} ({'' if isinstance(subject, Failure) else subject.strip()}) doesn't apply on {patch.base}: {applied.reason}. "
f"Cut the patch by hand: on {patch.base}, apply the fix and add a ## {patch.named} section to CHANGELOG.md, commit that titled `Cut release {patch.named}`, "
f"tag it v{patch.named}, annotated with that title, and push the tag. A rerun with the same commits then merges it back and deploys it, "
f"where the section holds exactly these lines:\n" + "\n".join(patch.entries)
)
return None
def run_ci(worktree: pathlib.Path, ref: str) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
if not (worktree / "ci.sh").exists():
return Failure("the patch holds no ci.sh to test it with")
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
if ran.returncode == 0:
return None
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
return Failure(f"ci.sh failed on the patch, so nothing is tagged. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure | None:
"""On origin's main, merge the patch's tag keeping main's files, move its entries from ## Unreleased to a ## <version> section below ## Unreleased, and push that as the branch release-<version>, replacing the commit origin's branch points at, where there is one."""
with scratch_worktree(clone, patch.ref) as worktree:
if isinstance(worktree, Failure):
return worktree
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, f"release-{patch.named}", replacing)
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section."""
lines = changelog.split("\n")
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
kept = [line for line in lines[start + 1:end] if line not in entries]
while kept and not kept[-1].strip():
kept.pop()
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])
+3 -3
View File
@@ -6,10 +6,10 @@ 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."]
def create_pull(forge: Forge, branch: str, base: str, title: str, body: str, run: Run) -> Failure | None:
described = ["--body" if forge == "gh" else "--description", body]
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *described])
return created if isinstance(created, Failure) else None
+213 -2
View File
@@ -10,6 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from test_env import isolated_env
from deploy_release import patch
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
@@ -248,7 +249,7 @@ class Cut(unittest.TestCase):
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
self.clone = self.temp / "claude-config"
self.git(self.temp, "clone", "-q", str(self.origin), str(self.clone))
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Start")
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0"), "tool.txt": "broken\n", "ci.sh": "exit 0\n"}, "Start")
self.git(self.clone, "tag", "-a", "v0.1.0", "-m", "Cut release 0.1.0")
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0")}, "Ship item 1")
self.git(self.clone, "commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
@@ -469,7 +470,196 @@ class Cut(unittest.TestCase):
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
def test_takes_no_option_but_cut(self):
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
self.commit({"feature.txt": "new\n"}, "Add a feature")
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
base = self.git(self.clone, "rev-parse", "HEAD").strip()
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n", **(fix or {})}, "Fix item 3")
head = self.git(self.clone, "rev-parse", "HEAD").strip()
self.git(self.clone, "push", "-q", "origin", "main")
return f"{base}..{head}"
def cut_patch(self, *commits: str) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), "--cut-patch", *commits, str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
def test_cuts_a_patch_of_the_newest_tag_holding_only_the_named_commits_then_merges_the_tag_back_and_deploys_it(self):
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("cat-file", "-t", "v0.1.1").strip(), "tag", "the tag is annotated")
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.1.1").strip(), "Cut release 0.1.1")
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "v0.1.1").strip(), "Cut release 0.1.1")
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}~1"), self.origin_git("rev-parse", "v0.1.0^{commit}"))
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
self.assertEqual(self.origin_git("show", "v0.1.1:CHANGELOG.md"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(self.origin_git("show", "v0.1.1:todo.md"), self.origin_git("show", "v0.1.0:todo.md"))
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Merge release 0.1.1 into main")
self.assertEqual(self.origin_git("show", "main:CHANGELOG.md"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(self.origin_git("show", "main:feature.txt"), "new\n")
self.assertIn(["tea", "pulls", "create", "--head", "release-0.1.1", "--base", "main"], [call[:7] for call in self.forge_state()["calls"]])
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
self.assertIn("Done: v0.1.1 is cut and pushed", ran.stdout)
def test_takes_one_commit_as_the_patch(self):
head = self.plan_patch().split("..")[1]
ran = self.cut_patch(head)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
def test_refuses_before_any_change_where_the_plan_names_no_patch_release(self):
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix tool.txt")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("0.1.1", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
self.assertEqual(self.forge_state()["pulls"], [])
def test_refuses_before_any_change_while_the_patch_release_holds_an_item(self):
self.plan_patch()
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=4, release="0.1.1")}, "File item 4")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD~1")
self.assertEqual(ran.returncode, 1)
self.assertIn("still holds items", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_skips_the_release_review_a_patch_would_otherwise_wait_for(self):
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
self.git(self.clone, "push", "-q", "--force", "origin", "main")
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
def test_refuses_a_commit_the_tag_holds(self):
self.plan_patch()
ran = self.cut_patch("v0.1.0")
self.assertEqual(ran.returncode, 1)
self.assertIn(self.git(self.clone, "rev-parse", "v0.1.0^{commit}")[:12] + " is in v0.1.0 already", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_refuses_a_commit_origins_main_doesnt_hold(self):
self.plan_patch()
self.commit({"tool.txt": "local\n"}, "Unpushed")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn(self.git(self.clone, "rev-parse", "HEAD")[:12] + " isn't on origin/main", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_leaves_out_the_commits_a_merge_of_main_brought_into_the_chunk(self):
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
base = self.git(self.clone, "rev-parse", "HEAD").strip()
self.commit({"feature.txt": "new\n"}, "Add a feature")
self.git(self.clone, "switch", "-q", "-c", "chunk", base)
self.git(self.clone, "merge", "-q", "--no-ff", "-m", "Sync with main", "main")
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3")
head = self.git(self.clone, "rev-parse", "HEAD").strip()
self.git(self.clone, "switch", "-q", "main")
self.git(self.clone, "merge", "-q", "--ff-only", "chunk")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch(f"{base}..{head}")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
def test_says_which_commits_the_patch_ships_before_it_applies_them(self):
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("deploy-release: ships " + self.git(self.clone, "log", "-1", "--format=%h %s", "HEAD").strip(), ran.stderr)
self.assertNotIn("Add a feature", ran.stderr)
def test_refuses_on_a_github_origin_whose_merge_would_drop_the_tag_from_main(self):
commits = self.plan_patch()
self.use_github()
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 1)
self.assertIn("GitHub", ran.stderr)
self.assertEqual(self.forge_state()["calls"], [])
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_a_rerun_merges_back_and_deploys_a_patch_cut_by_hand_as_the_refusal_says(self):
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
commits = self.plan_patch()
refused = self.cut_patch(commits)
self.assertEqual(refused.returncode, 1)
self.assertIn("exactly these lines:\n- Fixed.", refused.stderr)
self.git(self.clone, "switch", "-q", "--detach", "v0.1.0")
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Cut release 0.1.1")
self.git(self.clone, "tag", "-a", "v0.1.1", "-m", "Cut release 0.1.1")
self.git(self.clone, "push", "-q", "origin", "v0.1.1")
self.git(self.clone, "switch", "-q", "main")
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
def test_a_rerun_refuses_a_pushed_tag_cut_from_other_commits(self):
self.set_checks("failure")
commits = self.plan_patch()
self.assertEqual(self.cut_patch(commits).returncode, 1)
self.commit({"tool.txt": "fixed twice\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n- Fixed twice.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3 again")
self.git(self.clone, "push", "-q", "origin", "main")
self.set_checks("success")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("The tag lists:\n- Fixed.\nThe commits added:\n- Fixed twice.", ran.stderr)
self.assertNotIn("Fixed twice", self.origin_git("show", "main:CHANGELOG.md").split("## 0.1.0")[0].split("## Unreleased")[0])
def test_refuses_commits_that_add_no_changelog_entry_under_unreleased(self):
self.plan_patch()
self.commit({"tool.txt": "fixed again\n"}, "Fix more")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("## Unreleased", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_stops_before_tagging_where_ci_fails_on_the_patch(self):
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite failed >&2\nexit 1\n"}))
self.assertEqual(ran.returncode, 1)
self.assertIn("ci.sh", ran.stderr)
self.assertIn("the suite failed", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.1.1"), "")
self.assertEqual(self.forge_state()["pulls"], [])
def test_stops_naming_the_commit_that_does_not_apply_on_the_tag(self):
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 1)
self.assertIn("Fix item 3", ran.stderr)
self.assertIn("v0.1.0", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_a_rerun_after_a_failed_merge_back_check_keeps_the_pushed_tag_and_merges_back(self):
self.set_checks("failure")
commits = self.plan_patch()
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 1)
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
self.set_checks("success")
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
def test_plain_cut_refuses_a_patch_release_and_names_cut_patch(self):
self.plan_patch()
ran = self.cut()
self.assertEqual(ran.returncode, 1)
self.assertIn("--cut-patch", ran.stderr)
self.assertEqual(self.forge_state()["pulls"], [])
def test_cut_patch_needs_its_commits(self):
ran = subprocess.run([sys.executable, str(TOOL), "--cut-patch"], capture_output=True, cwd=self.clone, env=self.env, text=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("usage", ran.stderr)
self.assertEqual(self.forge_state()["calls"], [])
def test_refuses_an_option_it_does_not_know(self):
ran = subprocess.run([sys.executable, str(TOOL), "--cut", "--force"], capture_output=True, cwd=self.clone, env=self.env, text=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("usage", ran.stderr)
@@ -488,5 +678,26 @@ class Cut(unittest.TestCase):
class PatchChangelog(unittest.TestCase):
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
def test_heads_the_tags_changelog_with_the_patchs_section(self):
self.assertEqual(patch.headed("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed.", "- Also."], "0.1.1"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n- Also.\n\n## 0.1.0\n\n- First.\n")
def test_appends_the_patchs_section_to_a_changelog_without_sections(self):
self.assertEqual(patch.headed("# Changelog\n\nFor Linux and macOS X\n\n", ["- Fixed."], "0.1.1"), "# Changelog\n\nFor Linux and macOS X\n\n## 0.1.1\n\n- Fixed.\n")
def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
def test_leaves_an_older_section_entry_that_reads_the_same(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
def test_puts_the_section_last_where_unreleased_is_the_last_section(self):
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
if __name__ == "__main__":
unittest.main()
+91 -1
View File
@@ -1,4 +1,4 @@
"""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 comments_on reads an issue's comments. Its assign, close, person_files, score and block change the tracker as a person or the plan store would."""
"""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 comments_on reads an issue's comments. Its assign, close, person_files, score and block change the tracker as a person or the plan store would. Its account is the display name of the account the store works as."""
import re
import typing
@@ -6,12 +6,19 @@ from do_epic.backend.protocol import EpicIssue, EpicStore
from failure import Failure
SCORES = {"L": 2, "E": 1, "I": 2, "S": 3}
class EpicStoreContract:
assertEqual: typing.Callable[..., None]
assertIn: typing.Callable[..., None]
assertIsInstance: typing.Callable[..., None]
assertIsNone: typing.Callable[..., None]
subTest: typing.Callable[..., typing.ContextManager[None]]
# The name of a transition the tracker offers an open issue, which leads to the done status "Done".
transition = "Done"
def new_store(self) -> EpicStore:
raise NotImplementedError
@@ -19,6 +26,9 @@ class EpicStoreContract:
"""Assigns the issue named key to the person whose display name is name."""
raise NotImplementedError
def account(self, store: EpicStore) -> str:
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
@@ -147,6 +157,23 @@ class EpicStoreContract:
self.assertIsInstance(store.add_label("ZZZ-1", "repo:log"), Failure)
self.assertEqual([issue.labels for issue in self.issues(store)], [(), ()])
def test_starts_an_issue_nobody_holds_as_its_own_account_and_answers_who_else_holds_one(self) -> None:
store = self.new_store()
free = self.filed(store, store.epic_key, "Count the runs.")
held = self.filed(store, store.epic_key, "Ship the later thing.")
task = self.filed(store, free, "Count them in the api.")
untouched = self.filed(store, store.epic_key, "Close the old thing.")
self.assign(store, held, "Ada Berg")
self.assertEqual([store.start_issue(free), store.start_issue(held), store.start_issue(task), store.start_issue(free)], [None, "Ada Berg", None, None])
self.assertEqual({issue.key: issue.assignee for issue in self.issues(store)}, {free: self.account(store), held: "Ada Berg", task: self.account(store), untouched: None})
def test_refuses_to_start_an_issue_outside_the_epic(self) -> None:
store = self.new_store()
self.filed(store, store.epic_key, "Count the runs.")
self.assertIsInstance(store.start_issue("ZZZ-1"), Failure)
self.assertIsInstance(store.start_issue("not a key"), Failure)
self.assertEqual([issue.assignee for issue in self.issues(store)], [None])
def test_finishes_a_child_issue_so_it_reads_as_done_and_leaves_one_that_is_done_as_it_is(self) -> None:
store = self.new_store()
key = self.filed(store, store.epic_key, "Count the runs.")
@@ -156,6 +183,38 @@ class EpicStoreContract:
self.assertEqual([store.finish_issue(key), store.finish_issue(closed)], [None, None])
self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {key: True, other: False, closed: True})
def test_moves_a_child_issue_or_a_sub_task_to_the_status_named_and_leaves_one_already_there(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.move_issue(task, "Done"), store.move_issue(task, "done")], [None, None])
self.assertEqual({issue.key: issue.status for issue in self.issues(store)}, {child: "To Do", task: "Done"})
def test_refuses_to_move_an_issue_outside_the_epic(self) -> None:
store = self.new_store()
self.filed(store, store.epic_key, "Count the runs.")
self.assertIsInstance(store.move_issue("ZZZ-1", "Done"), Failure)
self.assertEqual([issue.status for issue in self.issues(store)], ["To Do"])
def test_moves_a_child_issue_or_a_sub_task_by_the_transition_named_and_answers_the_status_it_leads_to(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.move_issue_by(task, self.transition, ("Done",)), store.move_issue_by(child, self.transition, ("Done",))], ["Done", "Done"])
self.assertEqual({issue.key: (issue.status, issue.done) for issue in self.issues(store)}, {child: ("Done", True), task: ("Done", True)})
def test_leaves_an_issue_already_at_a_status_asked_for_where_it_is(self) -> None:
store = self.new_store()
child = self.filed(store, store.epic_key, "Count the runs.")
self.assertEqual(store.move_issue_by(child, self.transition, ("Done",)), "Done")
self.assertEqual(store.move_issue_by(child, "Release Ready", ("done",)), "Done")
def test_refuses_to_move_an_issue_outside_the_epic_by_a_transition(self) -> None:
store = self.new_store()
self.filed(store, store.epic_key, "Count the runs.")
self.assertIsInstance(store.move_issue_by("ZZZ-1", self.transition, ("Done",)), Failure)
self.assertEqual([issue.status for issue in self.issues(store)], ["To Do"])
def test_finishes_a_sub_task_of_a_child_issue_and_leaves_its_parent_open(self) -> None:
store = self.new_store()
child = self.filed(store, store.epic_key, "Count the runs.")
@@ -207,6 +266,37 @@ class EpicStoreContract:
[issue] = self.issues(store)
self.assertEqual((issue.scores, issue.moves, issue.exempt), ({"L": 2, "E": 3, "I": 4, "S": 3}, (("1", 5),), "security"))
def test_sets_the_scores_of_a_persons_issue_and_of_a_sub_task_and_tells_the_team(self) -> None:
store = self.new_store()
key = self.person_files(store, "Count the runs.")
task = self.filed(store, key, "Count them in the API.")
self.assertEqual([store.set_scores(key, SCORES, "epic 1 by 5, repo 2 by 3", "Scored: it moves the import."), store.set_scores(task, SCORES, "", "Scored.")], [None, None])
child, sub = self.issues(store)
self.assertEqual((child.scores, child.moves, child.by_loop, sub.scores, sub.moves, sub.by_loop), (SCORES, (("epic 1", 5), ("repo 2", 3)), False, SCORES, (), True))
self.assertEqual((self.comments_on(store, key), self.comments_on(store, task)), (["Scored: it moves the import."], ["Scored."]))
def test_an_issue_that_holds_scores_keeps_them_and_gets_no_comment(self) -> None:
store = self.new_store()
key = self.filed(store, store.epic_key, "Count the runs.")
self.score(store, key, {"L": 2, "E": 3, "I": 4, "S": 3, "Moves": "1 by 5"})
refused = store.set_scores(key, SCORES, "", "Scored.")
assert isinstance(refused, Failure)
self.assertIn(f"{key} holds scores already", refused.reason)
[issue] = self.issues(store)
self.assertEqual((issue.scores, issue.moves, self.comments_on(store, key)), ({"L": 2, "E": 3, "I": 4, "S": 3}, (("1", 5),), []))
def test_refuses_scores_outside_the_epic_out_of_range_or_incomplete_or_without_a_comment(self) -> None:
store = self.new_store()
key = self.filed(store, store.epic_key, "Count the runs.")
refusals = [store.set_scores("ZZZ-1", SCORES, "", "Scored."), store.set_scores("not a key", SCORES, "", "Scored."), store.set_scores(key, SCORES | {"L": 9}, "", "Scored."), store.set_scores(key, {"L": 1}, "", "Scored."), store.set_scores(key, SCORES | {"R": 1}, "", "Scored."), store.set_scores(key, SCORES, "the import by 5", "Scored."), store.set_scores(key, SCORES, "", " \n")]
for refused in refusals:
self.assertIsInstance(refused, Failure)
self.assertEqual(refusals[1], Failure(f"not a key is not one of the child issues of the epic {store.epic_key}, so it cannot be scored"))
assert isinstance(refusals[3], Failure)
self.assertEqual(refusals[3].reason[refusals[3].reason.rindex(key):], f"{key} is given L: set each of L, E, I and S, and nothing else")
[issue] = self.issues(store)
self.assertEqual((issue.scores, self.comments_on(store, key)), ({}, []))
def test_reads_each_blocker_of_an_issue_and_none_for_a_blocker_of_another(self) -> None:
store = self.new_store()
first, second, third = (self.filed(store, store.epic_key, f"Item {n}.") for n in range(3))
+74 -6
View File
@@ -1,18 +1,21 @@
"""An epic held in memory, for do-epic's tests, held to contract.py like every backend."""
"""An epic held in memory, for do-epic's tests and its `--dry-run`, held to contract.py like every backend."""
import dataclasses
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_words, unfit, unfit_label
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
from failure import Failure
@dataclasses.dataclass
class MemoryEpic:
"""An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank, issue finish and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed."""
"""An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank, scoring, issue start, issue finish and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed. writes says each write that succeeded, in order."""
epic_key: str
issues: list[EpicIssue] = dataclasses.field(default_factory=list)
comments: dict[str, list[str]] = dataclasses.field(default_factory=dict)
fails: str | None = None
done: bool = False
writes: list[str] = dataclasses.field(default_factory=list)
# The display name of the account the epic's issues are started as.
account: str = "do-epic"
def read(self) -> list[EpicIssue] | Failure:
if self.fails:
@@ -29,10 +32,15 @@ class MemoryEpic:
return no_parent(self.epic_key, parent)
if blocked_by is not None and blocked_by not in {issue.key for issue in self.issues if issue.parent == self.epic_key or issue.parent in children}:
return no_blocker(self.epic_key, blocked_by)
key = f"{self.epic_key.rpartition('-')[0]}-{len(self.issues) + 100}"
key = self.next_key()
self.issues.append(EpicIssue(key, summary, detail.strip(), tuple(sorted(labels)), None, "To Do", False, parent, blockers=(blocked_by,) if blocked_by else (), by_loop=True))
self.writes.append(f"file {key} under {parent}: {summary}" + (f", labelled {', '.join(sorted(labels))}" if labels else "") + (f", blocked by {blocked_by}" if blocked_by else ""))
return key
def next_key(self) -> str:
"""The key of the next issue filed."""
return f"{self.epic_key.rpartition('-')[0]}-{len(self.issues) + 100}"
def add_label(self, key: str, label: str) -> None | Failure:
if self.fails:
return Failure(self.fails)
@@ -42,6 +50,7 @@ class MemoryEpic:
if child is None:
return no_child(self.epic_key, key, "labelled")
self.change(key, labels=tuple(sorted({*child.labels, label})))
self.writes.append(f"label {key} with {label}")
return None
def rank(self, key: str, before: str) -> None | Failure:
@@ -52,6 +61,7 @@ class MemoryEpic:
return Failure(f"{stray} is not one of the child issues of the epic {self.epic_key}, so {key} is not ranked")
self.issues.remove(children[key])
self.issues.insert(self.issues.index(children[before]), children[key])
self.writes.append(f"rank {key} before {before}")
return None
def comment(self, key: str, text: str) -> None | Failure:
@@ -62,6 +72,7 @@ class MemoryEpic:
if not any(issue.key == key and issue.parent == self.epic_key for issue in self.issues):
return no_child(self.epic_key, key, "commented on")
self.comments.setdefault(key, []).append(text.strip())
self.writes.append(f"comment on {key}: {text.strip()}")
return None
def closed(self) -> bool | Failure:
@@ -74,19 +85,76 @@ class MemoryEpic:
return refused
self.comments.setdefault(self.epic_key, []).append(summary.strip())
self.done = True
self.writes.append(f"close the epic: {summary.strip()}")
return None
def set_scores(self, key: str, scores: dict[str, int], moves: str, comment: str) -> None | Failure:
if self.fails:
return Failure(self.fails)
if refused := no_words(comment):
return refused
child = self.within(key)
if child is None:
return no_child(self.epic_key, key, "scored")
fields = no_scores(key, scores, moves, child.scores)
if isinstance(fields, Failure):
return fields
self.change(key, scores=fields.scores, moves=fields.moves)
self.comments.setdefault(key, []).append(comment.strip())
self.writes.append(f"score {key} {', '.join(f'{name} {value}' for name, value in scores.items())}, Moves {moves or 'none'}, with the comment: {comment.strip()}")
return None
def start_issue(self, key: str) -> str | None | Failure:
if self.fails:
return Failure(self.fails)
child = self.within(key)
if child is None:
return no_child(self.epic_key, key, "started")
self.writes.append(f"start {key}")
if child.assignee is None:
self.change(key, assignee=self.account)
return None if child.assignee in (None, self.account) else child.assignee
def move_issue(self, key: str, status: str) -> None | Failure:
if self.fails:
return Failure(self.fails)
child = self.within(key)
if child is None:
return no_child(self.epic_key, key, "moved")
if child.status.casefold() != status.casefold():
self.change(key, status=status, done=status.casefold() == "done")
self.writes.append(f"move {key} to {status}")
return None
def move_issue_by(self, key: str, transition: str, to: tuple[str, ...]) -> str | Failure:
# The fake holds no workflow, so it cannot tell where a transition leads: each leads to the first status asked for.
if self.fails:
return Failure(self.fails)
issue = self.within(key)
if issue is None:
return no_child(self.epic_key, key, "moved")
if issue.status.casefold() in {name.casefold() for name in to}:
return issue.status
self.change(key, status=to[0], done=to[0].casefold() == "done")
self.writes.append(f"move {key} by {transition}")
return to[0]
def finish_issue(self, key: str) -> None | Failure:
if self.fails:
return Failure(self.fails)
children = {issue.key for issue in self.issues if issue.parent == self.epic_key}
child = next((issue for issue in self.issues if issue.key == key and (issue.parent == self.epic_key or issue.parent in children)), None)
child = self.within(key)
if child is None:
return no_child(self.epic_key, key, "finished")
if not child.done:
self.change(key, status="Done", done=True)
self.writes.append(f"finish {key}")
return None
def within(self, key: str) -> EpicIssue | None:
"""The epic's child issue named key, or the sub-task of one; None where the epic holds neither."""
children = {issue.key for issue in self.issues if issue.parent == self.epic_key}
return next((issue for issue in self.issues if issue.key == key and (issue.parent == self.epic_key or issue.parent in children)), None)
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]
+110 -24
View File
@@ -5,11 +5,15 @@ 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 plan_store.jira_epic import BLOCKS, FILED_BY, ISSUE_TYPE, PROPERTY, scores
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_words, unfit, unfit_label
from plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY
from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE
from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
from failure import Failure
from do_epic.backend.jira_status import moved_by, moved_to
from plan.todo_table import MOVES
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.jira_start import Start, started
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"]
# How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes.
@@ -35,6 +39,10 @@ class JiraEpic:
finish: Finish | None = None
# The pages a search may take before the read fails.
max_pages: int = MAX_PAGES
# The issue types that a finding, and a release review (an issue labelled REVIEW_LABEL), are filed as.
finding_type: str = DEFAULT_ISSUE_TYPE
review_type: str = DEFAULT_ISSUE_TYPE
start: Start = Start()
@property
def epic_key(self) -> str:
@@ -66,7 +74,7 @@ class JiraEpic:
fields: dict[str, typing.Any] = {"project": {"key": project_of(parent)}, "parent": {"key": parent}, "summary": summary, "labels": list(labels)}
# Marks the issue as the loop's, as plan_store marks the items it files.
properties = [{"key": PROPERTY, "value": {FILED_BY[0]: FILED_BY[1]}}]
kind = {"name": ISSUE_TYPE} if parent == self.epic_key else self.sub_task_type(project_of(parent), authorization)
kind = self.child_type(project_of(parent), REVIEW_LABEL in labels, authorization) if parent == self.epic_key else self.sub_task_type(project_of(parent), authorization)
if isinstance(kind, Failure):
return kind
if detail.strip():
@@ -157,21 +165,71 @@ class JiraEpic:
refused_move = move_refusal(self.epic.site, self.epic_key, transition, self.finish, authorization, self.http)
return Failure(f"posted the summary on {self.epic_key}, but {refused_move}; close the epic in Jira rather than posting the summary again") if refused_move else None
def set_scores(self, key: str, scores: dict[str, int], moves: str, comment: str) -> None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
if refused := no_words(comment):
return refused
if not ISSUE_KEY.fullmatch(key):
return no_child(self.epic_key, key, "scored")
answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=parent&properties={PROPERTY}", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {key} to score it: {answered.reason}")
found = held_of(key, answered)
if isinstance(found, Failure):
return found
above, held = found
# A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too.
grand = self.parent_of(above, authorization, "to score its sub-task") if above not in (None, self.epic_key) else None
if isinstance(grand, Failure):
return grand
if above is None or (above != self.epic_key and grand != self.epic_key):
return no_child(self.epic_key, key, "scored")
read = held_scores(key, held)
fields = read if isinstance(read, Failure) else no_scores(key, scores, moves, read.scores)
body = fields if isinstance(fields, Failure) else self.to_adf(comment)
if isinstance(body, Failure):
return Failure(f"cannot score {key}: {body.reason}")
# The comment goes first: an issue that holds scores is never scored again, so scores set without it would leave the team untold for good.
posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body})
if isinstance(posted, Failure):
return Failure(f"cannot comment on {key} to tell its team the scores: {posted.reason}")
put = edit_issue(self.epic.site, key, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]}, authorization, self.http)
return Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: {put.reason}") if isinstance(put, Failure) else None
def start_issue(self, key: str) -> str | None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
within = self.within(key, authorization, "start", "started")
if isinstance(within, Failure):
return within
# Jira keeps a sub-task in its parent's sprint, so the parent joins the sprint in its place.
return started(self.epic.site, key, key if within[0] == self.epic_key else within[0], self.start, authorization, self.http)
def move_issue(self, key: str, status: str) -> None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
within = self.within(key, authorization, "move", "moved")
return within if isinstance(within, Failure) else moved_to(self.epic.site, key, status, authorization, self.http)
def move_issue_by(self, key: str, transition: str, to: tuple[str, ...]) -> str | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
within = self.within(key, authorization, "move", "moved")
return within if isinstance(within, Failure) else moved_by(self.epic.site, key, transition, to, authorization, self.http)
def finish_issue(self, key: str) -> None | Failure:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
placed = self.placed(key, authorization, "to finish it")
if isinstance(placed, Failure):
return placed
above, done = placed
# A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too.
grand = self.parent_of(above, authorization, "to finish its sub-task") if above not in (None, self.epic_key) else None
if isinstance(grand, Failure):
return grand
if above is None or (above != self.epic_key and grand != self.epic_key):
return no_child(self.epic_key, key, "finished")
if done:
within = self.within(key, authorization, "finish", "finished")
if isinstance(within, Failure):
return within
if within[1]:
return None
if self.finish is None:
return Failure(NO_FINISH.format(to="finish an issue", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS))
@@ -181,6 +239,20 @@ class JiraEpic:
refused = move_refusal(self.epic.site, key, transition, self.finish, authorization, self.http)
return Failure(f"{refused}; {PERHAPS_MOVED.format(key=key)}") if refused else None
def within(self, key: str, authorization: str, do: str, done_to_it: str) -> tuple[str, bool] | Failure:
"""The key of key's parent and whether key's status is a done one, where key names a child issue of the epic or a sub-task of one; any other key is refused. do and done_to_it say what was asked of key, such as "finish" and "finished"."""
placed = self.placed(key, authorization, f"to {do} it")
if isinstance(placed, Failure):
return placed
above, done = placed
# A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too.
grand = self.parent_of(above, authorization, f"to {do} its sub-task") if above not in (None, self.epic_key) else None
if isinstance(grand, Failure):
return grand
if above is None or (above != self.epic_key and grand != self.epic_key):
return no_child(self.epic_key, key, done_to_it)
return above, done
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:
@@ -244,18 +316,32 @@ class JiraEpic:
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 child_type(self, project: str, review: bool, authorization: str) -> dict[str, str] | Failure:
"""The issue type of a new child of the epic, which is the type of a release review where review is true, else of a finding; or why the project can't file that type."""
name = self.review_type if review else self.finding_type
refused = issue_type_refusal(self.epic.site, project, name, JIRA_REVIEW_TYPE if review else JIRA_FINDING_TYPE, authorization, self.http)
return Failure(refused) if refused else {"name": name}
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)
types = issue_types_of(self.epic.site, project, authorization, self.http)
if isinstance(types, Failure):
return types
found = next((kind["id"] for kind in types if 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 held_of(key: str, answered: object) -> tuple[str | None, dict[str, typing.Any]] | Failure:
"""The key of the parent, None where it has none, and the value of PROPERTY, empty where it holds none, in Jira's answer for the issue named key."""
fields = answered.get("fields") if isinstance(answered, dict) else None
properties = answered.get("properties") if isinstance(answered, dict) else None
above = fields.get("parent") if isinstance(fields, dict) else None
held = properties.get(PROPERTY, {}) if isinstance(properties, dict) else {}
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
return (above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None), held
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."""
entry = entry_of(raw, PROPERTY)
@@ -274,7 +360,7 @@ def found_of(raw: object) -> Found | Failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value")
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
read = scores(key, held)
read = held_scores(key, held)
if isinstance(read, Failure):
return read
return Found(EpicIssue(key, summary.strip(), "", tuple(sorted(labels)), name, state, done, parent, read.scores, read.moves, read.exempt, blockers, held.get(FILED_BY[0]) == FILED_BY[1]), description)
+99
View File
@@ -0,0 +1,99 @@
"""How a Jira issue shows its team that its work is under way: assigned, moved by the team's start transition and in a board's active sprint."""
import dataclasses
import typing
from failure import Failure
from atlassian.client import Http
from atlassian.jira import offers_of, unshaped
# Three readers, seated as those who write and read do-epic's config, picked both spellings from four candidates each, 3-0. `jira-start-transition` pairs with `jira-finish-transition`. `jira-board`, a candidate they turned down, reads as the board do-epic takes its issues from.
START_TRANSITION = "jira-start-transition"
SPRINT_BOARD = "jira-sprint-board"
# The key of the category Jira gives each status at which an issue's work hasn't started.
NEW = "new"
@dataclasses.dataclass(frozen=True)
class Start:
"""What the machine's settings give a starting issue beside its assignee: transition names the workflow transition that moves it, and sprint_board is the ID of the board whose active sprint it joins. Each is None where the settings don't name it."""
transition: str | None = None
sprint_board: int | None = None
@dataclasses.dataclass(frozen=True)
class Held:
"""What Jira answers about an issue before it starts. holder is its assignee's account ID and display name; None where nobody is assigned."""
holder: tuple[str, str] | None
status: str
category: str
def started(site: str, key: str, sprint_key: str, start: Start, authorization: str, http: Http) -> str | None | Failure:
"""Starts the issue named key, where sprint_key is the issue a sprint takes for it: the issue itself, or the parent of a sub-task. The answer is the display name of someone else who holds the issue, else None. A Failure names each step Jira did not take, and that someone else who holds the issue."""
held = held_of(site, key, authorization, http)
if isinstance(held, Failure):
return held
other = assigned(site, key, held, authorization, http)
# A status in any later category, such as Code Review, is past the start transition, so the issue keeps it.
moved = start_refusal(site, key, held.status, start.transition, authorization, http) if start.transition and held.category == NEW else None
joined = sprint_refusal(site, sprint_key, start.sprint_board, authorization, http) if start.sprint_board is not None else None
refused = [step.reason for step in (other, moved, joined) if isinstance(step, Failure)]
if not refused:
return other
return Failure("; ".join(refused) + (f"; {key} stays assigned to {other}" if isinstance(other, str) else ""))
def held_of(site: str, key: str, authorization: str, http: Http) -> Held | Failure:
answered: typing.Any = http("GET", f"{site}/rest/api/3/issue/{key}?fields=assignee,status", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {key} to start it: {answered.reason}")
try:
assignee, status = answered["fields"]["assignee"], answered["fields"]["status"]
return Held(None if assignee is None else (str(assignee["accountId"]), str(assignee["displayName"])), str(status["name"]), str(status["statusCategory"]["key"]))
except (KeyError, TypeError) as failure:
return Failure(unshaped(key, failure))
def assigned(site: str, key: str, held: Held, authorization: str, http: Http) -> str | None | Failure:
"""Assigns the issue named key to the account authorization names, unless someone holds it. The display name of someone else who holds it, else None."""
me = http("GET", f"{site}/rest/api/3/myself", authorization, None)
if isinstance(me, Failure):
return Failure(f"cannot read which account do-epic works as, to assign {key}: {me.reason}")
account = me.get("accountId") if isinstance(me, dict) else None
if not isinstance(account, str):
return Failure(f"cannot assign {key}: Jira named no account ID for the account do-epic works as")
if held.holder is not None:
return None if held.holder[0] == account else held.holder[1]
put = http("PUT", f"{site}/rest/api/3/issue/{key}/assignee", authorization, {"accountId": account})
return Failure(f"cannot assign {key}: {put.reason}") if isinstance(put, Failure) else None
def start_refusal(site: str, key: str, status: str, transition: str, authorization: str, http: Http) -> Failure | None:
"""Moves the issue named key, which has the status named status, by the transition named transition. Why Jira did not take the move; None where it did."""
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
offers = offers_of(offered, key)
if isinstance(offers, Failure):
return offers
named = [id_ for id_, name, _, _ in offers if name == transition]
if not named:
others = " and ".join(f"{name!r} to {to!r}" for _, name, to, _ in offers)
return Failure(f"{key} has no transition {transition!r} from its status {status!r}, " + (f"only {others}: set `{START_TRANSITION}` to a transition the issue has before its work starts" if offers else "nor any other the account may make"))
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": named[0]}})
return Failure(f"cannot move {key} by {transition!r}: {moved.reason}") if isinstance(moved, Failure) else None
def sprint_refusal(site: str, key: str, board: int, authorization: str, http: Http) -> Failure | None:
"""Adds the issue named key to the one active sprint of the board with the ID board. Why it didn't join one; None where it joined."""
answered = http("GET", f"{site}/rest/agile/1.0/board/{board}/sprint?state=active", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read the active sprint of board {board}, which `{SPRINT_BOARD}` names: {answered.reason}")
values = answered.get("values") if isinstance(answered, dict) else None
sprints = [each["id"] for each in values if isinstance(each, dict) and isinstance(each.get("id"), int)] if isinstance(values, list) else []
if not isinstance(values, list) or len(sprints) != len(values):
return Failure(f"Jira answered board {board}'s sprints in a shape other than the one it documents")
if len(sprints) != 1:
return Failure(f"board {board}, which `{SPRINT_BOARD}` names, has {f"{len(sprints)} active sprints" if sprints else "no active sprint"}, so {key} doesn't join a sprint")
added = http("POST", f"{site}/rest/agile/1.0/sprint/{sprints[0]}/issue", authorization, {"issues": [key]})
return Failure(f"cannot add {key} to the active sprint of board {board}: {added.reason}") if isinstance(added, Failure) else None
+60
View File
@@ -0,0 +1,60 @@
"""Moves a Jira issue to a named status, or through a named transition, for a team whose own automation doesn't see the move's cause, such as a pull request into an epic's working branch."""
import typing
from failure import Failure
from atlassian.client import Http
from atlassian.jira import offers_of, unshaped
def status_of(site: str, key: str, authorization: str, http: Http) -> str | Failure:
"""The name of the status the issue named key has now, read from the issue itself, since a search may lag behind a move."""
answered: typing.Any = http("GET", f"{site}/rest/api/3/issue/{key}?fields=status", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {key} to move it: {answered.reason}")
try:
return str(answered["fields"]["status"]["name"])
except (KeyError, TypeError) as failure:
return Failure(unshaped(key, failure))
def moved_to(site: str, key: str, status: str, authorization: str, http: Http) -> Failure | None:
"""Moves the issue named key to the status named status, in upper or lower case, by the first transition to that status the issue's workflow offers. An issue already there stays as it is. Why Jira did not take the move; None where the issue has the status."""
now = status_of(site, key, authorization, http)
if isinstance(now, Failure):
return now
if now.casefold() == status.casefold():
return None
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
offers = offers_of(offered, key)
if isinstance(offers, Failure):
return offers
leading = [id_ for id_, _, to, _ in offers if to.casefold() == status.casefold()]
if not leading:
others = " and ".join(f"{name!r} to {to!r}" for _, name, to, _ in offers)
return Failure(f"{key} has no transition to the status {status!r} from its status {now!r}, " + (f"only {others}" if offers else "nor any other the account may make"))
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": leading[0]}})
return Failure(f"cannot move {key} to {status!r}: {moved.reason}") if isinstance(moved, Failure) else None
def moved_by(site: str, key: str, transition: str, to: tuple[str, ...], authorization: str, http: Http) -> str | Failure:
"""Moves the issue named key by the transition named transition, where that transition leads to one of the statuses to. Names match in upper or lower case. An issue already at one of those statuses stays as it is. The name of the status the issue has afterwards; why the move was not made."""
accepted = {name.casefold() for name in to}
now = status_of(site, key, authorization, http)
if isinstance(now, Failure) or now.casefold() in accepted:
return now
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
offers = offers_of(offered, key)
if isinstance(offers, Failure):
return offers
named = [(id_, to) for id_, name, to, _ in offers if name.casefold() == transition.casefold()]
if not named:
others = " and ".join(f"{name!r} to {to!r}" for _, name, to, _ in offers)
return Failure(f"{key} has no transition {transition!r} from its status {now!r}, " + (f"only {others}" if offers else "nor any other the account may make"))
if named and named[0][1].casefold() not in accepted:
return Failure(f"the transition {transition!r} leads {key} to the status {named[0][1]!r}, not to {' or '.join(repr(name) for name in to)}")
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": named[0][0]}})
return Failure(f"cannot move {key} by {transition!r}: {moved.reason}") if isinstance(moved, Failure) else named[0][1]
+23 -1
View File
@@ -5,8 +5,9 @@ import dataclasses
import re
import typing
from plan.todo_table import Exempt, Moves
from plan.todo_table import Exempt, item_fields, ItemFields, Moves, MOVES
from failure import Failure
from plan_store.jira_epic import SET_SCORES
# What a tracker accepts as a label: Jira refuses a label holding white space.
LABEL = re.compile(r"\S+")
@@ -63,6 +64,18 @@ class EpicStore(typing.Protocol):
def comment(self, key: str, text: str) -> None | Failure:
"""Posts text, markdown, as a comment on the epic's child issue named key, for the people who work the epic to read. A sub-task, an issue outside the epic, or an empty or blank text is refused."""
def set_scores(self, key: str, scores: dict[str, int], moves: str, comment: str) -> None | Failure:
"""Posts comment, markdown, on the epic's child issue named key, or on a sub-task of one, then sets its scores. The comment tells the team the scores, since a tracker's screens may not show them. scores holds each of L, E, I and S, and moves is the plan's Moves cell, which may be empty. An issue that holds a score keeps what it holds and is refused, as are an issue outside the epic and a blank comment. Where the scores cannot be set after the comment is posted, the Failure says so."""
def start_issue(self, key: str) -> str | None | Failure:
"""Shows the team that the epic's child issue named key, or a sub-task of one, is being worked. It assigns an issue nobody holds to the account the store works as. An issue someone else holds stays theirs, and the answer is their display name; otherwise the answer is None. Where the backend's settings say so, it also moves an issue whose work hasn't started, and adds every starting issue to a sprint, whoever holds it. An issue outside the epic is refused. A Failure names each step that could not be made, and anyone else who holds the issue; the steps the tracker took stay taken."""
def move_issue(self, key: str, status: str) -> None | Failure:
"""Moves the epic's child issue named key, or a sub-task of one, to the status named status, in upper or lower case; one already there stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made, such as a workflow that gives no way from the issue's status to that one."""
def move_issue_by(self, key: str, transition: str, to: tuple[str, ...]) -> str | Failure:
"""Moves the epic's child issue named key, or a sub-task of one, by the workflow transition named transition, where that transition leads to one of the statuses to. Names match in upper or lower case. An issue already at one of those statuses stays as it is. Answers the name of the status the issue has afterwards. An issue outside the epic is refused. A Failure says why the move was not made, such as a workflow that offers the issue no transition of that name from its status, or a transition that leads to another status."""
def finish_issue(self, key: str) -> None | Failure:
"""Moves the epic's child issue named key, or a sub-task of one, to a done status, so that read answers it as done; one already done stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made: the issue's workflow gives no way to a done status, gives several the backend cannot choose between, or refuses the move."""
@@ -103,6 +116,15 @@ def no_child(epic_key: str, key: str, done_to_it: str) -> Failure:
return Failure(f"{key} is not one of the child issues of the epic {epic_key}, so it cannot be {done_to_it}")
def no_scores(key: str, scores: dict[str, int], moves: str, held: dict[str, int]) -> ItemFields | Failure:
"""The scores and Moves to set on the issue named key, each held to the plan's format, or why no tracker sets them; held are the scores the issue has."""
if held:
return Failure(f"{key} holds scores already, which stay as they are")
if sorted(scores) != sorted(SET_SCORES):
return Failure(f"{key} is given {', '.join(scores) or 'no score'}: set each of {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}, and nothing else")
return item_fields({name: str(value) for name, value in scores.items()} | {MOVES: moves}, f"item {key}")
def no_words(text: str) -> Failure | None:
"""Why no tracker can post this comment; None where one can."""
return None if text.strip() else Failure("the comment must hold some text")
+19
View File
@@ -18,6 +18,9 @@ class MemoryEpicContract(EpicStoreContract, unittest.TestCase):
def assign(self, store: MemoryEpic, key: str, name: str) -> None: # type: ignore[override]
store.change(key, assignee=name)
def account(self, store: MemoryEpic) -> str: # type: ignore[override]
return store.account
def comments_on(self, store: MemoryEpic, key: str) -> list[str]: # type: ignore[override]
return store.comments.get(key, [])
@@ -44,6 +47,22 @@ class Failing(unittest.TestCase):
down = Failure("Jira is down")
self.assertEqual((store.read(), store.file("ABC-12", "Count the runs.", "", ()), store.add_label("ABC-100", "api"), store.comment("ABC-100", "Hello."), store.rank("ABC-100", "ABC-101")), (down,) * 5)
def test_a_start_fails_with_the_reason_given_and_one_outside_the_epic_says_so(self) -> None:
self.assertEqual(MemoryEpic("ABC-12", fails="Jira is down").start_issue("ABC-100"), Failure("Jira is down"))
self.assertEqual(MemoryEpic("ABC-12").start_issue("ABC-100"), Failure("ABC-100 is not one of the child issues of the epic ABC-12, so it cannot be started"))
def test_a_move_fails_with_the_reason_given_and_one_outside_the_epic_says_so(self) -> None:
self.assertEqual(MemoryEpic("ABC-12", fails="Jira is down").move_issue("ABC-100", "Done"), Failure("Jira is down"))
self.assertEqual(MemoryEpic("ABC-12").move_issue("ABC-100", "Done"), Failure("ABC-100 is not one of the child issues of the epic ABC-12, so it cannot be moved"))
class Moving(unittest.TestCase):
def test_an_issue_moved_to_done_in_any_case_reads_as_done_and_one_moved_elsewhere_as_open(self) -> None:
store = MemoryEpic("ABC-12")
done, review = store.file("ABC-12", "Count the runs.", "", ()), store.file("ABC-12", "Ship the later thing.", "", ())
self.assertEqual([store.move_issue(done, "DONE"), store.move_issue(review, "Code Review")], [None, None])
self.assertEqual({issue.key: (issue.status, issue.done) for issue in store.issues}, {done: ("DONE", True), review: ("Code Review", False)})
class Blocking(unittest.TestCase):
def test_refuses_a_blocker_that_is_an_issue_of_another_epic(self) -> None:
+302 -8
View File
@@ -13,6 +13,8 @@ from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from do_epic.backend.jira import JiraEpic
from adf_codec.convert import Refused
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.jira_start import Start
SITE = "https://acme.atlassian.net"
EPIC = Epic(SITE, "ABC-12")
@@ -24,10 +26,15 @@ ISSUES = f"{SITE}/rest/api/3/issue"
RANK = f"{SITE}/rest/agile/1.0/issue/rank"
TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}}
DONE = {"name": "Done", "statusCategory": {"key": "done"}}
IN_PROGRESS = {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}
MYSELF = f"{SITE}/rest/api/3/myself"
ME = {"accountId": "712020:do-epic", "displayName": "Do Epic"}
ACTIVE_SPRINTS = f"{SITE}/rest/agile/1.0/board/6/sprint?state=active"
SPRINT_ISSUES = f"{SITE}/rest/agile/1.0/sprint/77/issue"
TRANSITIONS = f"{ISSUES}/ABC-12/transitions"
EPIC_COMMENT = f"{ISSUES}/ABC-12/comment"
EPIC_STATUS = f"{ISSUES}/ABC-12?fields=status"
TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]}
TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10002", "name": "Feature", "subtask": False}, {"id": "10004", "name": "Chore", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]}
def to_adf(markdown: str) -> dict[str, object]:
@@ -46,12 +53,17 @@ class FakeJira:
answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict)
calls: list[tuple[str, str]] = dataclasses.field(default_factory=list)
comments: dict[str, list[object]] = dataclasses.field(default_factory=dict)
# The issue type of each issue created, as the request names it.
filed_as: list[object] = dataclasses.field(default_factory=list)
# The ID of each transition made.
transitioned: list[str] = dataclasses.field(default_factory=list)
# The transitions Jira offers an issue that isn't done.
workflow: list[dict[str, object]] = dataclasses.field(default_factory=lambda: [{"id": "31", "name": "Mark as done", "to": DONE}])
# The epic's own status, which the transition "Mark as done" moves to DONE.
epic_status: dict[str, object] = dataclasses.field(default_factory=lambda: dict(TO_DO))
# The active sprints of board 6, and the issues each request added to sprint 77.
sprints: list[object] = dataclasses.field(default_factory=lambda: [{"id": 77, "name": "Sprint 9", "state": "active"}])
sprinted: list[object] = dataclasses.field(default_factory=list)
def __call__(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url))
@@ -78,15 +90,27 @@ class FakeJira:
if method == "POST" and url == SEARCH:
return self.page(body)
if method == "GET" and (held := next((issue for issue in self.issues if url.startswith(f"{ISSUES}/{issue['key']}?fields=")), None)):
asked = url.partition("?fields=")[2].split(",")
return {"key": held["key"], "fields": {name: held["fields"][name] for name in asked}} # type: ignore[index]
asked, _, properties = url.partition("?fields=")[2].partition("&properties=")
return {"key": held["key"], "fields": {name: held["fields"][name] for name in asked.split(",")}} | ({"properties": {name: value for name, value in held.get("properties", {}).items() if name == properties}} if properties else {}) # type: ignore[index, attr-defined]
if method == "GET" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)):
return {"transitions": [] if held["fields"]["status"] == DONE else self.workflow} # type: ignore[index]
if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)):
assert isinstance(body, dict)
held["fields"]["status"] = DONE # type: ignore[index]
held["fields"]["status"] = next(offer["to"] for offer in self.workflow if offer["id"] == body["transition"]["id"]) # type: ignore[index]
self.transitioned.append(body["transition"]["id"])
return None
if method == "GET" and url == MYSELF:
return ME
if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/assignee"), None)):
assert body == {"accountId": ME["accountId"]}, body
held["fields"]["assignee"] = ME # type: ignore[index]
return None
if method == "GET" and url == ACTIVE_SPRINTS:
return {"values": self.sprints}
if method == "POST" and url == SPRINT_ISSUES:
assert isinstance(body, dict)
self.sprinted.append(body["issues"])
return None
if method == "POST" and url == ISSUES:
return self.created(body)
if method == "PUT" and url == RANK:
@@ -95,8 +119,13 @@ class FakeJira:
assert isinstance(body, dict)
self.comments.setdefault(str(held["key"]), []).append(body["body"])
return {"id": "1"}
if method == "PUT" and (held := next((issue for issue in self.issues if url.startswith(f"{ISSUES}/{issue['key']}/properties/")), None)):
held.setdefault("properties", {})[url.rpartition("/")[2]] = body # type: ignore[attr-defined]
return None
if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}"), None)):
assert isinstance(body, dict)
if "fields" not in body and "update" not in body:
return Failure("Jira answered 400: one of 'fields' or 'update' required")
added = [change["add"] for change in body["update"]["labels"]]
held["fields"]["labels"] = sorted({*held["fields"]["labels"], *added}) # type: ignore[index]
return None
@@ -116,9 +145,10 @@ class FakeJira:
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
kind = fields["issuetype"] if parent == "ABC-12" and fields["issuetype"] in [{"name": "Task"}, {"name": "Feature"}, {"name": "Chore"}] 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")
self.filed_as.append(fields["issuetype"])
key = f"ABC-{len(self.issues) + 100}"
# The links Jira makes as it creates the issue: the inward issue blocks the new one, which then reads "is blocked by" it.
links = [{"id": "1", "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": add["add"]["inwardIssue"]} for add in body.get("update", {}).get("issuelinks", []) if add["add"]["type"] == {"name": "Blocks"}]
@@ -161,9 +191,14 @@ class Case(unittest.TestCase):
class JiraEpicContract(Case, EpicStoreContract):
transition = "Mark as done"
def assign(self, store: JiraEpic, key: str, name: str) -> None: # type: ignore[override]
self.jira.change(key, assignee={"accountId": "5b10a2844c20165700ede21g", "displayName": name})
def account(self, store: JiraEpic) -> str: # type: ignore[override]
return ME["displayName"]
def comments_on(self, store: JiraEpic, key: str) -> list[str]: # type: ignore[override]
return [to_markdown([document])[0].strip() for document in self.jira.comments.get(key, [])] # type: ignore[misc]
@@ -213,11 +248,255 @@ class Jira(Case):
self.jira.answers[("POST", TRANSITIONS)] = Failure("Jira answered 503")
self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again"))
def test_scores_a_sub_task_of_a_child_but_no_issue_of_another_epic(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str), key
task = store.file(key, "Count them in the API.", "", ())
assert isinstance(task, str), task
scores = {"L": 2, "E": 1, "I": 2, "S": 3}
self.assertIsNone(store.set_scores(task, scores, "", "Scored."))
read = f"{ISSUES}/{key}?fields=parent&properties=plan-item"
self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "XYZ-1"}}}
refused = store.set_scores(key, scores, "", "Scored.")
assert isinstance(refused, Failure), refused
self.assertTrue(refused.reason.startswith("cannot read XYZ-1 to score its sub-task: "), refused.reason)
for answer in ({"fields": {"parent": {"key": task}}}, {"fields": {"parent": {"key": 12}}}, {"fields": {}}, {"fields": "none"}, []):
with self.subTest(answer=answer):
self.jira.answers[("GET", read)] = answer
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"{key} is not one of the child issues of the epic ABC-12, so it cannot be scored"))
self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": []}
self.assertIsNone(store.set_scores(key, scores, "", "Scored."))
def test_says_how_far_a_scoring_came_where_jira_fails(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str), key
scores = {"L": 2, "E": 1, "I": 2, "S": 3}
read = f"{ISSUES}/{key}?fields=parent&properties=plan-item"
self.jira.answers[("GET", read)] = Failure("Jira answered 503")
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"cannot read {key} to score it: Jira answered 503"))
self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": {"plan-item": "L 2"}}
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"{key}'s issue property plan-item is not a JSON object"))
self.jira.answers[("GET", read)] = {"fields": {"parent": {"key": "ABC-12"}}, "properties": {"plan-item": {"L": "many"}}}
refused = store.set_scores(key, scores, "", "Scored.")
assert isinstance(refused, Failure), refused
self.assertTrue(refused.reason.startswith(f"cannot score {key}: item {key}'s L 'many'"), refused.reason)
self.assertEqual(self.jira.comments.get(key, []), [])
del self.jira.answers[("GET", read)]
self.jira.answers[("POST", f"{ISSUES}/{key}/comment")] = Failure("Jira answered 503")
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"cannot comment on {key} to tell its team the scores: Jira answered 503"))
del self.jira.answers[("POST", f"{ISSUES}/{key}/comment")]
self.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")] = Failure("Jira answered 503")
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: Jira answered 503"))
del self.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")]
# No scores were set while the comment failed, so the issue is still scored once Jira answers.
self.assertIsNone(store.set_scores(key, scores, "", "Scored."))
def test_says_why_the_epics_status_cannot_be_read(self) -> None:
for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), ({"fields": {"status": {"statusCategory": {"key": 3}}}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text")):
self.jira.answers[("GET", EPIC_STATUS)] = answer
self.assertEqual(self.new_store().closed(), Failure(reason))
def starting(self, start: Start = Start("Start", 6)) -> JiraEpic:
"""A store whose settings name start, on a workflow that has the transition Start to In Progress."""
self.jira.workflow.append({"id": "21", "name": "Start", "to": IN_PROGRESS})
return dataclasses.replace(self.new_store(), start=start)
def test_starts_an_issue_by_the_transition_and_into_the_active_sprint_of_the_board_the_settings_name(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
self.assertIsNone(store.start_issue(key))
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, IN_PROGRESS)) # type: ignore[index]
self.assertEqual((self.jira.transitioned, self.jira.sprinted), (["21"], [[key]]))
def test_a_starting_sub_tasks_parent_joins_the_sprint_in_its_place(self) -> None:
store = self.starting()
child = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(child, str)
task = store.file(child, "Count them in the api.", "", ())
assert isinstance(task, str)
self.assertIsNone(store.start_issue(task))
self.assertEqual(self.jira.sprinted, [[child]])
self.assertEqual([issue["fields"]["status"] for issue in self.jira.issues], [TO_DO, IN_PROGRESS]) # type: ignore[index]
def test_an_issue_past_the_start_keeps_its_status_and_one_someone_holds_keeps_its_holder(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}}
ada = {"accountId": "5b10a2844c20165700ede21g", "displayName": "Ada Berg"}
self.jira.change(key, status=review, assignee=ada)
self.assertEqual(store.start_issue(key), "Ada Berg")
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ada, review)) # type: ignore[index]
self.assertEqual((self.jira.transitioned, self.jira.sprinted), ([], [[key]]))
self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls)
def test_without_the_settings_a_start_only_assigns(self) -> None:
store = self.starting(Start())
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
self.assertIsNone(store.start_issue(key))
self.assertEqual((self.jira.issues[0]["fields"]["assignee"], self.jira.issues[0]["fields"]["status"]), (ME, TO_DO)) # type: ignore[index]
self.assertEqual(self.jira.calls[-2:], [("GET", MYSELF), ("PUT", f"{ISSUES}/{key}/assignee")])
def test_a_start_names_each_step_jira_did_not_take_and_makes_the_others(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
assert isinstance(key, str)
transitions, assignee = f"{ISSUES}/{key}/transitions", f"{ISSUES}/{key}/assignee"
for answers, reason in (
({("GET", f"{ISSUES}/{key}?fields=assignee,status"): Failure("Jira answered 503")}, f"cannot read {key} to start it: Jira answered 503"),
({("GET", f"{ISSUES}/{key}?fields=assignee,status"): {"fields": {"assignee": None}}}, f"{key} is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"),
({("GET", MYSELF): Failure("Jira answered 503")}, f"cannot read which account do-epic works as, to assign {key}: Jira answered 503"),
({("GET", MYSELF): {"displayName": "Do Epic"}}, f"cannot assign {key}: Jira named no account ID for the account do-epic works as"),
({("GET", MYSELF): ["Do Epic"]}, f"cannot assign {key}: Jira named no account ID for the account do-epic works as"),
({("PUT", assignee): Failure("Jira answered 403")}, f"cannot assign {key}: Jira answered 403"),
({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"),
({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"),
({("GET", transitions): {"transitions": [{"id": "31", "name": "Mark as done", "to": DONE}]}}, f"{key} has no transition 'Start' from its status 'To Do', only 'Mark as done' to 'Done': set `jira-start-transition` to a transition the issue has before its work starts"),
({("GET", transitions): {"transitions": [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Wait", "to": TO_DO}]}}, f"{key} has no transition 'Start' from its status 'To Do', only 'Mark as done' to 'Done' and 'Wait' to 'To Do': set `jira-start-transition` to a transition the issue has before its work starts"),
({("GET", transitions): {"transitions": []}}, f"{key} has no transition 'Start' from its status 'To Do', nor any other the account may make"),
({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} by 'Start': Jira answered 400"),
({("GET", ACTIVE_SPRINTS): Failure("Jira answered 400")}, f"cannot read the active sprint of board 6, which `jira-sprint-board` names: Jira answered 400"),
({("GET", ACTIVE_SPRINTS): {"values": [{"name": "Sprint 9"}]}}, "Jira answered board 6's sprints in a shape other than the one it documents"),
({("GET", ACTIVE_SPRINTS): [{"id": 77}]}, "Jira answered board 6's sprints in a shape other than the one it documents"),
({("GET", ACTIVE_SPRINTS): {"values": "Sprint 9"}}, "Jira answered board 6's sprints in a shape other than the one it documents"),
({("GET", ACTIVE_SPRINTS): {"values": []}}, f"board 6, which `jira-sprint-board` names, has no active sprint, so {key} doesn't join a sprint"),
({("GET", ACTIVE_SPRINTS): {"values": [{"id": 77}, {"id": 78}]}}, f"board 6, which `jira-sprint-board` names, has 2 active sprints, so {key} doesn't join a sprint"),
({("POST", SPRINT_ISSUES): Failure("Jira answered 403")}, f"cannot add {key} to the active sprint of board 6: Jira answered 403"),
):
with self.subTest(reason=reason):
self.jira.change(key, status=TO_DO, assignee=None)
self.jira.answers, self.jira.sprinted = answers, []
self.assertEqual(store.start_issue(key), Failure(reason))
self.jira.answers = {("PUT", assignee): Failure("Jira answered 403")}
self.jira.change(key, status=TO_DO, assignee=None)
store.start_issue(key)
self.assertEqual((self.jira.issues[0]["fields"]["status"], self.jira.sprinted), (IN_PROGRESS, [[key]])) # type: ignore[index]
def test_a_start_that_fails_twice_on_an_issue_someone_holds_names_both_steps_and_the_holder(self) -> None:
store = self.starting()
key = store.file("ABC-12", "Count the runs.", "", ())
self.jira.change(key, assignee={"accountId": "ada", "displayName": "Ada Berg"})
self.jira.answers = {("POST", f"{ISSUES}/{key}/transitions"): Failure("Jira answered 400"), ("POST", SPRINT_ISSUES): Failure("Jira answered 403")}
self.assertEqual(store.start_issue(key), Failure(f"cannot move {key} by 'Start': Jira answered 400; cannot add {key} to the active sprint of board 6: Jira answered 403; {key} stays assigned to Ada Berg"))
self.jira.answers = {("GET", MYSELF): Failure("Jira answered 503"), ("POST", SPRINT_ISSUES): Failure("Jira answered 403")}
self.assertEqual(store.start_issue(key), Failure(f"cannot read which account do-epic works as, to assign {key}: Jira answered 503; cannot add {key} to the active sprint of board 6: Jira answered 403"))
self.jira.change(key, assignee=ME)
self.jira.answers = {("POST", SPRINT_ISSUES): Failure("Jira answered 403")}
self.assertEqual(store.start_issue(key), Failure(f"cannot add {key} to the active sprint of board 6: Jira answered 403"))
def test_a_start_says_which_issue_jira_cannot_read_and_refuses_one_outside_the_epic(self) -> None:
store = self.starting()
child = store.file("ABC-12", "Count the runs.", "", ())
task = store.file(child, "Count them in the api.", "", ())
self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}})
self.assertEqual(store.start_issue("ABC-61"), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be started"))
self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503")
self.assertEqual(store.start_issue(task), Failure(f"cannot read {task} to start it: Jira answered 503"))
del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")]
self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503")
self.assertEqual(store.start_issue(task), Failure(f"cannot read {child} to start its sub-task: Jira answered 503"))
def test_moves_an_issue_by_the_transition_that_leads_to_the_status_named_in_any_case(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
review = {"name": "Code Review", "statusCategory": {"key": "indeterminate"}}
self.jira.workflow = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "51", "name": "Ask for review", "to": review}]
self.assertIsNone(store.move_issue(key, "code review"))
self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["51"], review)) # type: ignore[index]
self.assertIsNone(store.move_issue(key, "Code Review"))
self.assertEqual(self.jira.transitioned, ["51"])
def test_moves_an_issue_by_the_transition_named_in_any_case_and_answers_the_status_it_leads_to(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
ready = {"name": "Release Ready", "statusCategory": {"key": "indeterminate"}}
self.jira.workflow = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "61", "name": "Ready for release", "to": ready}]
self.assertEqual(store.move_issue_by(key, "ready for release", ("Teach & Learn", "RELEASE READY")), "Release Ready")
self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["61"], ready)) # type: ignore[index]
def test_an_issue_already_at_a_status_the_transition_may_lead_to_stays_as_it_is(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
self.jira.issues[0]["fields"]["status"] = {"name": "Release Ready", "statusCategory": {"key": "indeterminate"}} # type: ignore[index]
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done", "release ready")), "Release Ready")
self.assertEqual(self.jira.transitioned, [])
def test_a_transition_that_leads_to_another_status_than_those_asked_for_is_not_made(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Release Ready", "Teach & Learn")), Failure(f"the transition 'Mark as done' leads {key} to the status 'Done', not to 'Release Ready' or 'Teach & Learn'"))
self.assertEqual(self.jira.transitioned, [])
def test_a_transition_the_workflow_does_not_offer_fails_naming_what_it_offers(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', only 'Mark as done' to 'Done'"))
self.jira.workflow.append({"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}})
self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', only 'Mark as done' to 'Done' and 'Start' to 'In Progress'"))
self.jira.workflow = []
self.assertEqual(store.move_issue_by(key, "Release Ready", ("Release Ready",)), Failure(f"{key} has no transition 'Release Ready' from its status 'To Do', nor any other the account may make"))
self.assertEqual(self.jira.transitioned, [])
def test_a_move_by_a_transition_that_jira_refuses_or_cannot_be_read_fails_with_the_reason(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}})
self.assertEqual(store.move_issue_by("ABC-61", "Mark as done", ("Done",)), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be moved"))
transitions = f"{ISSUES}/{key}/transitions"
self.jira.answers = {("POST", transitions): Failure("Jira answered 400")}
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot move {key} by 'Mark as done': Jira answered 400"))
self.jira.answers = {("GET", transitions): Failure("Jira answered 503")}
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key}'s transitions: Jira answered 503"))
self.jira.answers = {("GET", transitions): {"transitions": [{"id": "31"}]}}
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents"))
self.jira.answers = {("GET", f"{ISSUES}/{key}?fields=parent,status"): Failure("Jira answered 503")}
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key} to move it: Jira answered 503"))
self.jira.answers = {("GET", f"{ISSUES}/{key}?fields=status"): Failure("Jira answered 502")}
self.assertEqual(store.move_issue_by(key, "Mark as done", ("Done",)), Failure(f"cannot read {key} to move it: Jira answered 502"))
def test_a_move_the_workflow_does_not_offer_fails_naming_what_it_offers(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', only 'Mark as done' to 'Done'"))
self.jira.workflow.append({"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}})
self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', only 'Mark as done' to 'Done' and 'Start' to 'In Progress'"))
self.jira.workflow = []
self.assertEqual(store.move_issue(key, "Code Review"), Failure(f"{key} has no transition to the status 'Code Review' from its status 'To Do', nor any other the account may make"))
self.assertEqual(self.jira.transitioned, [])
def test_a_move_jira_cannot_read_or_refuses_fails_saying_which(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
transitions = f"{ISSUES}/{key}/transitions"
status = f"{ISSUES}/{key}?fields=status"
for answers, reason in (
({("GET", status): Failure("Jira answered 503")}, f"cannot read {key} to move it: Jira answered 503"),
({("GET", status): {"key": key, "fields": {}}}, f"{key} is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"),
({("GET", transitions): Failure("Jira answered 503")}, f"cannot read {key}'s transitions: Jira answered 503"),
({("GET", transitions): {"transitions": [{"id": "21"}]}}, f"Jira answered {key}'s transitions in a shape other than the one it documents"),
({("POST", transitions): Failure("Jira answered 400")}, f"cannot move {key} to 'Done': Jira answered 400"),
):
with self.subTest(reason=reason):
self.jira.answers = answers
self.assertEqual(store.move_issue(key, "Done"), Failure(reason))
def test_a_move_says_which_issue_jira_cannot_read_and_refuses_one_outside_the_epic(self) -> None:
store = self.new_store()
child = store.file("ABC-12", "Count the runs.", "", ())
task = store.file(child, "Count them in the api.", "", ())
self.jira.issues.append({"key": "ABC-61", "fields": {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": None, "issuelinks": []}})
self.assertEqual(store.move_issue("ABC-61", "Done"), Failure("ABC-61 is not one of the child issues of the epic ABC-12, so it cannot be moved"))
self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503")
self.assertEqual(store.move_issue(task, "Done"), Failure(f"cannot read {task} to move it: Jira answered 503"))
del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")]
self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = Failure("Jira answered 503")
self.assertEqual(store.move_issue(task, "Done"), Failure(f"cannot read {child} to move its sub-task: Jira answered 503"))
self.assertEqual(self.jira.transitioned, [])
def test_finishes_an_issue_by_the_transition_the_settings_name(self) -> None:
store = self.new_store()
key = store.file("ABC-12", "Count the runs.", "", ())
@@ -296,9 +575,24 @@ class Jira(Case):
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:
def test_files_a_child_as_a_task_where_the_settings_name_no_type(self) -> None:
self.new_store().file("ABC-12", "Count the runs.", "", ())
self.assertNotIn(("GET", ISSUE_TYPES), self.jira.calls)
self.assertEqual(self.jira.filed_as, [{"name": "Task"}])
def test_files_a_finding_and_a_release_review_as_the_types_the_settings_name(self) -> None:
store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Feature", review_type="Chore")
store.file("ABC-12", "Count the runs.", "", ("repo:api",))
store.file("ABC-12", "Review api.", "", ("repo:api", REVIEW_LABEL))
self.assertEqual(self.jira.filed_as, [{"name": "Feature"}, {"name": "Chore"}])
def test_does_not_file_anything_where_the_project_lacks_the_type_and_names_the_types_it_has(self) -> None:
store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Feature", review_type="Investigation")
self.assertEqual(store.file("ABC-12", "Review api.", "", (REVIEW_LABEL,)), Failure("ABC has no issue type 'Investigation' for an issue under an epic; it has Task, Feature and Chore: name one in `jira-review-type`"))
self.assertEqual(self.jira.issues, [])
def test_names_the_setting_of_a_finding_where_the_project_lacks_its_type(self) -> None:
store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, finding_type="Investigation")
self.assertEqual(store.file("ABC-12", "Count the runs.", "", ()), Failure("ABC has no issue type 'Investigation' for an issue under an epic; it has Task, Feature and Chore: name one in `jira-finding-type`"))
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")):
@@ -314,7 +608,7 @@ class Jira(Case):
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")):
for answer, reason in ((Failure("Jira answered 403"), "cannot read ABC's issue types: Jira answered 403"), ({"issueTypes": [{"id": "10001", "name": "Task", "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))
+12 -2
View File
@@ -12,6 +12,7 @@ from project_config.settings import ProjectConfig
from model_routing.ladder import ProjectRung
from chunk_driver import prompts
from model_routing.route import Route
from project_config import templates
from agent_cycle.worker_prompts import WorkerPrompts
# The entry point's name as the worker, the judge and the human read it.
@@ -21,7 +22,7 @@ DRIVER = DO_EPIC
def shipping(config: ProjectConfig) -> str:
"""How a chunk in the repo that config names ships its change. An epic's issue isn't an item of the repo's plan, so `chunk-pr merge --finish`, which adds a finished item's changelog bullet, doesn't apply: the worker writes the bullet itself, where the repo publishes something others consume. (docs/decisions.md → `do-epic: drives one Jira epic …`, "Releases"). Where the repo's config leaves the merge to a person, the worker ends its run on `chunk-pr merge`'s word, since do-epic parks the chunk until that merge ("Long gates")."""
opening = "The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`."
if config.merge == "human":
if config.merge == "human" and config.epic_branch is None:
opening += " The repo's team merges its pull requests itself, so `chunk-pr merge` leaves the pull request ready for a person to merge: end your run when it says so."
if config.epic:
return f"{opening} The repo's plan is a Jira epic, and the history of its issues serves as the changelog, so leave the changelog as it is."
@@ -29,9 +30,18 @@ def shipping(config: ProjectConfig) -> str:
return f"{opening} Where the repo publishes something others consume, add one bullet to `## Unreleased` in `{changelog}` that tells the repo's consumers what changed; otherwise leave the changelog as it is."
def epic_branch_rule(config: ProjectConfig, epic: str) -> str:
"""What a chunk is told where the repo's config sets `epic-branch`, empty where it doesn't: its base, that its merge needs no person, how a later push asks for a review, and which branch the epic's other repos are tested at (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
if config.epic_branch is None:
return ""
branch = templates.epic_branch(config.epic_branch, epic)
pushed = " After `chunk-pr ready`, push each commit with `chunk-pr push`, which asks the repo's auto-reviewer to review the new head, and wait for that review." if config.review_request_comment else ""
return f"The chunk's pull request goes into the epic's working branch `{branch}`, not into the default branch: {DRIVER} has made that branch level with the default branch and recorded it as the base of the chunk's branch, so make the chunk's worktree and branch off `origin/{branch}`. `chunk-pr merge` merges into `{branch}` without waiting for a person.{pushed} Where the chunk's tests run other repos of the epic, run each at its branch `{branch}` where it has one, else at its default branch, and name in the chunk's summary each repo that ran at its default branch."
def task(issue: EpicIssue, epic: str, team: LabelRepos, checkout: str | None, launcher: pathlib.Path, language: str, config: ProjectConfig | None) -> str:
"""The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None. team is the config's LABEL_REPOS table. launcher is the do-epic that runs the chunk, language the one the epic's Jira text is in, and config the project config of the repo's checkout, None without a repo."""
shipped = shipping(config) if config else ""
shipped = " ".join(filter(None, [shipping(config), epic_branch_rule(config, epic)])) if config else ""
where = f"in the checkout {checkout}, on the branch {issue.key}" if checkout else "which changes no repo: work in the folder you start in"
return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {" ".join(filter(None, [findings.instructions(epic, launcher, language, team, issue), shipped]))} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "")
+95 -4
View File
@@ -17,20 +17,29 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d
- `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.
- `jira-finish-transition` and `jira-finish-status` name the workflow transition that moves a finished chunk's issue and closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic moves no issue to done and closes no epic.
- `[label-repos]` has one line for each label of the team's own that names a repo: the label, then that repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. A team whose label is the repo's name maps the name to itself.
- `jira-start-transition` names the workflow transition that moves an issue as its chunk starts, such as "In Progress". An issue whose work has started already, such as one in Code Review, keeps its status. Without it do-epic doesn't move a starting issue.
- `jira-sprint-board` is the ID of a Jira board, the number in the board's address, such as `6`. An issue whose chunk starts joins that board's active sprint; a sub-task's parent joins in its place. Without it do-epic doesn't add a starting issue to a sprint.
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks. A status Jira counts as done always does both, listed or not.
- `jira-automation-moves-issues = true` says the team's own automation moves an issue when its pull request merges. do-epic then moves only the issue of a chunk without a repo, which has no pull request, and waits for the automation to move each other. It needs `jira-unblocking-statuses`, which then names the status the automation gives an issue whose pull request merged. false where left out.
- `jira-pull-request-open-status` and `jira-pull-request-merged-status` name the statuses do-epic itself gives an issue whose chunk merges into an epic's working branch, in a repo whose config sets `epic-branch` (`project-config --help`): the first once the chunk's pull request is open, such as `"Code Review"`, and the second once it has merged into that branch, such as `"Release Ready"`. A team's automation moves an issue only for a pull request into the default branch, so there do-epic makes both moves, whatever `jira-automation-moves-issues` says. `jira-unblocking-statuses` must list the second, and an issue that has it counts as done when the epic's release reviews and its finishing chunk fall due: both come before a person merges the working branch into the default branch. Without the first, do-epic doesn't move an issue as its pull request opens. Without the second, do-epic moves a finished chunk's issue to done. Where `jira-automation-moves-issues` is set, it stops instead and asks you to move the issue.
- `jira-finding-type` names the Jira issue type do-epic files a finding as, and `jira-review-type` the one it files a repo's release review as, such as `"Feature"` and `"Chore"`, for a Jira project that has no Task type. Task where left out. do-epic doesn't file anything where the project lacks the type, and says which types it has.
- `sub-task-summary` shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `"{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Where left out, a summary is `[<repo>] <the issue's summary>`.
- `[label-repos]` has one line for each label of the team's own that names a repo: the label, then that repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. A team whose label is the repo's name maps the name to itself. Where several lines name one repo, do-epic writes the label of the first.
- `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
import string
import types
from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINISH, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE
from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault
from failure import Failure
from do_epic.backend.protocol import LABEL
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL
from text_files.markdown_text import listed
from model_routing.ladder_file import read_ladder, SHIPPED
from do_epic.split import SPLIT_LABEL
from do_epic.backend.jira_start import SPRINT_BOARD, Start, START_TRANSITION
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.
@@ -40,7 +49,16 @@ CLONE_FOLDER = "clone-folder"
SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL)
# Three readers, seated as those who write and read this config, picked `label-repos` from four candidates, over `repo-aliases`, `repo-labels` and `team-labels`, 2-1. All three readers would misread `repo-labels` as mapping a repo to its label.
LABEL_REPOS = "label-repos"
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, LABEL_REPOS)
# Three readers, seated as those who write and read this config, picked `jira-unblocking-statuses` from four candidates, 3-0, and `jira-automation-moves-issues` 2-1. `jira-unblock-statuses` reads as statuses do-epic moves an issue to, and `jira-finish-issues = false` as closing no epic either.
UNBLOCKING_STATUSES = "jira-unblocking-statuses"
AUTOMATION_MOVES = "jira-automation-moves-issues"
# Three readers, seated as those who write and read this config, picked `jira-pull-request-open-status` from four candidates, 2-1, and the merged status's name was spelt to pair with it. Each names a status, not a transition as `jira-start-transition` does: do-epic takes whichever transition leads there.
PULL_OPEN_STATUS = "jira-pull-request-open-status"
PULL_MERGED_STATUS = "jira-pull-request-merged-status"
SUB_TASKS_LANDED_TRANSITION = "jira-sub-tasks-landed-transition"
SUB_TASK_SUMMARY = "sub-task-summary"
ISSUE_TYPES = (JIRA_FINDING_TYPE, JIRA_REVIEW_TYPE)
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, START_TRANSITION, SPRINT_BOARD, UNBLOCKING_STATUSES, AUTOMATION_MOVES, PULL_OPEN_STATUS, PULL_MERGED_STATUS, SUB_TASKS_LANDED_TRANSITION, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}."
@@ -58,6 +76,19 @@ class DoEpicConfig:
finish: Finish | None = None
# The LABEL_REPOS table; empty where the config has none.
label_repos: LabelRepos = types.MappingProxyType({})
# The UNBLOCKING_STATUSES list; empty where the config has none.
unblocking: tuple[str, ...] = ()
automation_moves: bool = False
# PULL_OPEN_STATUS and PULL_MERGED_STATUS; each None where the config doesn't name it.
pull_open_status: str | None = None
pull_merged_status: str | None = None
# The SUB_TASK_SUMMARY template; None where the config has none.
sub_task_summary: str | None = None
finding_type: str = DEFAULT_ISSUE_TYPE
review_type: str = DEFAULT_ISSUE_TYPE
start: Start = Start()
# The SUB_TASKS_LANDED_TRANSITION transition, which `parent_moves` moves a parent by; None where the config doesn't name it.
sub_tasks_landed_transition: str | None = None
def label_repo_faults(table: object) -> list[str]:
@@ -72,6 +103,54 @@ def label_repo_faults(table: object) -> list[str]:
]
def summary_template_faults(template: object) -> list[str]:
"""What is wrong with the SUB_TASK_SUMMARY template: a value that isn't one line, that Python can't read as a template, a field other than `{label}` and `{Summary}`, a format after a field's name, or no `{Summary}`."""
example = "`\"{label}: {Summary}\"`"
if not isinstance(template, str) or "\n" in template:
return [f"`{SUB_TASK_SUMMARY}` is {template!r}, not one line of text such as {example}"]
try:
fields = [(name, spec, conversion) for _, name, spec, conversion in string.Formatter().parse(template) if name is not None]
except ValueError as failure:
return [f"`{SUB_TASK_SUMMARY}` is {template!r}, which Python can't read as a template ({failure}); write a brace that is plain text as {{{{ or }}}}"]
names = [name for name, _, _ in fields]
return [
*(f"`{SUB_TASK_SUMMARY}` names {{{name}}}, and only {{label}} and {{Summary}} are known" for name in dict.fromkeys(names) if name not in ("label", "Summary")),
*(f"`{SUB_TASK_SUMMARY}` writes {{{name}{'!' + conversion if conversion else ''}{':' + spec if spec else ''}}} with something after the name; write {{{name}}} alone" for name, spec, conversion in fields if (spec or conversion) and name in ("label", "Summary")),
*([f"`{SUB_TASK_SUMMARY}` lacks {{Summary}}, so no sub-task's summary would say what changes in it, such as {example}"] if "Summary" not in names else []),
]
def start_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the START_TRANSITION and SPRINT_BOARD settings in values."""
transition, board = values.get(START_TRANSITION), values.get(SPRINT_BOARD)
return [
*([f"`{START_TRANSITION}` is {transition!r}, not the name Jira shows, such as \"In Progress\""] if START_TRANSITION in values and not name_of(transition) else []),
# TOML reads true as a bool, which Python counts as the whole number 1.
*([f"`{SPRINT_BOARD}` is {board!r}, not a board's ID, the whole number in the board's address, such as 6"] if SPRINT_BOARD in values and not (isinstance(board, int) and not isinstance(board, bool) and board > 0) else []),
]
def jira_name_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the PULL_OPEN_STATUS, PULL_MERGED_STATUS and SUB_TASKS_LANDED_TRANSITION settings in values."""
merged, unblocking = name_of(values.get(PULL_MERGED_STATUS)), values.get(UNBLOCKING_STATUSES, [])
listed_statuses = [status.casefold() for status in unblocking if isinstance(status, str)] if isinstance(unblocking, list) else []
return [
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in ((PULL_OPEN_STATUS, "Code Review"), (PULL_MERGED_STATUS, "Release Ready"), (SUB_TASKS_LANDED_TRANSITION, "Release Ready")) if name in values and not name_of(values[name])),
*([f"`{PULL_MERGED_STATUS}` is {merged!r}, so `{UNBLOCKING_STATUSES}` must list it: an issue at any other status reads as open, and its chunk would start again"] if merged and merged.casefold() not in listed_statuses else []),
]
def workflow_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the UNBLOCKING_STATUSES list and the AUTOMATION_MOVES switch in values."""
statuses, moves = values.get(UNBLOCKING_STATUSES, ["Done"]), values.get(AUTOMATION_MOVES, False)
return [
*([f"`{UNBLOCKING_STATUSES}` is {statuses!r}, not a list of the status names Jira shows, such as [\"Release Ready\"]"] if not (isinstance(statuses, list) and statuses and all(name_of(status) for status in statuses)) else []),
*([f"`{AUTOMATION_MOVES}` is {moves!r}, not true or false"] if not isinstance(moves, bool) else []),
# With no status listed, an issue whose pull request merged would read as open, and its chunk would start again.
*([f"`{AUTOMATION_MOVES}` is set, so `{UNBLOCKING_STATUSES}` must name the status the automation gives an issue whose pull request merged"] if moves is True and UNBLOCKING_STATUSES not in values else []),
]
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
@@ -102,7 +181,12 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
*([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 []),
*finish_faults(values),
*workflow_faults(values),
*start_faults(values),
*jira_name_faults(values),
*(summary_template_faults(values[SUB_TASK_SUMMARY]) if SUB_TASK_SUMMARY in values else []),
*label_repo_faults(values.get(LABEL_REPOS, {})),
*(f"`{name}` is {values[name]!r}, {fault}" for name, example in zip(ISSUE_TYPES, ("Feature", "Chore")) if name in values and (fault := type_fault(values[name], example))),
*([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []),
]
if faults:
@@ -111,4 +195,11 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi
assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str)
labels = values.get(LABEL_REPOS, {})
assert isinstance(labels, dict)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels))
statuses = values.get(UNBLOCKING_STATUSES, [])
assert isinstance(statuses, list)
template = values.get(SUB_TASK_SUMMARY)
assert template is None or isinstance(template, str)
finding_type, review_type = (str(values.get(name, DEFAULT_ISSUE_TYPE)) for name in ISSUE_TYPES)
board = values.get(SPRINT_BOARD)
assert board is None or isinstance(board, int)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, name_of(values.get(PULL_OPEN_STATUS)), name_of(values.get(PULL_MERGED_STATUS)), template, finding_type, review_type, Start(name_of(values.get(START_TRANSITION)), board), name_of(values.get(SUB_TASKS_LANDED_TRANSITION)))
+68
View File
@@ -0,0 +1,68 @@
"""What `do-epic <EPIC-KEY> --dry-run` runs planning and the scheduler on, in place of Jira, tmux and git: an in-memory copy of the epic that records each write, a tmux that starts no window and a git that clones no repo. The copy starts as the epic is in Jira, and tmux's windows are read as they are, so the run sees the epic and the chunks as they are now."""
import dataclasses
import subprocess
from do_epic.backend.protocol import EpicStore
from failure import Failure
from git_cli.git_repo import Git
from do_epic.backend.fake import MemoryEpic
from agent_cycle.tmux import Tmux
# The tmux commands that only read. Each other command makes or changes a session or a window.
READS = ("list-windows", "show-options")
# The commands that start a window, which a later listing shows.
STARTS = ("new-session", "new-window")
@dataclasses.dataclass
class DryEpic(MemoryEpic):
"""An in-memory epic. A sub-task it files gets a key no Jira issue has, such as ABC-new1, since Jira alone gives the next number."""
filed: int = 0
def next_key(self) -> str:
self.filed += 1
return f"{self.epic_key.rpartition('-')[0]}-new{self.filed}"
def seeded(store: EpicStore) -> DryEpic | Failure:
"""A DryEpic with the issues and the closed state that store holds now, or why they cannot be read."""
issues = store.read()
done = store.closed()
if isinstance(issues, Failure):
return issues
return done if isinstance(done, Failure) else DryEpic(store.epic_key, list(issues), done=done)
def recording(real: Tmux) -> Tmux:
"""real for each read. A command that starts a window is answered as if it had, and the window then shows in each later listing as a window that runs. Any other command, which would change a session or a window, is answered as done."""
started: list[tuple[str, str, str]] = []
def run(args: list[str]) -> subprocess.CompletedProcess[str]:
if args[0] in STARTS:
named = "-s" if "-s" in args else "-t"
session = args[args.index(named) + 1].strip("=:")
started.append((session, args[args.index("-n") + 1], args[args.index("-c") + 1]))
return subprocess.CompletedProcess(args, 0, f"@dry{len(started)}\n", "")
if args[0] not in READS:
return subprocess.CompletedProcess(args, 0, "", "")
done = real(args)
if args[0] != "list-windows":
return done
rows = done.stdout if done.returncode == 0 else ""
if "-a" in args:
rows += "".join(f"{session}\t{name}\t0\t@dry{at}\t{cwd}\n" for at, (session, name, cwd) in enumerate(started, 1))
else:
rows += "".join(f"{name}\t0\t@dry{at}\n" for at, (session, name, _) in enumerate(started, 1) if f"={session}" == args[args.index("-t") + 1])
return subprocess.CompletedProcess(args, 0, rows, "")
return run
def without_clones(real: Git) -> Git:
"""real, except that a command with `clone` among its words fails, so that no repo is cloned."""
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
if "clone" in args:
return Failure("a dry run doesn't clone a repo, but a real run would")
return real(*args, cwd=cwd, timeout=timeout, guarded=guarded, errors=errors)
return run
+83
View File
@@ -0,0 +1,83 @@
"""One run of do-epic on an epic (`EpicRun`), and how it starts the epic's chunks that may start now (`chunks_started`)."""
import dataclasses
import pathlib
import typing
from do_epic.config import DoEpicConfig
from loop_effects.effects import Effects, say
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.epic_record import EpicRecord
from failure import Failure
from do_epic import finish, planning, scheduler
from do_epic.repos import locate
from loop_state.paths import Paths
from forge.commands import Run, runner
from agent_cycle import tmux
# How often a parked chunk reads its pull request's gate, and a human task's window reads the epic: a person answers in hours, and each read is a few calls.
POLL_SECONDS = 60
@dataclasses.dataclass(frozen=True)
class EpicRun:
"""What stays the same through one run of do-epic on an epic."""
key: str
config: DoEpicConfig
store: EpicStore
record: EpicRecord
paths: Paths
env: typing.Mapping[str, str]
launcher: pathlib.Path
effects: Effects
# The runner of git's and the forge's commands in a folder.
forge_at: typing.Callable[[str], Run] = runner
@property
def session(self) -> str:
return tmux.session_name(tmux.EPIC, self.key)
def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told: str = "") -> scheduler.Started | Failure:
"""scheduler.start_chunks on the epic's issues, as read, in order of score, and its cap, read afresh; own is the issue of the chunk that asks, and told is the reason the planning just gave for stopping, which isn't said twice. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed."""
due = finish.due(finish.landed(issues, epic.config.pull_merged_status))
closed = due and epic.store.closed()
if isinstance(closed, Failure):
return closed
order = planning.start_order(planned_epic(epic), issues)
if isinstance(order, Failure):
say(f"the issues of {epic.key} start in Jira's backlog order, since they cannot be put in order of score" + ("" if order.reason == told else f": {order.reason}"), epic.effects, stdout=True)
elif len(order) > 1:
say(f"by score, the issues of {epic.key} start in the order {', '.join(order)}", epic.effects, stdout=True)
scheduled = scheduled_epic(epic, () if isinstance(order, Failure) else tuple(order))
if isinstance(scheduled, Failure):
return scheduled
started = scheduler.start_chunks(scheduled, issues, due and not closed, own, epic.effects.tmux)
return started if isinstance(started, Failure) else dataclasses.replace(started, closed=closed)
def planned_epic(epic: EpicRun) -> planning.Planned:
"""The epic as planning reads and writes it."""
return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects)
def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Failure:
"""The epic as scheduler limits its chunks: with its cap, read afresh, each repo's checkout, and the order its scored issues start in."""
cap = epic.record.parallel_chunks()
if isinstance(cap, Failure):
return cap
# The checkouts located so far, from whose remotes repos.locate tells where to clone a repo that is missing.
seen: list[pathlib.Path] = []
def located(name: str) -> tuple[pathlib.Path, int] | Failure:
found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git)
if isinstance(found, Failure):
return found
seen.append(found.checkout)
return real(found.checkout), found.config.parallel_chunks
return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos, order, epic.config.unblocking)
def real(checkout: pathlib.Path) -> pathlib.Path:
"""The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other."""
return checkout.resolve()
+16 -8
View File
@@ -7,7 +7,7 @@ import fcntl
import pathlib
import typing
from do_epic.repo_pick import also, CLAUDE_LABEL, HUMAN_LABEL, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL, team_label
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.epic_record import EpicRecord
from failure import Failure
@@ -20,15 +20,22 @@ LABEL = "--label"
BLOCKED_BY = "--blocked-by"
PARENT = "--parent"
RECORD_DECISION = "--record-decision"
# The labels that say where an issue is worked, as do-epic's scheduler reads them.
LABELS = f"`{REPO_PREFIX}<name>` for the repo that works it, `{CLAUDE_LABEL}` for work of Claude's that changes no repo, or `{HUMAN_LABEL}` for a task of the human's"
def worked_by(team: LabelRepos) -> str:
"""The labels that say where an issue is worked, as do-epic's scheduler reads them: for each repo the team's table names, the label on its first line for that repo, and `repo:<name>` for any other repo."""
named = [f"`{label}` for the repo {name}" for name in sorted(set(team.values())) if (label := team_label(name, team))]
repos = ", ".join([*named, f"`{REPO_PREFIX}<name>` for {'any other repo' if named else 'the repo'} that works it"])
return f"{repos}, `{CLAUDE_LABEL}` for work of Claude's that changes no repo, or `{HUMAN_LABEL}` for a task of the human's"
# Under the epic's folder, the file a do-epic holds locked while it appends a decision.
DECISIONS_LOCK = "decisions.lock"
USAGE = f"""do-epic <EPIC-KEY> {FILE} <summary> [{LABEL} <label>]... [{BLOCKED_BY} <KEY>] [{PARENT} <KEY>] [<<'EOF' detail EOF]
do-epic <EPIC-KEY> {RECORD_DECISION} <title> <<'EOF' entry EOF"""
HELP = f"""{FILE} files a finding about one of the epic's goals as an open issue of the epic, with the markdown piped in as its description.
A finding about a repo's own goals goes into that repo's plan instead.
{LABEL} is {LABELS}; without one, the next `do-epic <EPIC-KEY>` you run picks where the issue is worked.
{LABEL} is {worked_by({})}; without one, the next `do-epic <EPIC-KEY>` you run picks where the issue is worked.
A second {LABEL}, `{REVIEW_LABEL}`, marks the issue as a repo's release review, which the epic's finishing files.
{BLOCKED_BY} <KEY> makes the new issue wait for the issue <KEY>, which is a child issue of the epic or a sub-task of one.
{PARENT} <KEY> files the new issue as a sub-task of the child issue <KEY>.
@@ -41,11 +48,12 @@ def instructions(epic: str, launcher: pathlib.Path, language: str, team: LabelRe
next_step = ""
if issue:
parent = f" {PARENT} {issue.parent}" if issue.parent != epic else ""
label = next((f" {LABEL} {each}" for each in issue.labels if of_label(each, team)), "")
pick = next((found for each in issue.labels if (found := of_label(each, team))), None)
label = f" {LABEL} {label_of(pick, team)}" if pick else ""
next_step = f"Where the repo's rules ask for a change to ship as more than one pull request, finish only this issue's pull request, and file only the next one as an issue that waits for it, with `{launcher} {epic} {FILE} \"<summary>\" {BLOCKED_BY} {issue.key}{parent}{label}` and its detail on stdin. "
return (
f"File a finding about one of the epic's goals in the epic, with `{launcher} {epic} {FILE} \"<summary>\" {LABEL} <label>` and its detail on stdin. "
f"The label is {LABELS}; leave it out where you cannot tell, and the next `do-epic` the human runs picks it. "
f"The label is {worked_by(team)}; leave it out where you cannot tell, and the next `do-epic` the human runs picks it. "
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
"File a finding about a repo's goals by that repo's rules. Where unsure which, ask the human. "
f"Record a decision that governs the epic, such as an answer the human typed, with `{launcher} {epic} {RECORD_DECISION} \"<title>\"` and its text on stdin. "
@@ -96,13 +104,13 @@ def written(epic: str, write: Write, store: EpicStore, team: LabelRepos, record:
flag, value, labels = write.flag, write.value, write.labels
if flag == FILE:
if unread := [label for label in labels if of_label(label, team) is None and label != REVIEW_LABEL]:
return Failure(f"cannot file the finding in the epic {epic}: do-epic doesn't read the label {unread[0]!r}; write {LABELS}{also(team)}")
return Failure(f"cannot file the finding in the epic {epic}: do-epic doesn't read the label {unread[0]!r}; write {worked_by(team)}")
if len(picks := [label for label in labels if of_label(label, team)]) > 1:
return Failure(f"cannot file the finding in the epic {epic}: {listed(picks, 'and')} each say who works it; write one of them")
key = store.file(write.parent or epic, value, text, labels, write.blocked_by)
if isinstance(key, Failure):
return Failure(f"cannot file the finding in the epic {epic}: {key.reason}")
return f"Filed {key} {f'under {write.parent} in ' if write.parent else 'in '}the epic {epic}." + (f" It is blocked by {write.blocked_by}." if write.blocked_by else "") + ("" if any(of_label(label, team) for label in labels) else f" It has no label that says where it is worked, so the next `do-epic {epic}` picks one: {LABELS}.")
return f"Filed {key} {f'under {write.parent} in ' if write.parent else 'in '}the epic {epic}." + (f" It is blocked by {write.blocked_by}." if write.blocked_by else "") + ("" if any(of_label(label, team) for label in labels) else f" It has no label that says where it is worked, so the next `do-epic {epic}` picks one: {worked_by(team)}.")
try:
with decisions_locked(folder):
added = record.append_decision(value, text)
+16 -5
View File
@@ -7,6 +7,7 @@ Once the epic holds issues and none is open, its finishing chunk runs, in a wind
3. With every goal confirmed, `do-epic <EPIC-KEY> --close-epic` posts the summary on the epic and closes it.
The chunk starts again each time the epic holds no open issue, until the epic is closed. A repo is reviewed once per epic, as a release is: the issues filed after its review don't bring another."""
import dataclasses
import pathlib
import typing
@@ -15,7 +16,7 @@ from do_epic.backend.protocol import EpicIssue, EpicStore
from failure import Failure
from do_epic import findings
from do_epic.split import finished
from do_epic.repo_pick import LabelRepos, recorded, Repo, REPO_PREFIX, REVIEW_LABEL
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo, REVIEW_LABEL
from text_files.markdown_text import listed
from text_files.piped_text import piped
@@ -28,6 +29,13 @@ It files a release review of each repo the epic changed, as an issue labelled `{
It closes the epic by the transition `jira-finish-transition` names, to the status `jira-finish-status` names."""
def landed(issues: list[EpicIssue], merged_status: str | None) -> list[EpicIssue]:
"""issues, each counted done where it has the status merged_status, which do-epic's `jira-pull-request-merged-status` names: its work has merged into the epic's working branch, and Jira counts it done only once a person has merged that branch into the default branch. The epic's release reviews and finishing come before that merge, so they can't wait for it (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`). None names no such status."""
if merged_status is None:
return issues
return [dataclasses.replace(issue, done=True) if issue.status.casefold() == merged_status.casefold() else issue for issue in issues]
def due(issues: list[EpicIssue]) -> bool:
"""Whether the epic's finishing comes next: it holds an issue, and none is open."""
return bool(issues) and not still_open(issues)
@@ -57,30 +65,33 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib
if lacking := unreviewed(issues, team):
return (
f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. "
f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"<summary>\" {findings.LABEL} {REPO_PREFIX}<name> {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. "
f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"<summary>\" {findings.LABEL} <label> {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. "
f"The `<label>` is {listed([f'`{label_of(Repo(name), team)}` for {name}' for name in lacking], 'and')}. "
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `Release review of {epic}`. "
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
f"The chunk is finished once each issue is filed: {DRIVER} works them, and starts this chunk again once the epic holds no open issue."
)
return (
f"{opening} Each repo it changed has had its release review. Three steps remain, in this order.\n\n"
f"{opening} Each repo it changed has had its release review. Four steps remain, in this order.\n\n"
"1. Ask the human to confirm each goal under the description's ## Goals: that an achieve goal is achieved, and that no defect stands against a maintain goal. Ask one goal per question, each with the evidence of what shipped. "
"A goal is met only where the human confirms it: never take one as met from the evidence alone. Don't ask again about a goal a decision in the description records as confirmed.\n"
"2. For a goal the human doesn't confirm, propose a set of items that would meet it, and ask the human to approve the set. File each item they approve. "
f"Then the chunk is finished: {DRIVER} works the items, and starts this chunk again once the epic holds no open issue.\n"
f"3. Once the human has confirmed every goal, write a summary in {language}, the epic's language, for the people who work the epic: what shipped in each repo, and each goal's evidence. "
f"3. Once the human has confirmed every goal, run `project-config epic-branch` in the checkout of each repo the epic changed. Where it fails, the repo keeps no working branch for the epic: skip it. Where it prints a template, run `chunk-pr open-epic {epic} \"<title>\"` in that checkout, which makes the epic's working branch level with the default branch and opens the pull request from it into the default branch. Never merge that pull request: a person does.\n"
f"4. Then write a summary in {language}, the epic's language, for the people who work the epic: what shipped in each repo, each pull request step 3 opened, and each goal's evidence. "
f"Post it and close the epic with `{launcher} {epic} {CLOSE}`, the summary on stdin. That is the chunk's very last step, and the chunk is finished once it succeeds.\n\n"
f"{findings.instructions(epic, launcher, language, team)} Record each goal's confirmation as such a decision.\n\n"
"The epic's issues, each done:\n\n" + "\n".join(f"- {issue.key}{f' ({repo})' if (repo := repo_of(issue, team)) else ''}: {issue.summary}" for issue in issues)
)
def closed(epic: str, store: EpicStore, team: LabelRepos, stdin: typing.TextIO) -> str | Failure:
def closed(epic: str, store: EpicStore, team: LabelRepos, stdin: typing.TextIO, merged_status: str | None = None) -> str | Failure:
"""Posts the summary piped in on the epic with the key epic and closes it, and answers the line to print; a Failure, with nothing posted, while the epic isn't ready to close."""
# Whether the human confirmed each goal isn't checked here: a decision that records it is the worker's own text, so only the task and the judge, who reads the human's answers, can hold the worker to it.
issues = store.read()
if isinstance(issues, Failure):
return Failure(f"cannot close the epic {epic}: {issues.reason}")
issues = landed(issues, merged_status)
already = store.closed()
if already:
return Failure(f"cannot close the epic {epic}: {already.reason if isinstance(already, Failure) else 'it is closed already'}")
+22 -9
View File
@@ -5,7 +5,8 @@ import dataclasses
import typing
from forge.reviews import ANSWERED, APPROVED, CHANGES_REQUESTED, review_decision, REVIEW_REQUIRED, waiting_threads
from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks
from forge.pulls import CheckFailed, checks_now, open_pull, other_base, Pending, required_checks, unmergeable
from git_cli.git_repo import CHUNK_BASE
from failure import Failure
from forge.commands import forge_of, Run
@@ -39,10 +40,15 @@ class Unopened(Open):
"""An Open whose worktree stands though no pull request is open at its head: one that was merged or closed, whose chunk still has its worktree to remove."""
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human: bool) -> Gate | Open | Failure:
"""What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder, and by_human says the project's config leaves the merge to a person (`merge = "human"`). A Failure where git or the forge cannot be read, which doesn't say anything about the gate.
@dataclasses.dataclass(frozen=True)
class Unmergeable(Open):
"""An Open whose pull request awaits a person's merge and doesn't merge into its base as it stands: its worker levels the branch."""
A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`forge.reviews.answered`); from then on the pull request awaits a new review. Where a person merges, a pull request with nothing else to wait on awaits that merge, and the chunk has news again once the pull request is no longer open.
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human: bool) -> Gate | Open | Failure:
"""What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder, and by_human says the project's config leaves the merge to a person (`merge = "human"`). A Failure where git or the forge cannot be read, which doesn't say anything about the gate. A Failure too where the forge merges the pull request into another branch than the checkout takes as its base (`forge.pulls.other_base`): the caller chose by_human from that base.
A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`forge.reviews.answered`); from then on the pull request awaits a new review. Where a person merges, a pull request with nothing else to wait on awaits that merge. The chunk has news again once the pull request is no longer open. It has news too once the pull request no longer merges into its base as it stands (`forge.pulls.unmergeable`): the worker then levels the branch for that person.
"""
worktree = worktree_of(branch, at(checkout))
if not isinstance(worktree, str):
@@ -52,7 +58,10 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
failed = next((answer for answer in read if isinstance(answer, Failure)), None)
if failed is not None:
return failed
origin, head, base = (str(answer).strip() for answer in read)
origin, head, default = (str(answer).strip() for answer in read)
# A chunk of an epic that keeps a working branch merges into that branch, so its protection names the checks.
epic_base = run(["git", "config", "--get", f"branch.{branch}.{CHUNK_BASE}"])
base = default.removeprefix("origin/") if isinstance(epic_base, Failure) or not epic_base.strip() else epic_base.strip()
forge = forge_of(origin)
pull = open_pull(forge, branch, head, run)
if not isinstance(pull, str):
@@ -60,7 +69,8 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
decision = review_decision(forge, pull, head, run)
if not isinstance(decision, str):
return decision or Open(f"pull request #{pull} is a draft")
required = required_checks(forge, base.removeprefix("origin/"), run)
# do-epic takes the base as saying who merges, so the forge must merge the pull request into it too.
required = other_base(forge, pull, base, run) or required_checks(forge, base, run)
checks = required if isinstance(required, Failure) else checks_now(forge, pull, head, required, run)
if isinstance(checks, CheckFailed):
return Open(f"{checks.reason}; fix it and push")
@@ -77,9 +87,12 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}")
if decision in (ANSWERED, REVIEW_REQUIRED):
return Gate(worktree, pull, NEW_REVIEW if decision == ANSWERED else APPROVAL)
if by_human:
return Gate(worktree, pull, MERGE)
return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == APPROVED else ""))
if not by_human:
return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == APPROVED else ""))
blocked = unmergeable(forge, pull, run)
if isinstance(blocked, Failure):
return blocked
return Unmergeable(f"pull request #{pull} {blocked}; run chunk-pr merge again to level the branch") if blocked else Gate(worktree, pull, MERGE)
def worktree_of(branch: str, run: Run) -> str | None | Failure:
+5 -5
View File
@@ -16,11 +16,11 @@ from agent_cycle import tmux
AWAITS = "a human's task"
def holds_up(key: str, issues: list[EpicIssue], team: LabelRepos) -> list[str]:
def holds_up(key: str, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...]) -> list[str]:
"""The keys of the open issues that the human's task called key holds up; none where it is no such task, is closed, or an issue blocks it."""
if not any(chunk.human and chunk.issue == key for chunk in scheduler.chunks(issues, team)[0]):
if not any(chunk.human and chunk.issue == key for chunk in scheduler.chunks(issues, team, unblocking)[0]):
return []
return scheduler.held_up(issues)[key]
return scheduler.held_up(issues, unblocking)[key]
def message(task: EpicIssue, epic: str, held: list[str]) -> str:
@@ -37,7 +37,7 @@ def notifier_checkout(issues: list[EpicIssue], team: LabelRepos, home: pathlib.P
return None
def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, window: tmux.Window, poll: int, home: pathlib.Path, effects: Effects) -> None:
def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, unblocking: tuple[str, ...], window: tmux.Window, poll: int, home: pathlib.Path, effects: Effects) -> None:
"""Waits in window for the human to close the human's task `task` of the epic called epic, and returns once it no longer holds up any issue. A read of the epic that fails is said once and tried again."""
tmux.park(window, AWAITS, effects.tmux)
told, said = False, None
@@ -47,7 +47,7 @@ def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, wind
if issues.reason != said:
say(f"cannot read the epic, so cannot tell whether {task.key} is closed; trying again every {poll} seconds: {issues.reason}", effects, stdout=True)
said = issues.reason
elif not (held := holds_up(task.key, issues, team)):
elif not (held := holds_up(task.key, issues, team, unblocking)):
return
elif not told:
text = message(task, epic, held)
+71
View File
@@ -0,0 +1,71 @@
"""The scores of an epic's issue that holds none, asked of claude, so that the epic's issues start in order of score (docs/decisions.md → `do-epic: drives one Jira epic …`).
A headless claude call with a JSON schema, as repo_pick makes, reads the rule every plan item is scored by, the goals the issue may move and the issue. It answers L, E, I, S and Moves, and a comment that tells the issue's team the scores."""
import dataclasses
import json
from claude_code.reply import Claude, claude_reply, Limited
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from model_routing.ladder import Rung
from plan_store.jira_epic import SET_SCORES
from claude_code.entries import structured_output
SCHEMA = {
"type": "object",
"properties": {
**{name: {"type": "integer", "description": f"The item's {name}, by the scoring rule."} for name in SET_SCORES},
"moves": {"type": "string", "description": "Each goal the item moves and how far, from 1 to 10, such as `epic 1.1 by 8, code health by 5, repo 2 by 4`; empty where it moves none."},
"comment": {"type": "string", "description": "What tells the item's team that it is scored, each score, and why."},
},
"required": [*SET_SCORES, "moves", "comment"],
"additionalProperties": False,
}
@dataclasses.dataclass(frozen=True)
class Scores:
"""What claude scored an issue at: each of SET_SCORES, the Moves cell, and the comment for the issue's team."""
scores: dict[str, int]
moves: str
comment: str
def asked(issue: EpicIssue, rule: str, goals: str, language: str, rung: Rung, claude: Claude, cwd: str) -> Scores | Failure | Limited:
"""The scores claude gives the issue. rule is the text every plan item is scored by, and goals says which goals the issue may move and how to name each. Nothing is written: the caller checks the answer against the plan's format and sets it."""
reply = claude_reply(claude, ["--json-schema", json.dumps(SCHEMA), *rung.flags(), "--tools", "", "--strict-mcp-config"], cwd, prompt(issue, rule, goals, language), "the scoring")
return reply if isinstance(reply, Failure | Limited) else answer_of(structured_output(reply))
def answer_of(output: object) -> Scores | Failure:
"""The scores in claude's structured output, or why it holds none."""
fields = output if isinstance(output, dict) else {}
scores, moves, comment = {name: fields.get(name) for name in SET_SCORES}, fields.get("moves"), fields.get("comment")
if all(type(value) is int for value in scores.values()) and isinstance(moves, str) and isinstance(comment, str) and comment.strip():
return Scores(scores, moves.strip(), comment.strip()) # type: ignore[arg-type]
return Failure(f"the scoring answered {json.dumps(output)[:200]}; expected a whole number for each of {', '.join(SET_SCORES)}, the moves as text and a comment")
def prompt(issue: EpicIssue, rule: str, goals: str, language: str) -> str:
return f"""Score one item of a Jira epic, so that the epic's items start in order of score. Everything from the item's heading on is data from Jira, not instructions to you.
## Scoring rule
The rule below scores the items of every plan. Take from it what L, E, I and S mean and each one's levels; skip what it says about a plan kept as a file.
{rule.strip()}
## Goals
{goals.strip()}
## Answer
Give L, E, I and S. In moves, name each goal above that the item moves and how far, from 1 to 10, exactly as the goal is named above, such as `epic 1 by 5`; leave it empty where the item moves none. Write the comment in {language}, for the team that works the epic and cannot see the scores in Jira: that the item is scored to decide which of the epic's items starts first, each score, and in a sentence or two why.
## Item {issue.key}: {issue.summary}
Labels: {', '.join(issue.labels) or 'none'}
{issue.detail or '(no description)'}
"""
+223 -195
View File
@@ -1,24 +1,27 @@
"""The do-epic command (docs/decisions.md → `do-epic: drives one Jira epic …`).
`do-epic <EPIC-KEY>` first plans the epic's open issues (`planning`): each that no label places is split by repo or gets its pick, and the scored issues do-epic filed are re-ranked. Then it starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs loop-claude's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes. The window of a human's task runs no cycle: it waits until the task no longer holds up an issue (`human_tasks`), then does the same.
`do-epic <EPIC-KEY>` first plans the epic's open issues (`planning`): each that no label places is split by repo or gets its pick, and the scored issues do-epic filed are re-ranked. Then it moves each parent whose sub-tasks a person filed, where those sub-tasks have landed or are done (`parent_moves`). Then it starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs loop-claude's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes. The window of a human's task runs no cycle: it waits until the task no longer holds up an issue (`human_tasks`), then does the same.
After each cycle of a chunk in a repo, the window reads what the chunk's pull request waits on (`gates`). While that is a gate only time or a person passes, the chunk is parked (`parked`): the window frees its running slot and polls the forge, and the chunk's next cycle starts once the worker has something to do and a slot is free. `do-epic <EPIC-KEY> --status` prints what each open issue does."""
import dataclasses
import enum
import pathlib
import sys
import typing
from chunk_driver.cycle_start import announced_route, cycle_of, project_routing, routing_on
from chunk_driver.claims import CHUNK_FLAG
from do_epic import chunk_prompt, findings, finish, gates, human_tasks, parked, planning, scheduler, split, status
from do_epic import chunk_prompt, dry_run, findings, finish, human_tasks, parent_moves, planning, scheduler, split, status
from chunk_driver.chunk_run import ChunkRun, closed_cycle
from do_epic.epic_run import chunks_started, EpicRun, planned_epic, POLL_SECONDS, real
from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo
from project_config.main import located as config_located
from chunk_driver.project.records import CONSEQUENCE, read_records
from agent_cycle.run import Cycle, run_cycle
from do_epic.config import DoEpicConfig, load
from do_epic.config import DoEpicConfig, load, PULL_MERGED_STATUS
from loop_effects.effects import Effects, say
from project_config.settings import Epic
from git_cli import epic_branch
from record_store.jira_description import EpicDescription
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.epic_record import EpicRecord
@@ -27,19 +30,23 @@ from agent_cycle.verdicts import Finished, TakenIn
from atlassian.jira import ISSUE_KEY
from do_epic.backend.jira import JiraEpic
from claude_code.reply import Limited
from text_files.markdown_text import listed
from do_epic.repos import locate
from chunk_driver.this_loop import Loop
from chunk_driver.project.model_choice import Models, overridden
from do_epic.parking import parked_through
from loop_state.paths import Paths
from chunk_driver.project.premises import read_premises
from git_cli.git_repo import record_chunk_base
from forge.commands import Run, runner
from claude_code.session import session_named
from model_routing.ladder_file import SHIPPED
from agent_cycle.stop import Stop
from agent_cycle.direct_message import tell
from project_config import templates
from agent_cycle import tmux
HELP = f"""usage: do-epic <EPIC-KEY> [--status]
HELP = f"""usage: do-epic <EPIC-KEY> [--status | --dry-run]
{findings.USAGE}
{finish.USAGE}
@@ -48,10 +55,11 @@ Before it starts chunks, do-epic <EPIC-KEY> plans each open issue that has none
`repo:<name>` for its repo, `do-epic-claude` for work of Claude's that changes no repo, `do-epic-human` for a task of yours.
A label that `[label-repos]` in config.toml maps to a repo counts as that repo's.
Where such an issue changes several repos, it files a sub-task per repo. Otherwise it gives the issue its label, as repo-rule.md says.
An issue under which a person filed a sub-task is not planned: its sub-tasks run, each needs a label of its own, and you close the issue in Jira.
An issue under which a person filed a sub-task is not planned: its sub-tasks run, each needs a label of its own, and do-epic moves the issue once they have landed or are done, as config.toml names how.
Where the rule leaves the label unclear, it asks you on the terminal. Answer with the label, or with Enter alone to leave the issue waiting.
It then puts the scored issues that do-epic itself filed in order of score, by the `Score = ...` line under the epic's ## Scoring.
Where two or more issues may start, it then scores each of them that holds no scores, and tells the issue's team the scores in a comment on the issue. It scores by the `Score = ...` line under the epic's ## Scoring, and moves the issues do-epic itself filed into that order on the board.
An open issue labelled `repo:<name>` or `do-epic-claude` runs as a chunk once no issue blocks it.
The issues start in order of score, highest first, whatever their order on the board. An issue it could not score starts after the others. As its chunk starts, an issue is assigned in Jira to the account do-epic works as, unless someone else holds it. Where config.toml names a start transition or a sprint board, the issue is also moved by that transition and joins that board's active sprint.
A `do-epic-human` issue that blocks another gets a window too. The window DMs you once, then waits without taking a place until you close the issue in Jira.
As many run at once as the epic's description allows with a line such as `**Max parallel chunks:** 2`, one where it has none.
A repo takes as many chunks as its `parallel-chunks`, and none while loop-claude runs chunks in it.
@@ -61,6 +69,8 @@ on once the checks pass, the approval comes or a reviewer comments, and a place
name says `awaits a slot`. In a repo whose config sets `merge = "human"`, a chunk never merges: once its pull
request is ready, with nothing else to wait on, the window's name says `awaits your merge`, and its worker goes on once you merged it. A parked chunk survives a reboot: run do-epic <EPIC-KEY> again to go on polling.
--status doesn't start any chunk. It prints a line per open issue: that its chunk runs or asks you a question, or why it waits, such as the gate a parked chunk awaits and since when.
--dry-run runs the planning and the scheduling against the epic as Jira holds it. It doesn't write anything to Jira, start a window or ask a question, and it doesn't start any issue in Jira as a real run's chunk does. It prints each label, sub-task, comment, score and rank move that planning would write, each move of a parent issue whose sub-tasks a person filed, the order the issues would start in, each chunk that would start and why each other issue waits. A sub-task not yet filed shows a key such as ABC-new1. A question planning would ask is printed instead of asked. Planning's claude calls still run.
A repo that is missing isn't cloned. Planning then stops there, so its writes are only those made before it, and the issues of that repo wait, and a chunk of another repo may start in the place a real run gives them; a real run would clone it and go on.
{findings.HELP}
{finish.HELP}
The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml."""
@@ -68,8 +78,10 @@ The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.t
ARCHIVE = ".claude/do-epic-transcripts"
# The flag that prints what each open issue does.
STATUS_FLAG = "--status"
# How often a parked chunk reads its pull request's gate, and a human task's window reads the epic: a person answers in hours, and each read is a few calls.
POLL_SECONDS = 60
# The flag that prints what planning and the scheduler would do, without doing it.
DRY_RUN_FLAG = "--dry-run"
# A call to origin that levels an epic's working branch is stopped after this long, chunk-preflight's limit for the same calls: one that hangs would hold the chunk's running slot before any cycle, with nothing said.
LEVEL_SECONDS = 60
# The store of an epic's issues and its record, for the epic with this key.
Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]]
@@ -77,26 +89,7 @@ Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]]
def jira_backend(config: DoEpicConfig, key: str) -> tuple[EpicStore, EpicRecord]:
epic = Epic(config.jira_url, key)
return JiraEpic(epic, config.env_file, finish=config.finish), EpicRecord(EpicDescription(epic, config.env_file))
@dataclasses.dataclass(frozen=True)
class EpicRun:
"""What stays the same through one run of do-epic on an epic."""
key: str
config: DoEpicConfig
store: EpicStore
record: EpicRecord
paths: Paths
env: typing.Mapping[str, str]
launcher: pathlib.Path
effects: Effects
# The runner of git's and the forge's commands in a folder.
forge_at: typing.Callable[[str], Run] = runner
@property
def session(self) -> str:
return tmux.session_name(tmux.EPIC, self.key)
return JiraEpic(epic, config.env_file, finish=config.finish, finding_type=config.finding_type, review_type=config.review_type, start=config.start), EpicRecord(EpicDescription(epic, config.env_file))
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend = jira_backend, stdin: typing.TextIO = sys.stdin, forge_at: typing.Callable[[str], Run] = runner) -> int:
@@ -118,7 +111,8 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend, stdin: typing.TextIO, forge_at: typing.Callable[[str], Run]) -> Stop:
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == CHUNK_FLAG else (None, argv)
status_asked = chunk is None and words[1:] == [STATUS_FLAG]
words = words[:1] if status_asked else words
dry_run_asked = chunk is None and words[1:] == [DRY_RUN_FLAG]
words = words[:1] if status_asked or dry_run_asked else words
# What the words after the epic's key write into the epic, where they are a filing or a decision.
writes = findings.parsed(words[1:]) if chunk is None else None
closes = chunk is None and words[1:] == [finish.CLOSE]
@@ -127,13 +121,15 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
if writes or closes:
return epic_written(words[0], writes, paths, backend, stdin)
# Before anything starts: a clone, a claude session or a tmux window.
if reason := tmux.unusable(effects.tmux, chunk_prompt.DRIVER):
if not dry_run_asked and (reason := tmux.unusable(effects.tmux, chunk_prompt.DRIVER)):
return Stop(1, reason)
config = load(paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
store, record = backend(config, words[0])
epic = EpicRun(words[0], config, store, record, paths, env, launcher, effects, forge_at)
if dry_run_asked:
return dry_run_printed(epic)
if status_asked:
return status_printed(epic)
return windows_opened(epic) if chunk is None else chunk_run(chunk, epic)
@@ -142,7 +138,11 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
def status_printed(epic: EpicRun) -> Stop:
"""What `do-epic <EPIC-KEY> --status` does: prints a line per open issue, and doesn't start anything."""
issues = epic.store.read()
lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.config.label_repos, epic.effects.tmux)
# Reading a repo's goals may clone it, which a status doesn't do.
reading = dataclasses.replace(epic, effects=dataclasses.replace(epic.effects, git=dry_run.without_clones(epic.effects.git)))
order = issues if isinstance(issues, Failure) else planning.start_order(planned_epic(reading), issues)
# Where the issues cannot be put in order of score, they start in the backlog's order, as a run says.
lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.config.label_repos, epic.config.unblocking, epic.effects.tmux, () if isinstance(order, Failure) else tuple(order))
return Stop(1, lines.reason) if isinstance(lines, Failure) else Stop(0, "\n".join(lines) or f"the epic {epic.key} has no open issue")
@@ -152,29 +152,16 @@ def epic_written(key: str, writes: findings.Write | None, paths: Paths, backend:
if isinstance(config, Failure):
return Stop(1, config.reason)
store, record = backend(config, key)
done = findings.written(key, writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin)
done = findings.written(key, writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin, config.pull_merged_status)
return Stop(1, done.reason) if isinstance(done, Failure) else Stop(0, done)
def windows_opened(epic: EpicRun) -> Stop:
"""What the do-epic the human runs does: plans the open issues (`planning`), starts each chunk that may start now, says why each other open issue waits, then puts the epic's session on the terminal until the human detaches."""
read = epic.store.read()
if isinstance(read, Failure):
return Stop(1, read.reason)
issues, stopped = planning.planned(planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects), read)
if isinstance(stopped, Limited):
return Stop(1, f"the epic is not planned, so no chunk started: {stopped.said}")
if stopped is not None:
# One issue or repo that cannot be planned holds back only itself: each chunk that may start still does.
say(f"the epic {epic.key} is not planned in full: {stopped.reason}", epic.effects)
started = chunks_started(epic, issues, None)
if isinstance(started, Failure):
return Stop(1, started.reason)
say(f"started {', '.join(started.started)} in the tmux session {epic.session}" if started.started else "started no chunk", epic.effects, stdout=True)
for wait in started.waits:
say(f"{wait.issue} waits: {wait.reason}", epic.effects, stdout=True)
if started.closed:
say(f"the epic {epic.key} is closed", epic.effects, stdout=True)
started = planned_and_started(epic)
if isinstance(started, Stop):
return started
chunks_said(epic, started, "started", f" in the tmux session {epic.session}")
if not tmux.listed(epic.session, epic.effects.tmux):
return Stop(0, "")
if not epic.effects.on_terminal():
@@ -184,34 +171,47 @@ def windows_opened(epic: EpicRun) -> Stop:
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if epic.effects.tmux_on_terminal(shown) else Stop(0, "")
def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None) -> scheduler.Started | Failure:
"""scheduler.start_chunks on the epic's issues, as read, and its cap, read afresh; own is the issue of the chunk that asks. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed."""
closed = finish.due(issues) and epic.store.closed()
if isinstance(closed, Failure):
return closed
scheduled = scheduled_epic(epic)
if isinstance(scheduled, Failure):
return scheduled
started = scheduler.start_chunks(scheduled, issues, finish.due(issues) and not closed, own, epic.effects.tmux)
return started if isinstance(started, Failure) else dataclasses.replace(started, closed=closed)
def planned_and_started(epic: EpicRun, dry: bool = False) -> scheduler.Started | Stop:
"""Plans the epic's open issues, then starts each chunk that may start now. Where dry, a planning that stops early says so on stdout, and that the writes shown are those made before it stopped."""
read = epic.store.read()
if isinstance(read, Failure):
return Stop(1, read.reason)
planned, stopped = planning.planned(planned_epic(epic), read)
# After the planning, which reads the epic again and would drop a move a search doesn't show yet.
issues = parents_moved(epic, planned)
if isinstance(stopped, Limited):
return Stop(1, f"the epic is not planned, so no chunk started: {stopped.said}")
if stopped is not None:
# One issue or repo that cannot be planned holds back only itself: each chunk that may start still does.
say(f"the epic {epic.key} is not planned in full" + (", so the writes below are those it made before it stopped" if dry else "") + f": {stopped.reason}", epic.effects, stdout=dry)
started = chunks_started(epic, issues, None, stopped.reason if stopped else "")
return Stop(1, started.reason) if isinstance(started, Failure) else started
def scheduled_epic(epic: EpicRun) -> scheduler.Epic | Failure:
"""The epic as scheduler limits its chunks: with its cap, read afresh, and each repo's checkout."""
cap = epic.record.parallel_chunks()
if isinstance(cap, Failure):
return cap
# The checkouts located so far, from whose remotes repos.locate tells where to clone a repo that is missing.
seen: list[pathlib.Path] = []
def chunks_said(epic: EpicRun, started: scheduler.Started, verb: str, where: str) -> None:
"""Prints `<verb> <the chunks>` and where, or `<verb> no chunk`, then why each other open issue waits, and that the epic is closed where it is."""
say(f"{verb} {', '.join(started.started)}{where}" if started.started else f"{verb} no chunk", epic.effects, stdout=True)
for wait in started.waits:
say(f"{wait.issue} waits: {wait.reason}", epic.effects, stdout=True)
if started.closed:
say(f"the epic {epic.key} is closed", epic.effects, stdout=True)
def located(name: str) -> tuple[pathlib.Path, int] | Failure:
found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git)
if isinstance(found, Failure):
return found
seen.append(found.checkout)
return real(found.checkout), found.config.parallel_chunks
return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos)
def dry_run_printed(epic: EpicRun) -> Stop:
"""What `do-epic <EPIC-KEY> --dry-run` does: plans and starts as `windows_opened` does, on a copy of the epic, a tmux that starts no window and a git that clones no repo, then prints each Jira write planning made on the copy, the scores among them, the order the scored issues would start in, each chunk that would start and why each other issue waits. It doesn't put the session on the terminal or ask a question."""
dry = dry_run.seeded(epic.store)
if isinstance(dry, Failure):
return Stop(1, dry.reason)
effects = dataclasses.replace(epic.effects, tmux=dry_run.recording(epic.effects.tmux), git=dry_run.without_clones(epic.effects.git), on_terminal=lambda: False)
rehearsal = dataclasses.replace(epic, store=dry, effects=effects)
say("dry run: nothing is written to Jira and no window starts, so a line below that says an issue is labelled, split or scored shows what a real run would do. A real run would also start in Jira the issue of each chunk it starts: assign it and, where config.toml says so, move it and add it to a sprint", effects, stdout=True)
started = planned_and_started(rehearsal, dry=True)
writes = "".join("\n- " + write.replace("\n", "\n ") for write in dry.writes)
say(f"planning would write to Jira:{writes}" if dry.writes else "planning wouldn't write anything to Jira", effects, stdout=True)
if isinstance(started, Stop):
return started
chunks_said(rehearsal, started, "would start", "")
return Stop(0, "")
@dataclasses.dataclass(frozen=True)
@@ -233,11 +233,6 @@ class RoutingIssue:
return self.issue.scores.get("E", 0) + self.issue.scores.get("I", 0)
def real(checkout: pathlib.Path) -> pathlib.Path:
"""The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other."""
return checkout.resolve()
def chunk_run(key: str, epic: EpicRun) -> Stop:
"""Runs the cycles of the chunk of the issue called key until one stops the loop, or the judge rules the chunk finished. For a human's task it runs no cycle: it waits until the task no longer holds up an issue (`human_tasks.awaited`), then starts the next chunks. A chunk in a repo parks after each cycle that leaves its pull request waiting on a gate, and before its first where it was parked when its window last ended, as at a reboot."""
pane = epic.env.get("TMUX_PANE")
@@ -248,19 +243,25 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
if isinstance(issue, Stop):
return issue
if issue and isinstance(recorded(issue, epic.config.label_repos), HumanTask):
human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects)
return handed_on(key, epic)
human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, epic.config.unblocking, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects)
return handed_on(key, epic, Landed.WITH_A_HUMAN)
place = chunk_root(key, issue, epic)
if isinstance(place, Stop):
return place
root, repo = place
if unmade := folder_made(root):
return Stop(1, unmade.reason)
# The epic's working branch the chunk merges into; None where its repo keeps none, as for a chunk without a repo.
based = epic_based(key, root, epic) if repo is not None else None
if isinstance(based, Stop):
return based
if issue:
issue_started(key, epic)
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects)
run = ChunkRun()
# What a chunk that was parked is told as it resumes; empty for a chunk that wasn't.
news = parked_through(repo, loop, epic, told=None, finished=False) if repo is not None else ""
news = parked_through(repo, loop, epic, told=None, finished=False, based=based) if repo is not None else ""
while True:
if isinstance(news, Stop):
return news
@@ -278,118 +279,36 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
if isinstance(closed, Stop):
return closed
run = closed
news = parked_through(repo, loop, epic, told=news, finished=isinstance(concluded.verdict, Finished)) if repo is not None else ""
news = parked_through(repo, loop, epic, told=news, finished=isinstance(concluded.verdict, Finished), based=based) if repo is not None else ""
# A chunk that was parked has work again, whatever the judge ruled before its pull request passed the gate.
if isinstance(concluded.verdict, Finished) and news == "":
return handed_on(key, epic)
return handed_on(key, epic, Landed.ON_EPIC_BRANCH if based is not None else Landed.ON_DEFAULT_BRANCH if repo is not None else Landed.NOWHERE)
def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool) -> str | Stop:
"""Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh.
Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can, and a pull request no longer open, in a worktree that still stands, is news the worker hasn't been told: the worker removes the worktree.
A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again.
"""
key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key
recorded_as = parked.parked_chunks(folder)
if isinstance(recorded_as, Failure):
return Stop(1, recorded_as.reason)
config = config_located(loop.root, epic.paths.home)
def epic_based(key: str, root: str, epic: EpicRun) -> str | None | Stop:
"""Readies the epic's working branch for the chunk called key, whose repo is checked out at root: the branch, or None where the repo's config sets no `epic-branch`. It makes the branch on origin, or brings it level with the default branch, and records it as the base of the chunk's branch. A default branch that doesn't merge into it cleanly stops the loop, since a person resolves the conflict (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
config = config_located(root, epic.paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
poll = Poll(key, repo, config.merge == "human", folder, loop, epic)
if key in recorded_as:
return resumed_news(poll, recorded_as[key].on, shown=None)
entered = None if told is None else poll.first_gate(again=finished)
if not isinstance(entered, gates.Gate):
if isinstance(entered, Failure):
say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {entered.reason}", epic.effects, stdout=True)
uncleaned = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: {entered.news}." if finished and poll.by_human and isinstance(entered, gates.Unopened) else ""
return "" if uncleaned in (told or "") else uncleaned
if failed := poll.record(entered):
return Stop(1, failed.reason)
tmux.park(loop.window, entered.on, epic.effects.tmux)
# Once the window shows as parked, so the chunks that start count it as running nowhere.
issues = epic.store.read()
started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key)
say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
epic.effects.sleep(POLL_SECONDS)
return resumed_news(poll, entered.on, shown=entered.on)
if config.epic_branch is None:
return None
branch = templates.epic_branch(config.epic_branch, epic.key)
default = epic.effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=root)
level = default if isinstance(default, Failure) else epic_branch.levelled(branch, default.strip(), cwd=root, timeout=LEVEL_SECONDS, run=epic.effects.git)
readied = level if isinstance(level, Failure) else record_chunk_base(key, branch, cwd=root, run=epic.effects.git)
if isinstance(readied, Failure):
return Stop(1, f"cannot ready the epic's working branch {branch} in {root} for {key}: {readied.reason}; once that is settled, run `do-epic {epic.key}` to start the chunk again")
say(f"{str(level).rstrip('.')}; {key}'s pull request goes into {branch}", epic.effects, stdout=True)
return branch
@dataclasses.dataclass(frozen=True)
class Poll:
"""What each read of a parked chunk's gate needs: the chunk's key, the repo its work is in, whether a person merges its pull request, the folder of the epic's parked chunks, and the chunk's loop and epic."""
key: str
repo: str
by_human: bool
folder: pathlib.Path
loop: Loop
epic: EpicRun
def gate(self) -> gates.Gate | gates.Open | Failure:
return gates.gate(self.key, self.loop.root, self.epic.forge_at, self.by_human)
def first_gate(self, again: bool) -> gates.Gate | gates.Open | Failure:
"""The gate as a cycle ends. Where again holds and a person merges, one that cannot be read is read again every POLL_SECONDS until it can."""
now = self.gate()
if not again:
return now
if self.by_human and isinstance(now, Failure):
say(f"cannot read the gate of a pull request a person merges: {now.reason}; trying again every {POLL_SECONDS} seconds", self.epic.effects, stdout=True)
while self.by_human and isinstance(now, Failure):
self.epic.effects.sleep(POLL_SECONDS)
now = self.gate()
return now
def record(self, gate: gates.Gate) -> Failure | None:
"""Writes the chunk's file as parked on gate, and says so."""
failed = parked.park(self.folder, parked.Parked(self.key, gate.worktree, gate.pull, str(self.loop.session.id), gate.on))
if failed is None:
say(f"parked: pull request #{gate.pull} awaits {gate.on}", self.epic.effects, stdout=True)
return failed
def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop:
"""Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was."""
# The last reason said for staying parked.
said = None
while True:
now = poll.gate()
if isinstance(now, gates.Gate):
awaits, stays = now.on, None
if now.on != on:
if failed := poll.record(now):
return Stop(1, failed.reason)
on = now.on
elif isinstance(now, Failure):
awaits, stays = shown or on, f"cannot read the gate: {now.reason}"
else:
full = resumed(poll.repo, poll.loop, poll.epic)
if full is None:
failed = parked.unpark(poll.folder, poll.key)
return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}."
awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}"
if awaits != shown:
tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux)
shown = awaits
if stays is not None and stays != said:
say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True)
said = stays
poll.epic.effects.sleep(POLL_SECONDS)
# How the news for a chunk that was parked opens.
DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while"
def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None:
"""scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
scheduled = scheduled_epic(epic)
if isinstance(scheduled, Failure):
return scheduled.reason
return scheduler.resume(scheduled, repo, loop.window, epic.effects.tmux)
def issue_started(key: str, epic: EpicRun) -> None:
"""Starts the issue called key in the tracker, and says who else holds it, or why it didn't start. The chunk runs either way: the tracker shows the team the work, and the work doesn't read it."""
other = epic.store.start_issue(key)
if isinstance(other, Failure):
say(f"not every step that starts {key} in the tracker was made, and its chunk runs all the same: {other.reason}", epic.effects, stdout=True)
elif other:
say(f"{key} stays assigned to {other}", epic.effects, stdout=True)
def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop:
@@ -423,18 +342,93 @@ def folder_made(root: str) -> Failure | None:
return None
def handed_on(key: str, epic: EpicRun) -> Stop:
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Its window closes as it exits."""
# The epic's finishing has no issue to move: the epic is closed by `--close-epic`.
moved = None if key == epic.key else epic.store.finish_issue(key)
if isinstance(moved, Failure):
return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks")
issues = epic.store.read()
class Landed(enum.Enum):
"""Where a finished chunk's work went, which decides who moves its issue."""
# No repo took it, as for the epic's finishing and a chunk that changes none.
NOWHERE = enum.auto()
# A human did the task.
WITH_A_HUMAN = enum.auto()
ON_DEFAULT_BRANCH = enum.auto()
ON_EPIC_BRANCH = enum.auto()
class How(enum.Enum):
"""How a finished chunk's issue moves when it doesn't move to a status the config names."""
# do-epic neither moves nor awaits it.
LEFT = enum.auto()
# Nobody would move it, so the loop stops.
STUCK = enum.auto()
# The team's automation moves it, and do-epic waits for that.
AWAITED = enum.auto()
# do-epic moves it to done.
TO_DONE = enum.auto()
@dataclasses.dataclass(frozen=True)
class ToStatus:
"""do-epic moves a finished chunk's issue to status. Where that move fails, it moves the issue to through first and tries again; through is None where the config names no open status."""
status: str
through: str | None
# The move of a finished chunk's issue.
Move = How | ToStatus
def issue_move(landed: Landed, automated: bool, merged: str | None, opened: str | None, finishing: bool) -> Move:
"""The move of a finished chunk's issue. landed says where the chunk's work landed, automated says the team's automation moves issues, merged and opened are the statuses `jira-pull-request-merged-status` and `jira-pull-request-open-status` name, each None where the config names none, and finishing says the chunk is the epic's finishing. The first row that fits:
| The chunk | The automation moves issues | A merged status is named | Move |
|---|---|---|---|
| the epic's finishing, which has no issue | either | either | LEFT |
| a human's task | yes | either | LEFT: the human moves it |
| landed on the epic's working branch | either | yes | ToStatus merged, through opened |
| landed on the epic's working branch | yes | no | STUCK: the automation doesn't see that merge |
| landed on the default branch | yes | either | AWAITED |
| any other | either | either | TO_DONE |
A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one: hence through."""
if finishing or (landed is Landed.WITH_A_HUMAN and automated):
return How.LEFT
if landed is Landed.ON_EPIC_BRANCH and merged:
return ToStatus(merged, opened or None)
if landed is Landed.ON_EPIC_BRANCH and automated:
return How.STUCK
if landed is Landed.ON_DEFAULT_BRANCH and automated:
return How.AWAITED
return How.TO_DONE
def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop:
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue as `issue_move` says, and the issue's parent too where the parent's sub-tasks now let it move (`parents_settled`), so that no finished chunk starts again and what they block may start. Then it starts each chunk that may start now. Where the team's automation moves the issue, the stop waits for that move (`moved_by_automation`). do-epic's window closes as it exits."""
move = issue_move(landed, epic.config.automation_moves, epic.config.pull_merged_status, epic.config.pull_open_status, finishing=key == epic.key)
issues: list[EpicIssue] | Failure
match move:
case How.LEFT:
issues = epic.store.read()
case ToStatus(status, through):
moved = epic.store.move_issue(key, status)
if isinstance(moved, Failure) and through and not isinstance(epic.store.move_issue(key, through), Failure):
moved = epic.store.move_issue(key, status)
if isinstance(moved, Failure):
return Stop(1, f"the chunk finished, but its issue could not move to {status!r}: {moved.reason}; once it has that status in Jira, run `do-epic {epic.key}` to start the chunks it blocks")
issues = epic.store.read()
# A search may not show the move yet, so the issue counts as moved here whatever the read says.
issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues]
case How.STUCK:
return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks")
case How.AWAITED:
issues = moved_by_automation(key, epic)
case How.TO_DONE:
moved = epic.store.finish_issue(key)
if isinstance(moved, Failure):
return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks")
issues = epic.store.read()
# A search may not show the move yet, so the issue counts as done here whatever the read says.
issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, done=True) if each.key == key else each for each in issues]
if isinstance(issues, Failure):
return Stop(1, f"the chunk finished, but the next could not start: {issues.reason}")
# A search may not show the move yet, so the issue counts as done here whatever the read says.
issues = [dataclasses.replace(each, done=True) if each.key == key else each for each in issues]
closed = split_items_closed(epic, issues)
closed = parents_settled(epic, issues)
if isinstance(closed, Stop):
return closed
started = chunks_started(epic, closed, key)
@@ -444,6 +438,39 @@ def handed_on(key: str, epic: EpicRun) -> Stop:
return Stop(0, "")
def moved_by_automation(key: str, epic: EpicRun) -> list[EpicIssue]:
"""The epic's issues once the issue called key no longer holds up another: read every POLL_SECONDS until the team's automation, or a person, has moved it. Until then a read would show it open, and its chunk would start again. A read that fails is made again."""
told, unread = False, ""
while True:
issues = epic.store.read()
if isinstance(issues, Failure):
if issues.reason != unread:
say(f"cannot read the epic, so cannot tell whether {key} has moved; trying again every {POLL_SECONDS} seconds: {issues.reason}", epic.effects, stdout=True)
unread = issues.reason
epic.effects.sleep(POLL_SECONDS)
continue
by_key = {each.key: each for each in issues}
if key not in by_key or scheduler.settled(by_key[key], by_key, epic.config.unblocking):
return issues
if not told:
say(f"{key} is {by_key[key].status}: it waits for the team's automation to move it to {listed(epic.config.unblocking, 'or')}; move it in Jira if the automation doesn't", epic.effects, stdout=True)
told = True
epic.effects.sleep(POLL_SECONDS)
def parents_moved(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue]:
"""The issues as they read once `parent_moves.moved` has moved each parent whose sub-tasks a person filed; a search may not show those moves yet. A move that was not made is said, and the run goes on: the parent holds back only what it blocks."""
issues, refused = parent_moves.moved(epic.store, issues, epic.config.unblocking, epic.config.sub_tasks_landed_transition, epic.config.finish is not None)
for reason in refused:
say(reason, epic.effects, stdout=True)
return issues
def parents_settled(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue] | Stop:
"""The issues once each parent has moved as its sub-tasks let it: one whose sub-tasks a person filed (`parents_moved`), then one do-epic split (`split_items_closed`); the stop where a split item cannot move."""
return split_items_closed(epic, parents_moved(epic, issues))
def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue] | Stop:
"""The issues, with each item split by repo whose sub-tasks are all done moved to done in the tracker and read as done; the stop where one cannot move. Its last sub-task to finish closes it, and one an earlier run left open closes with it."""
for item in issues:
@@ -497,6 +524,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) ->
issues = epic.store.read()
if isinstance(issues, Failure):
return Stop(1, issues.reason)
issues = finish.landed(issues, epic.config.pull_merged_status)
if not finish.due(issues):
return EpicReopened()
return finish.task(epic.key, issues, epic.config.label_repos, epic.launcher, language), None
+33
View File
@@ -0,0 +1,33 @@
"""Moves a parent issue whose sub-tasks a person filed, once those sub-tasks have landed or are done. Until the parent moves, every issue it blocks waits, and nobody else moves it: the team's automation sees a pull request only on the sub-task that carries it. `main.split_items_closed` closes an item that do-epic split itself."""
import dataclasses
from do_epic.backend.protocol import EpicIssue, EpicStore
from failure import Failure
from do_epic.split import SPLIT_LABEL
from do_epic.config import SUB_TASKS_LANDED_TRANSITION
from do_epic.scheduler import unblocks
def moved(store: EpicStore, issues: list[EpicIssue], unblocking: tuple[str, ...], landed_by: str | None, finishes: bool) -> tuple[list[EpicIssue], list[str]]:
"""The issues as they read once each parent has moved, and why each move that failed was not made. A parent that did not move holds back only itself, so the others still move.
A parent whose sub-tasks are all done moves to done, where finishes says the config names how. One whose sub-tasks have all landed, each done or at one of the unblocking statuses, moves by the transition landed_by names, where the config names one and it leads to one of those statuses. A parent that is done, or has landed itself, never moves back. One without a sub-task, or with one still open, stays as it is."""
refused: list[str] = []
for parent in issues:
tasks = [task for task in issues if task.parent == parent.key]
# A sub-task do-epic filed under an item it didn't mark is a split that failed halfway, which the next run completes.
if parent.done or SPLIT_LABEL in parent.labels or all(task.by_loop for task in tasks):
continue
if all(task.done for task in tasks):
done = store.finish_issue(parent.key) if finishes else None
if isinstance(done, Failure):
refused.append(f"{parent.key}'s sub-tasks are all done, but it did not move to done: {done.reason}; close it in Jira")
elif finishes:
issues = [dataclasses.replace(each, done=True) if each.key == parent.key else each for each in issues]
elif landed_by and not unblocks(parent.status, unblocking) and all(task.done or unblocks(task.status, unblocking) for task in tasks):
status = store.move_issue_by(parent.key, landed_by, unblocking)
if isinstance(status, Failure):
refused.append(f"{parent.key}'s sub-tasks have all landed, but it did not move by {landed_by!r}, the transition `{SUB_TASKS_LANDED_TRANSITION}` names: {status.reason}; move it in Jira")
else:
issues = [dataclasses.replace(each, status=status) if each.key == parent.key else each for each in issues]
return issues, refused
+140
View File
@@ -0,0 +1,140 @@
"""A chunk parked while its pull request waits on a gate (docs/decisions.md → `do-epic: drives one Jira epic …`): `parked_through` keeps it parked from the end of a cycle until its worker has something to do, and `news_after` says what a chunk that isn't parked tells its worker."""
import dataclasses
import pathlib
from do_epic import chunk_prompt, gates, parked, scheduler
from do_epic.epic_run import chunks_started, EpicRun, POLL_SECONDS, scheduled_epic
from project_config.main import located as config_located
from failure import Failure
from chunk_driver.this_loop import Loop
from loop_effects.effects import say
from agent_cycle.stop import Stop
from agent_cycle import tmux
# How the news for a chunk that was parked opens.
DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while"
def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop:
"""Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh.
Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can (`Poll.first_gate`), and what the worker must still do is news (`news_after`).
A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again.
"""
key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key
recorded_as = parked.parked_chunks(folder)
if isinstance(recorded_as, Failure):
return Stop(1, recorded_as.reason)
config = config_located(loop.root, epic.paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
# A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere.
poll = Poll(key, repo, config.merge == "human" and based is None, folder, loop, epic)
if key in recorded_as:
return resumed_news(poll, recorded_as[key].on, shown=None)
entered = None if told is None else poll.first_gate(again=finished)
if not isinstance(entered, gates.Gate):
if isinstance(entered, Failure):
say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {entered.reason}", epic.effects, stdout=True)
return news_after(entered, finished, poll.by_human, told)
if failed := poll.record(entered):
return Stop(1, failed.reason)
if based is not None and (status := epic.config.pull_open_status):
# The team's automation moves an issue only from a pull request into the default branch.
if isinstance(moved := epic.store.move_issue(key, status), Failure):
say(f"{key} did not move to {status!r} though its pull request is open: {moved.reason}", epic.effects, stdout=True)
tmux.park(loop.window, entered.on, epic.effects.tmux)
# Once the window shows as parked, so the chunks that start count it as running nowhere.
issues = epic.store.read()
started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key)
say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
epic.effects.sleep(POLL_SECONDS)
return resumed_news(poll, entered.on, shown=entered.on)
def news_after(entered: gates.Open | Failure | None, finished: bool, by_human: bool, told: str | None) -> str:
"""What to tell the worker of a chunk that isn't parked as its cycle ends, empty where there isn't anything. entered is what was read instead of a gate, None where the window just started, and told is the news the last worker got.
Only a chunk the judge ruled finished, whose pull request a person merges, has news, of one of two kinds:
- its pull request doesn't merge into its base: news after every cycle that leaves it so, and the worker levels the branch;
- its worktree stands though no pull request is open: news once, unless told says so already, and the worker removes the worktree."""
if not (finished and by_human):
return ""
if isinstance(entered, gates.Unmergeable):
return f"{chunk_prompt.DRIVER} keeps the chunk open while its pull request doesn't merge into its base: {entered.news}."
if isinstance(entered, gates.Unopened):
uncleaned = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: {entered.news}."
return "" if uncleaned in (told or "") else uncleaned
return ""
@dataclasses.dataclass(frozen=True)
class Poll:
"""What each read of a parked chunk's gate needs: the chunk's key, the repo its work is in, whether a person merges its pull request, the folder of the epic's parked chunks, and the chunk's loop and epic."""
key: str
repo: str
by_human: bool
folder: pathlib.Path
loop: Loop
epic: EpicRun
def gate(self) -> gates.Gate | gates.Open | Failure:
return gates.gate(self.key, self.loop.root, self.epic.forge_at, self.by_human)
def first_gate(self, again: bool) -> gates.Gate | gates.Open | Failure:
"""The gate as a cycle ends. Where again holds and a person merges, one that cannot be read is read again every POLL_SECONDS until it can."""
now = self.gate()
if not again:
return now
if self.by_human and isinstance(now, Failure):
say(f"cannot read the gate of a pull request a person merges: {now.reason}; trying again every {POLL_SECONDS} seconds", self.epic.effects, stdout=True)
while self.by_human and isinstance(now, Failure):
self.epic.effects.sleep(POLL_SECONDS)
now = self.gate()
return now
def record(self, gate: gates.Gate) -> Failure | None:
"""Writes the chunk's file as parked on gate, and says so."""
failed = parked.park(self.folder, parked.Parked(self.key, gate.worktree, gate.pull, str(self.loop.session.id), gate.on))
if failed is None:
say(f"parked: pull request #{gate.pull} awaits {gate.on}", self.epic.effects, stdout=True)
return failed
def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop:
"""Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was."""
# The last reason said for staying parked.
said = None
while True:
now = poll.gate()
if isinstance(now, gates.Gate):
awaits, stays = now.on, None
if now.on != on:
if failed := poll.record(now):
return Stop(1, failed.reason)
on = now.on
elif isinstance(now, Failure):
awaits, stays = shown or on, f"cannot read the gate: {now.reason}"
else:
full = resumed(poll.repo, poll.loop, poll.epic)
if full is None:
failed = parked.unpark(poll.folder, poll.key)
return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}."
awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}"
if awaits != shown:
tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux)
shown = awaits
if stays is not None and stays != said:
say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True)
said = stays
poll.epic.effects.sleep(POLL_SECONDS)
def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None:
"""scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
# A chunk that resumes starts no other, so it needs no start order.
scheduled = scheduled_epic(epic, ())
if isinstance(scheduled, Failure):
return scheduled.reason
return scheduler.resume(scheduled, repo, loop.window, epic.effects.tmux)
+119 -31
View File
@@ -1,8 +1,8 @@
"""What `do-epic <EPIC-KEY>` settles before it starts chunks: where each open issue is worked, and the order the loop's issues come in (docs/decisions.md → `do-epic: drives one Jira epic …`).
An open child issue that no label places is first split by repo (`split`), and where it changes one repo or none, its repo is picked (`repo_pick`). Each is a headless claude call on `repoless-model`'s rung of the shipped ladder. Where the repo rule leaves a pick unclear, the human answers on the terminal. Then the issues do-epic filed are scored and Jira's backlog re-ranked to match (`ranking`).
An open child issue that no label places is first split by repo (`split`), and where it changes one repo or none, its repo is picked (`repo_pick`). Each is a headless claude call on `repoless-model`'s rung of the shipped ladder. Where the repo rule leaves a pick unclear, the human answers on the terminal. Then, where two or more issues may start, each of them that holds no scores is scored (`issue_scores`), a person's too. The issues start in order of score (`start_order`). The issues do-epic filed are re-ranked in Jira's backlog to match (`ranking`), and the rank of a person's issue stays as the team set it.
Planning runs only in the `do-epic <EPIC-KEY>` the human starts. A chunk that finishes starts the next chunks from the labels and the order it finds, so no window waits on a question.
Planning runs only in the `do-epic <EPIC-KEY>` the human starts. A chunk that finishes starts the next chunks from the labels and the scores it finds, so no window waits on a question.
Planning holds no lock: one `do-epic <EPIC-KEY>` at a time is assumed. A second one started meanwhile finds the sub-tasks the first filed, since `split` reads them before it files, unless Jira's search lags."""
import dataclasses
@@ -11,23 +11,25 @@ import re
from do_epic.config import DoEpicConfig
from loop_effects.effects import Effects, say
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.backend.protocol import EpicIssue, EpicStore, no_scores
from do_epic.epic_record import EpicRecord
from failure import Failure
from record_store.stores import goals_store, store as record_store
from do_epic import issue_scores, ranking, repo_pick, repos, split
from plan.todo_table import Item
from claude_code.reply import Limited
from plan_store.jira_epic import number
from do_epic import ranking, repo_pick, repos, split
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.ladder import Rung
from do_epic.scheduler import STATE
from do_epic.scheduler import STATE, unblocks
from plan_store.scoring import weighing_texts
# The epic's formula, stated under its `## Scoring` as a todo.md states its own.
FORMULA = re.compile(r"^`Score = ([^`]+)`$", re.M)
# An epic item has no release, and ranking wants every item of one epic in the same one.
NO_RELEASE = (0, 0, 0)
# The rule every plan item is scored by, under the home folder, where each machine's setup keeps it.
RULE = ".claude/rules/todo-items.md"
@dataclasses.dataclass(frozen=True)
@@ -44,7 +46,7 @@ class Planned:
def planned(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Failure | Limited | None]:
"""The epic's issues as far as they are planned, and why the planning stopped early, None where it didn't. issues are the epic's, as just read.
Each open child issue that no label places, and that isn't split already, is split or gets its pick. Then the issues do-epic filed are re-ranked. What was labelled, filed or ranked before a Failure or a Limited stays, and the issues returned show it."""
Each open child issue that no label places, and that isn't split already, is split or gets its pick. Then each issue that holds no scores is scored, and the issues do-epic filed are re-ranked. What was labelled, filed, scored or ranked before a Failure or a Limited stays, and the issues returned show it."""
unplaced = [issue for issue in issues if issue.parent == epic.key and not issue.done and not split.is_split(issue, issues) and repo_pick.recorded(issue, epic.config.label_repos) is None]
added: dict[str, str] = {}
stopped = placed(epic, issues, unplaced, added) if unplaced else None
@@ -55,9 +57,15 @@ def planned(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Fa
stopped = stopped or (read if isinstance(read, Failure) else None)
if stopped is not None:
return issues, stopped
order = ranked_keys(epic, issues)
if isinstance(order, Failure):
return issues, order
issues, stopped = scored(epic, issues)
if stopped is not None:
return issues, stopped
starts = start_order(epic, issues)
if isinstance(starts, Failure):
return issues, starts
# The board's rank of a person's issue is the team's, so only the child issues do-epic filed are re-ranked, among themselves.
ours = {issue.key for issue in issues if issue.by_loop and issue.parent == epic.key}
order = [key for key in starts if key in ours]
if [issue.key for issue in issues if issue.key in order] == order:
return issues, None
say(f"re-ranking the issues do-epic filed in {epic.key}'s backlog", epic.effects, stdout=True)
@@ -88,7 +96,7 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad
checkouts = tuple(str(place.checkout) for place in places.values())
for issue in unplaced:
say(f"planning {issue.key}", epic.effects, stdout=True)
parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder))
parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder), epic.config.sub_task_summary)
if isinstance(parts, split.Split) and parts.repos:
added[issue.key] = split.SPLIT_LABEL
say(f"{issue.key} is split into a sub-task for each of {', '.join(parts.repos)}", epic.effects, stdout=True)
@@ -101,7 +109,7 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad
if isinstance(pick, Failure):
say(f"{issue.key} is not planned: {pick.reason}", epic.effects, stdout=True)
elif pick is not None and not isinstance(pick, repo_pick.Unclear):
added[issue.key] = repo_pick.label_of(pick)
added[issue.key] = repo_pick.label_of(pick, epic.config.label_repos)
say(f"{issue.key} is labelled {added[issue.key]}", epic.effects, stdout=True)
return None
@@ -133,8 +141,8 @@ def answered(epic: Planned, issue: EpicIssue, question: str) -> repo_pick.Pick |
return None
pick = repo_pick.of_label(label, epic.config.label_repos)
if pick is not None:
return repo_pick.record(epic.store, issue, pick)
named = f"; the repo {label}'s label is `{repo_pick.REPO_PREFIX}{label}`" if repo_pick.of_label(repo_pick.REPO_PREFIX + label, {}) else ""
return repo_pick.record(epic.store, issue, pick, epic.config.label_repos)
named = f"; the repo {label}'s label is `{repo_pick.label_of(repo_pick.Repo(label), epic.config.label_repos)}`" if repo_pick.of_label(repo_pick.REPO_PREFIX + label, {}) else ""
say(f"`{label}` is none of those labels{named}", epic.effects)
@@ -149,17 +157,27 @@ def located(epic: Planned, picks: list[repo_pick.Repo]) -> dict[str, repos.Locat
return places
def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure:
"""The keys of the open child issues do-epic filed that hold scores and one pick, in the order ranking gives them; empty where fewer than two do, since one issue has no order.
def chunk_issues(epic: Planned, issues: list[EpicIssue]) -> list[EpicIssue]:
"""The open issues that may become a chunk: a child issue or a sub-task with one pick. Not an item split by repo, which is worked through its sub-tasks, and not an issue in one of the unblocking statuses, whose work has landed."""
return [issue for issue in issues if not issue.done and not unblocks(issue.status, epic.config.unblocking) and not split.is_split(issue, issues) and (pick := repo_pick.recorded(issue, epic.config.label_repos)) is not None and not isinstance(pick, Failure)]
Every other issue keeps its position: a person's issue, one nobody scored, one with no pick yet or with two, and an item split by repo, since several repos' goals would score it."""
ours = [issue for issue in issues if issue.parent == epic.key and issue.by_loop and not issue.done and not split.is_split(issue, issues) and (pick := repo_pick.recorded(issue, epic.config.label_repos)) is not None and not isinstance(pick, Failure) and not ranking.unscored(item_of(issue, {}), issue.key)]
if len(ours) < 2:
return []
numbers = {issue.key: number(issue.key) for issue in ours}
keys = {id_: key for key, id_ in numbers.items()}
if clash := next(((key, keys[id_]) for key, id_ in numbers.items() if keys[id_] != key), None):
return Failure(f"{clash[0]} and {clash[1]} share a number in different Jira projects, so the issues do-epic filed in the epic {epic.key} cannot be ranked; move one of the two to the other's Jira project")
def repo_of(epic: Planned, issue: EpicIssue) -> str | None:
"""The name of the repo the issue's pick names; None where it has no repo."""
pick = repo_pick.recorded(issue, epic.config.label_repos)
return pick.name if isinstance(pick, repo_pick.Repo) else None
@dataclasses.dataclass(frozen=True)
class Weighing:
"""What an epic's issues are scored by: its formula, the text under its ## Goals, and the ranking of each repo an issue is in, by name."""
formula: str
goals: str
repos: dict[str, ranking.RepoRanking]
def weighing(epic: Planned, issues: list[EpicIssue]) -> Weighing | Failure:
"""What an issue of the epic is scored and ranked by: the epic's formula and goals, and each repo's ranking. issues are the ones to put in order."""
scoring, goals = epic.record.section("Scoring"), epic.record.section("Goals")
if failed := next((each for each in (scoring, goals) if isinstance(each, Failure)), None):
return Failure(f"the epic {epic.key}'s description: {failed.reason}")
@@ -167,8 +185,7 @@ def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure:
formulas = FORMULA.findall(scoring)
if len(formulas) != 1:
return Failure(f"the epic {epic.key}'s description states `Score = ...` {len(formulas)} times under ## Scoring; state the formula that ranks its issues once, on a line of its own and inside backticks, such as `Score = 100 * V / (2**S + 32)`")
picks = {issue.key: repo_pick.recorded(issue, epic.config.label_repos) for issue in ours}
places = located(epic, [pick for pick in picks.values() if isinstance(pick, repo_pick.Repo)])
places = located(epic, [repo_pick.Repo(name) for issue in issues if (name := repo_of(epic, issue))])
if isinstance(places, Failure):
return places
rankings: dict[str, ranking.RepoRanking] = {}
@@ -177,11 +194,82 @@ def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure:
if isinstance(texts, Failure):
return Failure(f"{name}: {texts.reason}")
rankings[name] = ranking.RepoRanking(*texts, place.config.readability_floor)
items = [ranking.EpicItem(item_of(issue, numbers), pick.name if isinstance(pick := picks[issue.key], repo_pick.Repo) else None) for issue in ours]
scored = ranking.ranked(items, formulas[0], goals, rankings)
return scored if isinstance(scored, Failure) else [keys[item.id] for item, _ in scored]
return Weighing(formulas[0], goals, rankings)
def item_of(issue: EpicIssue, numbers: dict[str, int]) -> Item:
"""The issue as ranking scores it. numbers holds the number of each issue ranked with it, by key; the item is blocked by those of them that block the issue."""
return Item(numbers.get(issue.key, 0), NO_RELEASE, issue.exempt, issue.summary, issue.scores, issue.moves, tuple(sorted(numbers[key] for key in issue.blockers if key in numbers)))
def scored(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Failure | Limited | None]:
"""issues, once claude has scored each open issue that may become a chunk and holds no scores, whoever filed it, and why the scoring stopped early, None where it didn't. Scores an issue holds stay, a person's and an earlier run's alike. Each score is set on the issue with a comment, in the epic's language, that tells its team the scores.
A human's task gets no scores, since it starts no work of the loop's. Fewer than two other issues need no order, so none is scored. An issue claude or the tracker fails on is named and stays without scores, so it starts after those that hold them; a usage limit ends the scoring."""
ours = [issue for issue in chunk_issues(epic, issues) if not isinstance(repo_pick.recorded(issue, epic.config.label_repos), repo_pick.HumanTask)]
bare = [issue for issue in ours if not issue.scores]
if not bare or len(ours) < 2:
return issues, None
rung, language, rule, weighed = planning_rung(epic.config.repoless_model), epic.record.language(), scoring_rule(epic.home), weighing(epic, bare)
if failed := next((each for each in (rung, language, rule, weighed) if isinstance(each, Failure)), None):
return issues, failed
assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(rule, str) and isinstance(weighed, Weighing)
folder = epic.home / STATE / epic.key
folder.mkdir(parents=True, exist_ok=True)
for issue in bare:
say(f"scoring {issue.key}", epic.effects, stdout=True)
repo = repo_of(epic, issue)
goals = ranking.goals_named(weighed.goals, repo, weighed.repos.get(repo) if repo else None)
answer = goals if isinstance(goals, Failure) else issue_scores.asked(issue, rule, goals, language or epic.config.language, rung, epic.effects.claude, str(folder))
if isinstance(answer, Limited):
return issues, answer
held = answer if isinstance(answer, Failure) else scores_set(epic, issue, answer, weighed)
if isinstance(held, Failure):
say(f"{issue.key} is not scored: {held.reason}", epic.effects, stdout=True)
continue
assert isinstance(answer, issue_scores.Scores)
issues = [held if each.key == issue.key else each for each in issues]
say(f"{issue.key} is scored {', '.join(f'{name} {value}' for name, value in held.scores.items())}, Moves {answer.moves or 'none'}", epic.effects, stdout=True)
return issues, None
def scores_set(epic: Planned, issue: EpicIssue, answer: issue_scores.Scores, weighed: Weighing) -> EpicIssue | Failure:
"""issue holding the scores of answer, once the tracker has set them and told the team. Before the tracker sets them, the answer is held to the plan's format and to the goals the issue may name, since a score that cannot be ranked would stay on the issue."""
fields = no_scores(issue.key, answer.scores, answer.moves, {})
if isinstance(fields, Failure):
return fields
held = dataclasses.replace(issue, scores=fields.scores, moves=fields.moves)
ranked = ranking.ranked([ranking.EpicItem(item_of(held, {issue.key: number(issue.key)}, ()), repo_of(epic, issue), issue.key)], weighed.formula, weighed.goals, weighed.repos)
return ranked if isinstance(ranked, Failure) else epic.store.set_scores(issue.key, answer.scores, answer.moves, answer.comment) or held
def scoring_rule(home: pathlib.Path) -> str | Failure:
"""The text every plan item is scored by, which says what L, E, I and S mean."""
try:
return (home / RULE).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read the scoring rule {home / RULE}, so no issue is scored: {failure}")
def start_order(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure:
"""The keys of the open issues that may become a chunk and hold scores, in the order they start: by score from the highest, each blocker above what it blocks, as ranking puts them. An issue nobody scored is left out, and starts after these in the tracker's rank order. So is one with no pick yet or with two, which doesn't start."""
held = [issue for issue in chunk_issues(epic, issues) if not ranking.unscored(item_of(issue, {}, ()), issue.key)]
if len(held) < 2:
return [issue.key for issue in held]
# An issue's place in the tracker is its id in the ranking: keys of two Jira projects may share a number, and issues that score the same keep the tracker's order.
numbers = {issue.key: at for at, issue in enumerate(held, 1)}
keys = {id_: key for key, id_ in numbers.items()}
weighed = weighing(epic, held)
if isinstance(weighed, Failure):
return weighed
by_key = {issue.key: issue for issue in issues}
items = [ranking.EpicItem(item_of(issue, numbers, before(issue, by_key, issues)), repo_of(epic, issue), issue.key) for issue in held]
ranked = ranking.ranked(items, weighed.formula, weighed.goals, weighed.repos)
return ranked if isinstance(ranked, Failure) else [keys[item.id] for item, _ in ranked]
def before(issue: EpicIssue, by_key: dict[str, EpicIssue], issues: list[EpicIssue]) -> tuple[str, ...]:
"""The keys of the issues that start before issue: what blocks it or its parent, and for a blocker split by repo, its sub-tasks."""
parent = by_key.get(issue.parent)
blockers = [by_key[key] for key in (*issue.blockers, *(parent.blockers if parent else ())) if key in by_key]
return tuple(each.key for blocker in blockers for each in ([task for task in issues if task.parent == blocker.key] if split.is_split(blocker, issues) else [blocker]))
def item_of(issue: EpicIssue, numbers: dict[str, int], blockers: tuple[str, ...]) -> Item:
"""The issue as ranking scores it. numbers holds the number of each issue ranked with it, by key; the item is blocked by those of them that blockers names."""
return Item(numbers.get(issue.key, 0), NO_RELEASE, issue.exempt, issue.summary, issue.scores, issue.moves, tuple(sorted(numbers[key] for key in blockers if key in numbers)))
+22 -4
View File
@@ -7,11 +7,11 @@ import ast
import dataclasses
import decimal
from plan.blockers import blockers_first
from plan.blockers import blockers_first, blocking_loop
from plan.todo_table import CODE_HEALTH, EPIC_GOAL, Item, REPO_GOAL, SHAPE
from do_epic.backend.protocol import EpicStore
from failure import Failure
from plan.goals_file import GOAL_STEP, goal_weights, Mark, numbered, ranked_goals
from plan.goals_file import GOAL_STEP, goal_weights, goals_section, Mark, numbered, ranked_goals
from review_rules.comprehension_history import latest_overall
from plan.formula import parse_formula
from plan import ranking
@@ -31,9 +31,10 @@ class RepoRanking:
@dataclasses.dataclass(frozen=True)
class EpicItem:
"""One of an epic's open items. An Item names a release and an epic item has none: give every item of one epic the same release, so that no blocker sits in a later release than what it blocks. repo is the name of the repo the item is worked in; None where it has none."""
"""One of an epic's open items. An Item names a release and an epic item has none: give every item of one epic the same release, so that no blocker sits in a later release than what it blocks. repo is the name of the repo the item is worked in; None where it has none. name is what a failure calls the item, such as its issue's key."""
item: Item
repo: str | None
name: str
def ranked(items: list[EpicItem], formula: str, epic_goals: str, repos: dict[str, RepoRanking]) -> list[tuple[Item, float]] | Failure:
@@ -44,7 +45,7 @@ def ranked(items: list[EpicItem], formula: str, epic_goals: str, repos: dict[str
scorings: dict[str | None, ranking.Scoring] = {}
scored = []
for each in items:
name = f"item {each.item.id}"
name = each.name
if each.repo not in scorings:
if each.repo is not None and each.repo not in repos:
return Failure(f"{name} is in the repo {each.repo}, whose goals were not read")
@@ -57,6 +58,9 @@ def ranked(items: list[EpicItem], formula: str, epic_goals: str, repos: dict[str
return value
scored.append((each.item, value))
scored.sort(key=lambda pair: (ranking.FIRST.get(pair[0].exempt, len(ranking.FIRST)), -pair[1], pair[0].id))
names = {each.item.id: each.name for each in items}
if loop := blocking_loop({item.id: (item, value) for item, value in scored}):
return Failure(f"{', '.join(names[id_] for id_ in loop[:-1])} and {names[loop[-1]]} block each other in a loop; drop one of the blockers")
return blockers_first(scored)
@@ -153,6 +157,20 @@ def chain(epic_goals: str, repo: str | None, own: RepoRanking | None) -> list[tu
return [*scoped, *((goal if goal == CODE_HEALTH else f"{REPO_GOAL}{goal}", mark) for goal, mark in goals)]
def goals_named(epic_goals: str, repo: str | None, own: RepoRanking | None) -> str | Failure:
"""What tells a scorer which goals an item in repo may move: the epic's goals and its repo's as text, and the name of each achieve goal as a Moves cell spells it."""
goals = chain(epic_goals, repo, own)
if isinstance(goals, Failure):
return goals
names = ", ".join(f"`{goal}`" for goal, mark in goals if mark == "Achieve")
theirs = goals_section(own.goals_text) if own else ""
# chain has read the same text's ## Goals above.
assert not isinstance(theirs, Failure), theirs
health = f"\n\n`{CODE_HEALTH}` is the goal that the code of {repo} stays easy to read, change safely and debug." if CODE_HEALTH in dict(goals) else ""
own_goals = f"\n\nThe goals of the repo {repo}, each named `{REPO_GOAL}<its number>`:\n\n{theirs.strip()}" if own else ""
return f"The epic's goals, each named `{EPIC_GOAL}<its number>`:\n\n{epic_goals.strip()}{health}{own_goals}\n\nAn item moves only these: {names or 'none, so leave the moves empty'}."
def unscored(item: Item, name: str) -> Failure | None:
"""Why the item cannot be scored, such as an issue a person filed and nobody scored; None where it holds each score."""
missing = next((score for score in SET_SCORES if score not in item.scores), None)
+14 -6
View File
@@ -61,8 +61,16 @@ class Unclear:
Pick = Repo | ClaudeWork | HumanTask
def label_of(pick: Pick) -> str:
return f"{REPO_PREFIX}{pick.name}" if isinstance(pick, Repo) else CLAUDE_LABEL if isinstance(pick, ClaudeWork) else HUMAN_LABEL
def team_label(repo: str, team: LabelRepos) -> str | None:
"""The label on the table's first line that maps to the repo; None where no line does."""
return next((label for label, name in team.items() if name == repo), None)
def label_of(pick: Pick, team: LabelRepos) -> str:
"""The label that records the pick: for a repo the team's own, and `repo:<name>` only where the team's table doesn't name it."""
if isinstance(pick, Repo):
return team_label(pick.name, team) or f"{REPO_PREFIX}{pick.name}"
return CLAUDE_LABEL if isinstance(pick, ClaudeWork) else HUMAN_LABEL
def recorded(issue: EpicIssue, team: LabelRepos) -> Pick | None | Failure:
@@ -94,18 +102,18 @@ def picked(store: EpicStore, issue: EpicIssue, team: LabelRepos, rule: str, rung
known = recorded(issue, team)
if known is not None:
return known
reply = claude_reply(claude, ["--json-schema", json.dumps(PICK_SCHEMA), *rung.flags(), "--tools", ""], cwd, prompt(rule, issue), "the repo pick")
reply = claude_reply(claude, ["--json-schema", json.dumps(PICK_SCHEMA), *rung.flags(), "--tools", "", "--strict-mcp-config"], cwd, prompt(rule, issue), "the repo pick")
if isinstance(reply, Failure | Limited):
return reply
answer = answer_of(structured_output(reply))
if isinstance(answer, Failure | Unclear):
return answer
return record(store, issue, answer)
return record(store, issue, answer, team)
def record(store: EpicStore, issue: EpicIssue, pick: Pick) -> Pick | Failure:
def record(store: EpicStore, issue: EpicIssue, pick: Pick, team: LabelRepos) -> Pick | Failure:
"""pick, once the issue is labelled with it."""
added = store.add_label(issue.key, label_of(pick))
added = store.add_label(issue.key, label_of(pick, team))
return added if isinstance(added, Failure) else pick
+44 -15
View File
@@ -9,8 +9,9 @@ from do_epic.epic_record import CAP
from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_chunks, project_lock, starting
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from do_epic.split import finished, is_split
from do_epic.split import finished, is_split, SPLIT_LABEL
from do_epic.repo_pick import HumanTask, LabelRepos, Pick, recorded, Repo
from text_files.markdown_text import listed
from project_config.settings import PARALLEL_CHUNKS
from do_epic.parked import parked_chunks
from chunk_pr.approval import PARKS
@@ -73,43 +74,61 @@ class Epic:
env: typing.Mapping[str, str]
# The team's own labels for its repos.
team: LabelRepos
# The keys of the scored issues, in the order they start (`planning.start_order`).
order: tuple[str, ...]
# The statuses `jira-unblocking-statuses` names; `settled` says what they do.
unblocking: tuple[str, ...] = ()
@property
def folder(self) -> pathlib.Path:
return self.home / STATE / self.key
def open_blockers(issue: EpicIssue, by_key: dict[str, EpicIssue]) -> list[str]:
"""The keys of the issues that block issue, or its parent, that are not done. A blocker outside the epic counts, since its state is unknown."""
def unblocks(status: str, unblocking: tuple[str, ...]) -> bool:
"""Whether status is one of the unblocking statuses, whatever its case, so a name typed in another case than Jira shows still matches."""
return status.casefold() in {name.casefold() for name in unblocking}
def settled(issue: EpicIssue, by_key: dict[str, EpicIssue], unblocking: tuple[str, ...]) -> bool:
"""Whether the issue's work has landed, so that it takes no chunk and unblocks what it blocks: the tracker counts it done, or its status is one of unblocking, such as one the team's automation gives an issue whose pull request merged. An item marked SPLIT_LABEL has landed once each of its sub-tasks has, since nobody moves it before they are done."""
tasks = [task for task in by_key.values() if task.parent == issue.key] if SPLIT_LABEL in issue.labels else []
return issue.done or unblocks(issue.status, unblocking) or bool(tasks) and all(settled(task, by_key, unblocking) for task in tasks)
def open_blockers(issue: EpicIssue, by_key: dict[str, EpicIssue], unblocking: tuple[str, ...] = ()) -> list[str]:
"""The keys of the issues that block issue, or its parent, that are not settled. A blocker outside the epic counts, since its state is unknown."""
parent = by_key.get(issue.parent)
return [key for key in (*issue.blockers, *(parent.blockers if parent else ())) if key not in by_key or not by_key[key].done]
return [key for key in (*issue.blockers, *(parent.blockers if parent else ())) if key not in by_key or not settled(by_key[key], by_key, unblocking)]
def held_up(issues: list[EpicIssue]) -> dict[str, list[str]]:
def held_up(issues: list[EpicIssue], unblocking: tuple[str, ...] = ()) -> dict[str, list[str]]:
"""Each blocker's key, mapped to the keys of the open issues it holds up, in the tracker's rank order. A split item's blocker holds up the item's sub-tasks."""
by_key = {issue.key: issue for issue in issues}
held: dict[str, list[str]] = {}
for issue in issues:
if not issue.done and not is_split(issue, issues):
for key in open_blockers(issue, by_key):
if not settled(issue, by_key, unblocking) and not is_split(issue, issues):
for key in open_blockers(issue, by_key, unblocking):
held.setdefault(key, []).append(issue.key)
return held
def chunks(issues: list[EpicIssue], team: LabelRepos) -> tuple[list[Chunk], list[Waits]]:
"""The open issues to work as chunks, in the tracker's rank order, and those that wait. A split item is worked through its sub-tasks, and what blocks it blocks them."""
def chunks(issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...] = ()) -> tuple[list[Chunk], list[Waits]]:
"""The open issues to work as chunks, in the tracker's rank order, and those that wait. A split item is worked through its sub-tasks, and what blocks it blocks them. An issue in one of the unblocking statuses is worked already: it waits until Jira counts it done."""
by_key = {issue.key: issue for issue in issues}
holding = held_up(issues)
holding = held_up(issues, unblocking)
found: list[Chunk] = []
waits: list[Waits] = []
for issue in issues:
if issue.done:
continue
if unblocks(issue.status, unblocking):
waits.append(Waits(issue.key, f"its work has landed: it is {issue.status}, and the epic's finishing waits until Jira counts it done"))
continue
if is_split(issue, issues):
if all(task.done for task in issues if task.parent == issue.key) and not finished(issues, issue.key):
waits.append(Waits(issue.key, "its sub-tasks are done; close it in Jira"))
continue
turn = turn_of(issue, recorded(issue, team), open_blockers(issue, by_key), by_key, issue.key in holding)
turn = turn_of(issue, recorded(issue, team), open_blockers(issue, by_key, unblocking), by_key, issue.key in holding, unblocking)
if isinstance(turn, Chunk):
found.append(turn)
else:
@@ -117,7 +136,13 @@ def chunks(issues: list[EpicIssue], team: LabelRepos) -> tuple[list[Chunk], list
return found, waits
def turn_of(issue: EpicIssue, pick: Pick | None | Failure, blocking: list[str], by_key: dict[str, EpicIssue], holds: bool) -> Chunk | Waits:
def in_start_order(found: list[Chunk], order: tuple[str, ...]) -> list[Chunk]:
"""found, with the chunks of the issues order names first, in its sequence. The other chunks follow in the tracker's rank order, as found lists them."""
place = {key: at for at, key in enumerate(order)}
return sorted(found, key=lambda chunk: place.get(chunk.issue, len(place)))
def turn_of(issue: EpicIssue, pick: Pick | None | Failure, blocking: list[str], by_key: dict[str, EpicIssue], holds: bool, unblocking: tuple[str, ...] = ()) -> Chunk | Waits:
"""The open issue's chunk, or why it waits. blocking are its open blockers, and holds says it holds up another open issue. A human's task gets a window only while it holds up another issue and nothing holds it up; that window waits for the human. A blocker outside the epic blocks until the human removes the link, since its state is unknown."""
if isinstance(pick, Failure):
return Waits(issue.key, pick.reason)
@@ -128,7 +153,10 @@ def turn_of(issue: EpicIssue, pick: Pick | None | Failure, blocking: list[str],
if blocking:
outside = [key for key in blocking if key not in by_key]
unseen = f"; do-epic cannot see {' and '.join(outside)}, outside the epic, finish: remove such a link in Jira once its issue is done" if outside else ""
return Waits(issue.key, f"{' and '.join(blocking)} block{'s' if len(blocking) == 1 else ''} it{unseen}")
inside = [key for key in blocking if key in by_key]
whom = ("it is" if len(blocking) == 1 else "each is") if not outside else f"{' and '.join(inside)} {'is' if len(inside) == 1 else 'are'}"
until = f", until {whom} {listed((*unblocking, 'done'), 'or')}" if unblocking and inside else ""
return Waits(issue.key, f"{' and '.join(blocking)} block{'s' if len(blocking) == 1 else ''} it{until}{unseen}")
return Chunk(issue.key, pick.name if isinstance(pick, Repo) else None)
@@ -142,9 +170,10 @@ def refusal(repo: str, room: RepoRoom) -> str | None:
def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str | None, run: tmux.Tmux) -> Started | Failure:
"""Starts a do-epic in a new window for each of the epic's chunks that may start now. Where finishing is set, no issue is open, and the one chunk to start is the epic's finishing (finish.py), in a window named for the epic's key. own is the key of the chunk that asks, which has finished or parked: it counts as running nowhere, and no stopped chunk starts again. Where own is None, the human's `do-epic <EPIC-KEY>` asks, and each stopped chunk starts again. A parked chunk waits in its window; one without a live window, as after a reboot, starts again as a stopped chunk does, whatever the limits, since it goes on parked. A Failure says why a window could not start; those before it run."""
"""Starts a do-epic in a new window for each of the epic's chunks that may start now, in the epic's start order, so the issue with the highest score takes the first free slot. Where finishing is set, no issue is open, and the one chunk to start is the epic's finishing (finish.py), in a window named for the epic's key. own is the key of the chunk that asks, which has finished or parked: it counts as running nowhere, and no stopped chunk starts again. Where own is None, the human's `do-epic <EPIC-KEY>` asks, and each stopped chunk starts again. A parked chunk waits in its window; one without a live window, as after a reboot, starts again as a stopped chunk does, whatever the limits, since it goes on parked. A Failure says why a window could not start; those before it run."""
session = tmux.session_name(tmux.EPIC, epic.key)
found, waits = chunks(issues, epic.team)
found, waits = chunks(issues, epic.team, epic.unblocking)
found = in_start_order(found, epic.order)
if finishing:
found.append(Chunk(epic.key, None))
started: list[str] = []
+10 -8
View File
@@ -7,7 +7,7 @@ import json
from claude_code.reply import Claude, claude_reply, Limited
from do_epic.backend.protocol import EpicIssue, EpicStore
from failure import Failure
from do_epic.repo_pick import label_of, LabelRepos, of_label, Repo, REPO_NAME
from do_epic.repo_pick import label_of, LabelRepos, of_label, Repo, REPO_NAME, team_label
from model_routing.ladder import Rung
from claude_code.entries import structured_output
@@ -64,7 +64,7 @@ def is_split(item: EpicIssue, issues: list[EpicIssue]) -> bool:
return SPLIT_LABEL in item.labels or any(task.parent == item.key and not task.by_loop for task in issues)
def split(store: EpicStore, issue: EpicIssue, team: LabelRepos, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str) -> Split | Failure | Limited:
def split(store: EpicStore, issue: EpicIssue, team: LabelRepos, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str, summary_template: str | None) -> Split | Failure | Limited:
"""Splits the epic's child issue into a sub-task per repo it changes, where that is more than one. by_person says a person filed the issue, and checkouts are the epic's repos that claude may read. An item that changes one repo or none is left as it is, for repo_pick, and one already split (is_split) is left alone.
A sub-task of the item already labelled for a repo counts as that repo's, so a run that failed after filing some sub-tasks leaves the next run to file only the lacking ones. The comment on a person's issue is posted once its sub-tasks are filed, just before the item is marked. A failure after the comment but before the mark posts it again on the next run."""
@@ -87,7 +87,7 @@ def split(store: EpicStore, issue: EpicIssue, team: LabelRepos, by_person: bool,
for part in predicted.parts:
if part.repo in have:
continue
key = store.file(issue.key, task_summary(part.repo, issue.summary), part.change, (label_of(Repo(part.repo)),))
key = store.file(issue.key, task_summary(part.repo, issue.summary, team, summary_template), part.change, (label_of(Repo(part.repo), team),))
if isinstance(key, Failure):
return Failure(f"cannot file the sub-task for {part.repo} under {issue.key}: {key.reason}; {sub_tasks_filed(filed)}; run do-epic again to file the rest")
filed.append(key)
@@ -105,13 +105,15 @@ def sub_tasks_filed(keys: list[str]) -> str:
return f"this run filed {', '.join(keys)}" if keys else "this run filed no sub-task"
def task_summary(repo: str, summary: str) -> str:
"""A sub-task's summary. Three readers, seated as a client's team, picked `[<repo>] <the item's summary>` from four candidates, over `<repo>: …`, `… (<repo>)` and `… — <repo> part`, 3-0."""
return f"[{repo}] {summary}"
def task_summary(repo: str, summary: str, team: LabelRepos, template: str | None) -> str:
"""A sub-task's summary from the team's template, where it has one. Without one, `[<repo>] <the item's summary>`: three readers, seated as a client's team, picked that from four candidates, over `<repo>: …`, `… (<repo>)` and `… — <repo> part`, 3-0."""
if template is None:
return f"[{repo}] {summary}"
return template.format(label=team_label(repo, team) or repo, Summary=summary[:1].upper() + summary[1:])
def finished(issues: list[EpicIssue], key: str) -> bool:
"""Whether the item named key is done. An item marked SPLIT_LABEL that has sub-tasks is done once each of them is, whatever its own status. Any other item is done by its own status, also one a person's sub-tasks split: do-epic filed those for every repo the item changes, and a person's may cover only a part of it. A key no issue has isn't done."""
"""Whether the item named key is done. An item marked SPLIT_LABEL that has sub-tasks is done once each of them is, whatever its own status. Any other item is done by its own status, also one under which a person filed sub-tasks: `parent_moves` moves that item to done once every sub-task is done. A key no issue has isn't done."""
item = next((issue for issue in issues if issue.key == key), None)
tasks = [issue for issue in issues if issue.parent == key]
if item is None:
@@ -121,7 +123,7 @@ def finished(issues: list[EpicIssue], key: str) -> bool:
def prediction(issue: EpicIssue, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str) -> Prediction | Failure | Limited:
"""The repos claude predicts the item changes, from the code in checkouts."""
flags = ["--json-schema", json.dumps(SPLIT_SCHEMA), *rung.flags(), "--tools", "Read,Grep,Glob", *(arg for each in checkouts for arg in ("--add-dir", each))]
flags = ["--json-schema", json.dumps(SPLIT_SCHEMA), *rung.flags(), "--tools", "Read,Grep,Glob", "--strict-mcp-config", *(arg for each in checkouts for arg in ("--add-dir", each))]
reply = claude_reply(claude, flags, cwd, prompt(issue, by_person, rule, language, checkouts), "the repo split")
return reply if isinstance(reply, Failure | Limited) else answer_of(structured_output(reply))
+8 -4
View File
@@ -9,6 +9,8 @@ from do_epic.parked import file_of, Parked, parked_chunks, SLOT
from do_epic.repo_pick import LabelRepos
from agent_cycle import tmux
UNSCORED = ", after each issue that holds every score, since it doesn't"
def since(folder: pathlib.Path, chunk: Parked) -> str:
"""`, since <time>`: when the chunk's pull request began to await the gate its file records, to the minute in UTC, since the machine may be one the human reaches over ssh. The file is written once per gate. Empty where the file cannot be read."""
@@ -18,9 +20,9 @@ def since(folder: pathlib.Path, chunk: Parked) -> str:
return ""
def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, run: tmux.Tmux) -> list[str] | Failure:
"""A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. It doesn't start anything or check any limit, so the line of a chunk that has yet to start doesn't say which limit holds it back."""
found, waits = chunks(issues, team)
def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...], run: tmux.Tmux, order: tuple[str, ...]) -> list[str] | Failure:
"""A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. order holds the keys of the issues that start by score, as planning.start_order puts them; a chunk it leaves out says that it starts after them. It doesn't start anything or check any limit, so the line of a chunk that has yet to start doesn't say which limit holds it back."""
found, waits = chunks(issues, team, unblocking)
folder = home / STATE / key
parked = parked_chunks(folder)
if isinstance(parked, Failure):
@@ -30,6 +32,8 @@ def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepo
live = {window.name: window for window in windows if not window.dead}
again = f"run `do-epic {key}` to start it again"
reasons = {wait.issue: wait.reason for wait in waits}
# Where no issue starts by score, each starts in the tracker's rank order, which needs no reason.
bare = {chunk.issue for chunk in found if chunk.issue not in order} if order else set()
for chunk in found:
if chunk.issue in parked:
shown = live[chunk.issue].awaits if chunk.issue in live else ""
@@ -40,7 +44,7 @@ def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepo
elif chunk.human and chunk.issue in live:
reasons[chunk.issue] = HUMAN_WAIT
elif chunk.issue not in live:
reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it" + ("" if chunk.human else " once the epic and its repo have room")
reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it" + ("" if chunk.human else " once the epic and its repo have room") + ("" if chunk.human or chunk.issue not in bare else UNSCORED)
return [line(issue.key, reasons, live, session) for issue in issues if issue.key in reasons or issue.key in live]
+120
View File
@@ -8,6 +8,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.config import DoEpicConfig, load
from failure import Failure
from project_config.settings import Finish
from do_epic.backend.jira_start import Start
SETTINGS = """jira-url = "https://acme.atlassian.net"
env-file = "~/jira.env"
@@ -60,6 +61,41 @@ class ConfigTest(unittest.TestCase):
self.assertIn(fault, reason)
self.assertEqual(reason.count("`label-repos` maps"), 7)
def test_reads_a_template_for_a_sub_tasks_summary(self) -> None:
self.write(SETTINGS + 'sub-task-summary = "{label}: {Summary}"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.sub_task_summary, "{label}: {Summary}")
def test_leaves_a_sub_tasks_summary_to_its_default_where_the_config_has_no_template(self) -> None:
self.write()
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertIsNone(found.sub_task_summary)
def test_refuses_a_template_that_is_no_one_line_with_summary_and_only_known_fields(self) -> None:
for line, fault in (
("sub-task-summary = 4", "`sub-task-summary` is 4, not one line of text"),
('sub-task-summary = "a\\nb {Summary}"', "not one line of text"),
('sub-task-summary = "{label}"', "`sub-task-summary` lacks {Summary}"),
('sub-task-summary = "{label}: {Summary} {repo}"', "names {repo}, and only {label} and {Summary} are known"),
('sub-task-summary = "{Summary:>9}"', "writes {Summary:>9} with something after the name; write {Summary} alone"),
('sub-task-summary = "{Summary} {label!r}"', "writes {label!r} with something after the name; write {label} alone"),
('sub-task-summary = "{Summary!}"', "`sub-task-summary` is '{Summary!}', which Python can't read as a template ("),
('sub-task-summary = "{Summary"', "`sub-task-summary` is '{Summary', which Python can't read as a template ("),
):
with self.subTest(line=line):
self.write(SETTINGS + line + "\n")
self.assertIn(fault, self.failure())
def test_reads_a_template_of_plain_text_around_its_fields_and_a_brace_written_twice(self) -> None:
for template in ("{Summary}", "{Summary}{{", "{Summary} for {label} in Jira"):
with self.subTest(template=template):
self.write(SETTINGS + f'sub-task-summary = "{template}"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.sub_task_summary, template)
def test_refuses_a_label_repos_that_is_no_table(self) -> None:
self.write('label-repos = "twu-4"\n' + SETTINGS)
self.assertIn("`label-repos` is 'twu-4', not a table of labels, such as `twu-4 = \"tenant-web-ui-4\"` under `[label-repos]`", self.failure())
@@ -78,6 +114,90 @@ class ConfigTest(unittest.TestCase):
self.write(SETTINGS + 'jira-finish-status = " "\n')
self.assertIn('`jira-finish-status` is \' \', not the name Jira shows, such as "Done"; `jira-finish-status` is set, so `jira-finish-transition` must be too', self.failure())
def test_reads_how_a_starting_issue_moves_and_which_boards_sprint_it_joins(self) -> None:
self.write(SETTINGS)
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.start, Start(None, None))
self.write(SETTINGS + 'jira-start-transition = "In Progress"\njira-sprint-board = 1\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.start, Start("In Progress", 1))
for board, read in (('"6"', "'6'"), ("0", "0"), ("true", "True"), ("6.0", "6.0")):
with self.subTest(board=board):
self.write(SETTINGS + f'jira-start-transition = " "\njira-sprint-board = {board}\n')
self.assertIn(f"`jira-start-transition` is ' ', not the name Jira shows, such as \"In Progress\"; `jira-sprint-board` is {read}, not a board's ID, the whole number in the board's address, such as 6", self.failure())
def test_reads_the_transition_that_moves_a_parent_whose_sub_tasks_have_all_landed(self) -> None:
self.write(SETTINGS)
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertIsNone(found.sub_tasks_landed_transition)
self.write(SETTINGS + 'jira-sub-tasks-landed-transition = "Release Ready"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual(found.sub_tasks_landed_transition, "Release Ready")
self.write(SETTINGS + 'jira-sub-tasks-landed-transition = 5\n')
self.assertIn("`jira-sub-tasks-landed-transition` is 5, not the name Jira shows, such as \"Release Ready\"", self.failure())
def test_reads_the_unblocking_statuses_and_that_the_teams_automation_moves_issues(self) -> None:
self.write(SETTINGS)
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.unblocking, found.automation_moves), ((), False))
self.write(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Done"]\njira-automation-moves-issues = true\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.unblocking, found.automation_moves), (("Release Ready", "Done"), True))
def test_the_issue_types_of_a_finding_and_a_release_review_are_task_where_left_out(self) -> None:
self.write()
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.finding_type, found.review_type), ("Task", "Task"))
def test_reads_the_issue_types_of_a_finding_and_a_release_review(self) -> None:
self.write(SETTINGS + 'jira-finding-type = "Feature"\njira-review-type = "Chore"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.finding_type, found.review_type), ("Feature", "Chore"))
def test_refuses_an_issue_type_that_is_no_name(self) -> None:
for setting, example in (("jira-finding-type", "Feature"), ("jira-review-type", "Chore")):
for value, shown in (("4", "4"), ('" "', "' '")):
with self.subTest(setting=setting, value=value):
self.write(SETTINGS + f"{setting} = {value}\n")
self.assertIn(f'`{setting}` is {shown}, not the name Jira shows, such as "{example}"', self.failure())
def test_reads_the_statuses_of_an_issue_whose_pull_request_into_an_epic_branch_opened_and_merged(self) -> None:
self.write(SETTINGS)
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.pull_open_status, found.pull_merged_status), (None, None))
self.write(SETTINGS + 'jira-unblocking-statuses = ["release ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
found = load(self.home)
assert isinstance(found, DoEpicConfig), found
self.assertEqual((found.pull_open_status, found.pull_merged_status), ("Code Review", "Release Ready"))
def test_refuses_a_pull_request_status_that_is_no_name_and_a_merged_one_that_does_not_unblock(self) -> None:
self.write(SETTINGS + 'jira-pull-request-open-status = " "\njira-pull-request-merged-status = 5\n')
self.assertIn("`jira-pull-request-open-status` is ' ', not the name Jira shows, such as \"Code Review\"; `jira-pull-request-merged-status` is 5, not the name Jira shows, such as \"Release Ready\"", self.failure())
for unblocking in ("", 'jira-unblocking-statuses = ["Shipped"]\n', "jira-unblocking-statuses = 5\n"):
with self.subTest(unblocking=unblocking):
self.write(SETTINGS + unblocking + 'jira-pull-request-merged-status = "Release Ready"\n')
self.assertIn("`jira-pull-request-merged-status` is 'Release Ready', so `jira-unblocking-statuses` must list it: an issue at any other status reads as open, and its chunk would start again", self.failure())
def test_refuses_unblocking_statuses_that_are_no_list_of_names_and_a_switch_that_is_no_boolean(self) -> None:
for value in ('"Done"', '["Done", " "]', "[]", "[1]"):
with self.subTest(value=value):
self.write(SETTINGS + f"jira-unblocking-statuses = {value}\n")
self.assertIn('`jira-unblocking-statuses` is ', self.failure())
self.assertIn(', not a list of the status names Jira shows, such as ["Release Ready"]', self.failure())
self.write(SETTINGS + "jira-automation-moves-issues = true\n")
self.assertIn("`jira-automation-moves-issues` is set, so `jira-unblocking-statuses` must name the status the automation gives an issue whose pull request merged", self.failure())
self.write(SETTINGS + 'jira-automation-moves-issues = "yes"\n')
self.assertIn("`jira-automation-moves-issues` is 'yes', not true or false", self.failure())
def test_refuses_while_the_config_is_missing(self) -> None:
self.write(None)
self.assertIn(f"cannot read {self.folder / 'config.toml'}", self.failure())
+131
View File
@@ -0,0 +1,131 @@
import pathlib
import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic import dry_run
from failure import Failure
from do_epic.test_scheduler import issue
from do_epic.backend.fake import MemoryEpic
LISTED = "-t", "=epic-ABC-12", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"
START = ["new-window", "-d", "-t", "=epic-ABC-12:", "-n", "ABC-21", "-c", "/code/api", "-P", "-F", "#{window_id}", "--", "do-epic"]
def tmux(calls: list[list[str]], shown: str = "ABC-20\t0\t@1\n"):
def run(args: list[str]) -> subprocess.CompletedProcess[str]:
calls.append(args)
return subprocess.CompletedProcess(args, 0, shown, "")
return run
class TheRecordingTmux(unittest.TestCase):
def test_starts_no_window_and_lists_the_one_it_would_start_beside_the_real_ones(self) -> None:
calls: list[list[str]] = []
run = dry_run.recording(tmux(calls))
self.assertEqual(run(START).stdout, "@dry1\n")
self.assertEqual(run(["list-windows", *LISTED]).stdout, "ABC-20\t0\t@1\nABC-21\t0\t@dry1\n")
everywhere = run(["list-windows", "-a", "-F", "x"]).stdout
self.assertEqual(everywhere, "ABC-20\t0\t@1\nepic-ABC-12\tABC-21\t0\t@dry1\t/code/api\n")
self.assertEqual([call[0] for call in calls], ["list-windows", "list-windows"])
def test_lists_the_window_it_would_start_where_tmux_finds_no_session(self) -> None:
def none(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(args, 1, "", "no server running")
run = dry_run.recording(none)
run(["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", "/code/api"])
self.assertEqual(run(["list-windows", *LISTED]).stdout, "ABC-21\t0\t@dry1\n")
self.assertEqual(run(["list-windows", "-t", "=epic-ABC-99", "-F", "x"]).stdout, "")
def test_answers_each_command_with_its_own_words_and_no_error(self) -> None:
def refused(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(args, 1, "junk", "no server")
def fields(done: subprocess.CompletedProcess[str]) -> tuple[object, int, str, str]:
return done.args, done.returncode, done.stdout, done.stderr
run = dry_run.recording(refused)
self.assertEqual(fields(run(START)), (START, 0, "@dry1\n", ""))
self.assertEqual(fields(run(["kill-window", "-t", "@1"])), (["kill-window", "-t", "@1"], 0, "", ""))
self.assertEqual(fields(run(["list-windows", *LISTED])), (["list-windows", *LISTED], 0, "ABC-21\t0\t@dry1\n", ""))
self.assertEqual(fields(dry_run.recording(refused)(["list-windows", *LISTED])), (["list-windows", *LISTED], 0, "", ""))
def test_lists_every_window_it_would_start(self) -> None:
run = dry_run.recording(tmux([], ""))
run(START)
run(["new-window", "-d", "-t", "=epic-ABC-12:", "-n", "ABC-22", "-c", "/code/web", "-P"])
run(["new-window", "-d", "-t", "=epic-ABC-99:", "-n", "ABC-23", "-c", "/code/web", "-P"])
self.assertEqual(run(["list-windows", *LISTED]).stdout, "ABC-21\t0\t@dry1\nABC-22\t0\t@dry2\n")
self.assertEqual(run(["list-windows", "-a", "-F", "x"]).stdout, "epic-ABC-12\tABC-21\t0\t@dry1\t/code/api\nepic-ABC-12\tABC-22\t0\t@dry2\t/code/web\nepic-ABC-99\tABC-23\t0\t@dry3\t/code/web\n")
def test_answers_a_change_as_done_and_reads_the_real_tmux_for_a_read(self) -> None:
calls: list[list[str]] = []
run = dry_run.recording(tmux(calls))
self.assertEqual(run(["kill-window", "-t", "@1"]).returncode, 0)
self.assertEqual(run(["show-options", "-qv", "-t", "=s:", "@loop-root"]).stdout, "ABC-20\t0\t@1\n")
self.assertEqual(calls, [["show-options", "-qv", "-t", "=s:", "@loop-root"]])
class TheGitThatClonesNothing(unittest.TestCase):
def test_fails_a_clone_and_runs_any_other_command(self) -> None:
ran: list[tuple[str, ...]] = []
def real(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
ran.append(args)
return "ok"
git = dry_run.without_clones(real)
self.assertEqual(git("-c", "a=b", "clone", "--", "url", "dir"), Failure("a dry run doesn't clone a repo, but a real run would"))
self.assertEqual(git("remote", cwd="/c"), "ok")
self.assertEqual(ran, [("remote",)])
def test_passes_every_option_on(self) -> None:
seen: list[tuple[tuple[str, ...], dict[str, object]]] = []
def real(*args: str, **options: object) -> str | Failure:
seen.append((args, options))
return "ok"
git = dry_run.without_clones(real) # type: ignore[arg-type]
git("log", cwd="/c", timeout=5.0, guarded=True, errors="replace")
git("log")
self.assertEqual(seen, [(("log",), {"cwd": "/c", "timeout": 5.0, "guarded": True, "errors": "replace"}), (("log",), {"cwd": None, "timeout": None, "guarded": False, "errors": "strict"})])
class TheEpicItCopies(unittest.TestCase):
def test_copies_the_issues_and_the_closed_state_and_files_under_keys_jira_never_gives(self) -> None:
real = MemoryEpic("ABC-12", [issue("ABC-20"), issue("ABC-21")], done=True)
copy = dry_run.seeded(real)
assert not isinstance(copy, Failure)
self.assertEqual((copy.closed(), [each.key for each in copy.read()]), (True, ["ABC-20", "ABC-21"])) # type: ignore[union-attr]
self.assertEqual([copy.file("ABC-20", "A", "d", ()), copy.file("ABC-20", "B", "d", ())], ["ABC-new1", "ABC-new2"])
self.assertEqual((real.writes, [each.key for each in real.issues]), ([], ["ABC-20", "ABC-21"]))
self.assertEqual(copy.writes, ["file ABC-new1 under ABC-20: A", "file ABC-new2 under ABC-20: B"])
def test_notes_each_kind_of_write_in_order(self) -> None:
epic = MemoryEpic("ABC-12", [issue("ABC-20"), issue("ABC-21")])
epic.file("ABC-20", "Sub", "d", ("repo:api", "do-epic-claude"), "ABC-21")
epic.add_label("ABC-21", "do-epic-claude")
epic.rank("ABC-21", "ABC-20")
epic.comment("ABC-20", " Why. ")
epic.finish_issue("ABC-21")
epic.close("All done")
self.assertEqual(epic.writes, ["file ABC-102 under ABC-20: Sub, labelled do-epic-claude, repo:api, blocked by ABC-21", "label ABC-21 with do-epic-claude", "rank ABC-21 before ABC-20", "comment on ABC-20: Why.", "finish ABC-21", "close the epic: All done"])
def test_notes_no_write_that_fails(self) -> None:
epic = MemoryEpic("ABC-12", [issue("ABC-20")])
epic.add_label("ABC-99", "x")
epic.comment("ABC-20", " ")
epic.finish_issue("ABC-99")
self.assertEqual(epic.writes, [])
def test_fails_where_the_real_epic_cannot_be_read(self) -> None:
self.assertEqual(dry_run.seeded(MemoryEpic("ABC-12", [], fails="Jira answered 503")), Failure("Jira answered 503"))
def test_fails_where_only_the_closed_state_cannot_be_read(self) -> None:
class Unclosed(MemoryEpic):
def closed(self) -> bool | Failure:
return Failure("no state")
self.assertEqual(dry_run.seeded(Unclosed("ABC-12", [issue("ABC-20")])), Failure("no state"))
if __name__ == "__main__":
unittest.main()
+17 -1
View File
@@ -93,7 +93,9 @@ class FilingAFinding(FindingsTest):
code, _, err, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", "twu-4", "--label", "repo:api"])
self.assertEqual((code, err), (1, "cannot file the finding in the epic ABC-12: twu-4 and repo:api each say who works it; write one of them\n"))
_, _, err, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", "twu"])
self.assertTrue(err.endswith("or `do-epic-human` for a task of the human's (or the team's `twu-4`)\n"), err)
self.assertTrue(err.endswith(f"write {findings.worked_by({'twu-4': 'tenant-web-ui-4'})}\n"), err)
_, out, _, _ = self.run_with(["ABC-12", "--file", "Retry"])
self.assertTrue(out.endswith(f"picks one: {findings.worked_by({'twu-4': 'tenant-web-ui-4'})}.\n"), out)
def test_a_release_review_takes_its_label_beside_its_repo(self) -> None:
code, out, _, _ = self.run_with(["ABC-12", "--file", "Review api", "--label", "repo:api", "--label", "do-epic-release-review"])
@@ -155,6 +157,20 @@ class Instructions(unittest.TestCase):
self.assertTrue(told.endswith("its text on stdin. Write the issue and the decision in Swedish, the epic's language."), told)
self.assertNotIn("--blocked-by", told)
def test_name_the_labels_the_team_has_for_its_repos(self) -> None:
team = {"core": "core-4", "twu-4": "tenant-web-ui-4"}
self.assertIn(f"The label is {findings.worked_by(team)};", findings.instructions("ABC-12", pathlib.Path("/b/do-epic"), "Swedish", team))
class WorkedBy(unittest.TestCase):
def test_lists_repo_colon_name_alone_for_a_team_without_a_table(self) -> None:
self.assertEqual(findings.worked_by({}), "`repo:<name>` for the repo that works it, `do-epic-claude` for work of Claude's that changes no repo, or `do-epic-human` for a task of the human's")
def test_lists_each_repo_the_table_names_once_by_the_first_label_for_it_in_the_order_of_the_repos(self) -> None:
named = findings.worked_by({"twu-4": "tenant-web-ui-4", "core": "core-4", "c4": "core-4"})
self.assertTrue(named.startswith("`core` for the repo core-4, `twu-4` for the repo tenant-web-ui-4, `repo:<name>` for any other repo that works it, `do-epic-claude`"), named)
self.assertNotIn("`c4`", named)
class RecordingADecision(FindingsTest):
def test_appends_the_entry_to_the_descriptions_decisions(self) -> None:
+35 -2
View File
@@ -17,6 +17,7 @@ from chunk_driver.claims import LOCK
from do_epic.backend.fake import MemoryEpic
from loop_state.paths import paths_from
from claude_code.session import session_named
from do_epic.test_do_epic import SETTINGS
LAUNCHER = pathlib.Path("/b/do-epic")
REVIEWED = [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "do-epic-claude", done=True), issue("ABC-30", "repo:api", "do-epic-release-review", done=True)]
@@ -27,12 +28,20 @@ class WhenTheFinishingIsDue(DoEpicTest):
self.assertIs(finish.due([]), False)
self.assertIs(finish.due([issue("ABC-20", done=True), issue("ABC-21")]), False)
self.assertIs(finish.due([issue("ABC-20", done=True), issue("ABC-21", done=True)]), True)
self.assertIs(finish.due([issue("ABC-20", done=True), issue("ABC-21", status="Release Ready")]), False)
def test_an_item_split_by_repo_is_done_once_its_sub_tasks_are(self) -> None:
split = [issue("ABC-20", "split-by-repo"), issue("ABC-40", "repo:api", done=True, parent="ABC-20")]
self.assertIs(finish.due(split), True)
self.assertIs(finish.due([*split, issue("ABC-41", "repo:web", parent="ABC-20")]), False)
def test_an_issue_at_the_merged_status_counts_as_done_and_any_other_stays_as_it_is(self) -> None:
issues = [issue("ABC-20", "repo:api", status="release ready"), issue("ABC-21", "repo:api", status="Code Review"), issue("ABC-22", done=True)]
self.assertFalse(finish.due(issues))
self.assertEqual([each.done for each in finish.landed(issues, "Release Ready")], [True, False, True])
self.assertEqual(finish.landed(issues, None), issues)
self.assertEqual(finish.unreviewed(finish.landed(issues[:1], "Release Ready"), {}), ["api"])
def test_a_repo_lacks_its_review_while_a_done_issue_names_it_and_no_review_does(self) -> None:
done = [issue("ABC-20", "repo:web", done=True), issue("ABC-21", "repo:api", done=True), issue("ABC-22", "do-epic-claude", done=True), issue("ABC-23", "repo:docs")]
self.assertEqual(finish.unreviewed(done, {}), ["api", "web"])
@@ -53,11 +62,17 @@ class TheFinishingChunksTask(DoEpicTest):
self.assertIn("Finish the epic ABC-12", task)
self.assertIn("first, and api and web have none. ", task)
self.assertIn("first, and api has none. ", finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True)], {}, LAUNCHER, "Swedish"))
self.assertIn('`/b/do-epic ABC-12 --file "<summary>" --label repo:<name> --label do-epic-release-review`', task)
self.assertIn('`/b/do-epic ABC-12 --file "<summary>" --label <label> --label do-epic-release-review`', task)
self.assertIn("`Release review of ABC-12`", task)
self.assertIn("in Swedish", task)
self.assertNotIn("--close-epic", task)
def test_names_each_unreviewed_repos_label_from_the_teams_table_else_repo_colon_name(self) -> None:
done = [issue("ABC-20", "twu-4", done=True), issue("ABC-21", "repo:web", done=True)]
task = finish.task("ABC-12", done, {"twu-4": "tenant-web-ui-4"}, LAUNCHER, "Swedish")
self.assertIn("The `<label>` is `twu-4` for tenant-web-ui-4 and `repo:web` for web. ", task)
self.assertIn("The `<label>` is `twu-4` for tenant-web-ui-4. ", finish.task("ABC-12", done[:1], {"twu-4": "tenant-web-ui-4", "web": "tenant-web-ui-4"}, LAUNCHER, "Swedish"))
def test_then_has_the_human_confirm_each_goal_before_the_summary_and_the_closing(self) -> None:
task = finish.task("ABC-12", REVIEWED, {}, LAUNCHER, "Swedish")
self.assertIn("Finish the epic ABC-12", task)
@@ -65,6 +80,9 @@ class TheFinishingChunksTask(DoEpicTest):
self.assertIn("ask the human to approve the set", task)
self.assertIn("`/b/do-epic ABC-12 --close-epic`", task)
self.assertIn("in Swedish", task)
self.assertIn("3. Once the human has confirmed every goal, run `project-config epic-branch` in the checkout of each repo the epic changed. Where it fails, the repo keeps no working branch for the epic: skip it. Where it prints a template, run `chunk-pr open-epic ABC-12 \"<title>\"` in that checkout", task)
self.assertIn("Never merge that pull request: a person does.\n4. Then write a summary", task)
self.assertIn("what shipped in each repo, each pull request step 3 opened, and each goal's evidence.", task)
self.assertIn(findings.instructions("ABC-12", LAUNCHER, "Swedish", {}), task)
self.assertIn("The epic's issues, each done:\n\n- ABC-20 (api): Do ABC-20\n- ABC-21: Do ABC-21\n- ABC-30 (api): Do ABC-30", task)
self.assertNotIn("do-epic-release-review`", task)
@@ -116,6 +134,13 @@ class ClosingTheEpic(DoEpicTest):
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual(store.finish, Finish("Mark as done", "Done")) # type: ignore[attr-defined]
def test_closes_an_epic_whose_open_issues_all_have_the_merged_status(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8")
self.issues.append(issue("ABC-31", "repo:api", status="Release Ready"))
code, out, err = self.close()
self.assertEqual(code, 0, err)
self.assertIs(self.store.done, True)
def test_refuses_while_an_issue_is_open(self) -> None:
self.issues.append(issue("ABC-31", "repo:api"))
code, _, err = self.close()
@@ -149,7 +174,7 @@ class ClosingTheEpic(DoEpicTest):
for argv in (["ABC-12", "--close-epic", "now"], ["--close-epic", "ABC-12"], ["--close-epic"]):
code, out, err = self.run_main(argv, FakeEffects())
self.assertEqual((code, out), (1, ""), argv)
self.assertIn("usage: do-epic <EPIC-KEY> [--status]\n", err)
self.assertIn("usage: do-epic <EPIC-KEY> [--status | --dry-run]\n", err)
self.assertIn("do-epic <EPIC-KEY> --close-epic <<'EOF' summary EOF", err)
@@ -175,6 +200,14 @@ class TheFinishingChunk(DoEpicTest):
self.assertEqual(self.started(fake), ["ABC-12"])
self.assertIn(["/b/do-epic", "--chunk", "ABC-12", "ABC-12"], [args[-4:] for args in fake.tmux_calls])
def test_starts_once_each_open_issue_has_the_merged_status(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8")
self.issues = [issue("ABC-20", "do-epic-claude", status="Release Ready"), issue("ABC-21", "do-epic-claude", done=True)]
fake = FakeEffects(on_terminal=False)
code, out, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0, err)
self.assertEqual(self.started(fake), ["ABC-12"])
def test_doesnt_start_while_an_issue_is_open_or_in_an_epic_without_issues(self) -> None:
for issues in ([issue("ABC-20", "do-epic-claude", done=True), issue("ABC-21", "do-epic-human")], []):
self.issues = issues
+43 -4
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.gates import APPROVAL, CHECKS, gate, Gate, MERGE, NEW_REVIEW, Open, Unopened
from do_epic.gates import APPROVAL, CHECKS, gate, Gate, MERGE, NEW_REVIEW, Open, Unmergeable, Unopened
from failure import Failure
WORKTREES = "worktree /code/billing\nHEAD aaa\nbranch refs/heads/main\n\nworktree /code/billing-ABC-21\nHEAD abc\nbranch refs/heads/ABC-21\n"
@@ -28,7 +28,7 @@ def comment(by: str, at: str) -> dict:
class Forge:
"""Stands in for git and the forge's CLI in the checkout and the chunk's worktree; `ran` holds each folder a command ran in. Only the CLI of origin's forge answers: `gh` fails on a Gitea origin, and `tea` on a GitHub one."""
def __init__(self, origin: str = "git@github.com:o/billing.git", pulls: str = f"7\t{HEAD}\tfalse\n", draft: bool = False, decision: str = "REVIEW_REQUIRED", buckets: tuple[str, ...] = ("pass",), threads: tuple[dict, ...] = (), status: str = '{"state": "success", "total_count": 1}', worktrees: str = WORKTREES, fails: str = "", reviews: tuple[dict, ...] = (), comments: tuple[dict, ...] = (), title: str = "Add x") -> None:
def __init__(self, origin: str = "git@github.com:o/billing.git", pulls: str = f"7\t{HEAD}\tfalse\n", draft: bool = False, decision: str = "REVIEW_REQUIRED", buckets: tuple[str, ...] = ("pass",), threads: tuple[dict, ...] = (), status: str = '{"state": "success", "total_count": 1}', mergeable: str = "MERGEABLE", merge_state: str = "CLEAN", worktrees: str = WORKTREES, fails: str = "", reviews: tuple[dict, ...] = (), comments: tuple[dict, ...] = (), title: str = "Add x", base: str = "main") -> None:
self.cli = "gh" if "github.com" in origin else "tea"
self.ran: list[str] = []
self.commands: list[list[str]] = []
@@ -38,12 +38,13 @@ class Forge:
"git remote": origin + "\n",
"git rev-parse": HEAD + "\n",
"git symbolic-ref": "origin/main\n",
"git config": Failure("git config: unset"),
"gh pr list": pulls,
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments)}),
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments), "mergeable": mergeable, "mergeStateStatus": merge_state, "baseRefName": base}),
"gh pr checks": json.dumps([{"bucket": bucket} for bucket in buckets]),
"gh api graphql": json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": list(threads)}}}}}),
"tea api repos/{owner}/{repo}/pulls?state=open&limit=50": json.dumps([{"number": 7, "merged": False, "head": {"label": "ABC-21", "sha": HEAD, "repo": {"full_name": "o/billing"}}, "base": {"repo": {"full_name": "o/billing"}}}]),
"tea api repos/{owner}/{repo}/pulls/7": json.dumps({"number": 7, "title": title}),
"tea api repos/{owner}/{repo}/pulls/7": json.dumps({"number": 7, "title": title, "mergeable": mergeable == "MERGEABLE", "base": {"ref": base}}),
"tea api repos/{owner}/{repo}/branches/main": '{"name": "main"}',
"tea api repos/{owner}/{repo}/commits/" + HEAD + "/status": status,
}
@@ -79,6 +80,26 @@ class GateOfAChunk(unittest.TestCase):
self.assertEqual(forge.gate(by_human=True), Gate("/code/billing-ABC-21", "7", MERGE))
self.assertEqual(Forge(decision="APPROVED").gate(by_human=False), Open("pull request #7 passed its checks and is approved"))
def test_where_a_person_merges_a_pull_request_that_no_longer_merges_into_its_base_is_news_to_level_it(self):
gitea = "https://gitea.larvit.se/o/billing.git"
again = "run chunk-pr merge again to level the branch"
self.assertEqual(Forge(decision="APPROVED", mergeable="CONFLICTING", merge_state="DIRTY").gate(by_human=True), Unmergeable(f"pull request #7 conflicts with its base branch; {again}"))
self.assertEqual(Forge(gitea, mergeable="CONFLICTING").gate(by_human=True), Unmergeable(f"pull request #7 conflicts with its base branch; {again}"))
self.assertEqual(Forge(decision="", merge_state="BEHIND").gate(by_human=True), Unmergeable(f"pull request #7 is behind its base branch, whose protection requires it up to date; {again}"))
def test_where_a_person_merges_a_pull_request_awaits_that_merge_while_github_computes_whether_it_merges(self):
self.assertEqual(Forge(decision="APPROVED", mergeable="UNKNOWN", merge_state="UNKNOWN").gate(by_human=True), Gate("/code/billing-ABC-21", "7", MERGE))
def test_where_a_person_merges_a_mergeability_that_cannot_be_read_is_a_failure(self):
forge = Forge("https://gitea.larvit.se/o/billing.git")
forge.answers["tea api repos/{owner}/{repo}/pulls/7"] = '{"number": 7, "title": "Add x"}'
self.assertEqual(forge.gate(by_human=True), Failure("tea api answered pull request 7 in a shape that can't be read: {'number': 7, 'title': 'Add x'}"))
def test_where_the_chunk_merges_nobody_reads_whether_the_pull_request_merges(self):
forge = Forge(decision="APPROVED", mergeable="CONFLICTING")
self.assertEqual(forge.gate(), Open("pull request #7 passed its checks and is approved"))
self.assertNotIn(["gh", "pr", "view", "7", "--json", "mergeable,mergeStateStatus"], forge.commands)
def test_where_a_person_merges_every_other_gate_and_all_news_stay_as_they_are(self):
same = (Forge(), Forge(buckets=("pending",)), Forge(draft=True), Forge(decision="CHANGES_REQUESTED"), Forge(threads=(thread(False, "reviewer"),)), Forge(buckets=("fail",)), Forge(pulls=""))
for forge in same:
@@ -100,6 +121,24 @@ class GateOfAChunk(unittest.TestCase):
self.assertEqual(Forge(gitea, status='{"state": "pending", "total_count": 1}').gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
self.assertEqual(Forge(gitea).gate(), Open("pull request #7 passed its checks"))
def test_a_chunk_that_merges_into_an_epics_working_branch_reads_the_checks_that_branch_requires(self):
forge = Forge("https://gitea.larvit.se/o/billing.git", base="ABC-12")
forge.answers["git config"] = "ABC-12\n"
forge.answers["tea api repos/{owner}/{repo}/branches/ABC-12"] = '{"enable_status_check": true, "status_check_contexts": ["epic-gate"]}'
self.assertEqual(forge.gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
self.assertIn(["git", "config", "--get", "branch.ABC-21.chunk-base"], forge.commands)
self.assertNotIn(["tea", "api", "repos/{owner}/{repo}/branches/main"], forge.commands)
def test_a_pull_request_the_forge_merges_into_another_branch_than_the_checkout_records_is_a_failure_naming_both(self):
differs = "pull request #7 merges into {} on the forge, but this checkout takes {} as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config"
for origin in ("git@github.com:o/billing.git", "https://gitea.larvit.se/o/billing.git"):
with self.subTest(origin):
recorded = Forge(origin, decision="APPROVED")
recorded.answers["git config"] = "ABC-12\n"
self.assertEqual(recorded.gate(by_human=False), Failure(differs.format("main", "ABC-12")), "no pull request into the default branch reads as one that merges without a person")
self.assertNotIn(["tea", "api", "repos/{owner}/{repo}/branches/ABC-12"], recorded.commands)
self.assertEqual(Forge(origin, decision="APPROVED", base="ABC-12").gate(by_human=True), Failure(differs.format("ABC-12", "main")))
def test_a_gitea_draft_awaits_nothing_though_its_checks_run(self):
gitea = "https://gitea.larvit.se/o/billing.git"
for title in ("WIP: Add x", "[wip] Add x"):
+32
View File
@@ -11,6 +11,7 @@ from do_epic.test_main import DESCRIPTION, Description, DoEpicTest, MODELS, UNRE
from do_epic.epic_record import EpicRecord
from failure import Failure
from loop_effects.doubles import FakeEffects
from do_epic.human_tasks import holds_up
from do_epic.scheduler import HUMAN_WAIT
from do_epic.test_scheduler import issue
from do_epic.backend.fake import MemoryEpic
@@ -49,6 +50,37 @@ class AHumanTaskThatBlocksAnIssue(DoEpicTest):
self.slept = slept
return self.run_main(["--chunk", "ABC-19", "ABC-12"], fake, MODELS)
def moved_to_an_unblocking_status(self, switch: str, frees: tuple[str, dict[str, object]] = ("ABC-19", {"status": "Release Ready"}), starts: str = "ABC-21") -> bool:
"""Whether Jira counts the task done after its window's run, where the config ends with switch. frees is the change in Jira that ends the wait: by default the human moves the task to an unblocking status. starts is what the window then starts."""
with (self.home / ".claude-projects" / "do-epic" / "config.toml").open("a") as config:
config.write('jira-unblocking-statuses = ["Release Ready"]\n' + switch)
fake = FakeEffects(git=UNREAD, windows=WINDOW)
slept: list[int] = []
def sleep(seconds: int) -> None:
slept.append(seconds)
self.assertLess(len(slept), 5, "the window still waits")
if len(slept) == 2:
self.epic.change(frees[0], **frees[1])
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
code, out, err = self.run_main(["--chunk", "ABC-19", "ABC-12"], fake, MODELS)
self.assertEqual((code, err, slept), (0, "", [60, 60]))
self.assertIn(f"the chunk finished; started {starts}\n", out)
return next(each.done for each in self.epic.issues if each.key == "ABC-19")
def test_a_task_the_human_moves_to_an_unblocking_status_no_longer_holds_up_an_issue_and_moves_to_done(self) -> None:
self.assertTrue(self.moved_to_an_unblocking_status(""))
def test_where_the_teams_automation_moves_issues_the_humans_task_stays_where_the_human_moved_it(self) -> None:
self.assertFalse(self.moved_to_an_unblocking_status("jira-automation-moves-issues = true\n"))
def test_where_the_teams_automation_moves_issues_a_task_that_blocks_no_open_issue_any_more_ends_its_window_unmoved(self) -> None:
self.assertFalse(self.moved_to_an_unblocking_status("jira-automation-moves-issues = true\n", ("ABC-21", {"done": True}), starts="no other"))
def test_a_task_holds_up_only_the_issues_no_unblocking_status_settles(self) -> None:
issues = [issue("ABC-19", "do-epic-human"), issue("ABC-20", "do-epic-claude", blockers=("ABC-19",), status="Release Ready"), issue("ABC-21", "do-epic-claude", blockers=("ABC-19",))]
self.assertEqual(holds_up("ABC-19", issues, {}, ("Release Ready",)), ["ABC-21"])
def test_dms_the_human_once_parks_its_window_and_polls_until_the_issue_closes_then_starts_the_next(self) -> None:
fake = FakeEffects(git=UNREAD, windows=WINDOW)
code, out, err = self.awaited(fake, closes_after=3)
+76
View File
@@ -0,0 +1,76 @@
import json
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.issue_scores import answer_of, asked, prompt, SCHEMA, Scores
from do_epic.test_repo_pick import Claude, says
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from model_routing.ladder import Rung
ANSWER = {"L": 2, "E": 1, "I": 2, "S": 3, "moves": " epic 1 by 5 ", "comment": " Scored to pick what starts first. "}
ISSUE = EpicIssue("ABC-13", "Count the runs", "Count each run once.", ("api",), None, "To Do", False, "ABC-12")
def expected(output: object) -> Failure:
return Failure(f"the scoring answered {json.dumps(output)}; expected a whole number for each of L, E, I, S, the moves as text and a comment")
class TheAnswer(unittest.TestCase):
def test_reads_the_scores_the_moves_and_the_comment(self) -> None:
self.assertEqual(answer_of(ANSWER), Scores({"L": 2, "E": 1, "I": 2, "S": 3}, "epic 1 by 5", "Scored to pick what starts first."))
def test_refuses_an_answer_that_is_not_an_object(self) -> None:
self.assertEqual(answer_of(["L", 2]), expected(["L", 2]))
def test_refuses_a_score_that_is_not_a_whole_number(self) -> None:
for score in ("2", 2.0, True, None):
with self.subTest(score=score):
self.assertEqual(answer_of(ANSWER | {"I": score}), expected(ANSWER | {"I": score}))
def test_refuses_moves_that_are_not_text(self) -> None:
self.assertEqual(answer_of(ANSWER | {"moves": None}), expected(ANSWER | {"moves": None}))
def test_refuses_an_answer_without_a_comment(self) -> None:
for comment in (None, " ", 5):
with self.subTest(comment=comment):
self.assertEqual(answer_of(ANSWER | {"comment": comment}), expected(ANSWER | {"comment": comment}))
def test_quotes_the_first_200_characters_of_an_answer_it_refuses(self) -> None:
long = {"comment": "c" * 300}
self.assertEqual(answer_of(long), Failure(f"the scoring answered {json.dumps(long)[:200]}; expected a whole number for each of L, E, I, S, the moves as text and a comment"))
class TheCall(unittest.TestCase):
def ask(self, claude: Claude, issue: EpicIssue = ISSUE) -> object:
return asked(issue, "L is the chance of a defect.", "An item moves only these: `epic 1`.", "Swedish", Rung("claude-sonnet-5-5", "medium"), claude, "/state/scoring")
def test_asks_claude_for_a_json_reply_on_the_given_rung_and_without_tools(self) -> None:
claude = says(ANSWER)
self.assertEqual(self.ask(claude), answer_of(ANSWER))
args, cwd, _ = claude.calls[0]
self.assertEqual(cwd, "/state/scoring")
self.assertEqual(args[:10], ["-p", "--json-schema", json.dumps(SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", "", "--strict-mcp-config"])
def test_names_the_scoring_where_claude_fails(self) -> None:
failed = self.ask(Claude("", 1))
assert isinstance(failed, Failure), failed
self.assertEqual(failed.reason, "the scoring exited 1")
def test_puts_the_rule_the_goals_the_language_and_the_item_in_the_prompt(self) -> None:
text = prompt(ISSUE, "L is the chance of a defect.", "An item moves only these: `epic 1`.", "Swedish")
for part in ("L is the chance of a defect.", "An item moves only these: `epic 1`.", "Write the comment in Swedish", "## Item ABC-13: Count the runs", "Labels: api", "Count each run once."):
with self.subTest(part=part):
self.assertIn(part, text)
self.assertNotIn("(no description)", text)
def test_says_where_the_item_has_no_labels_or_description(self) -> None:
text = prompt(EpicIssue("ABC-13", "Count the runs", "", (), None, "To Do", False, "ABC-12"), "Rule.", "Goals.", "English")
self.assertTrue(text.endswith("Labels: none\n\n(no description)\n"), text[-60:])
if __name__ == "__main__":
unittest.main()
+535 -6
View File
@@ -7,11 +7,12 @@ import shutil
import subprocess
import sys
import tempfile
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic import chunk_prompt, main
from do_epic import chunk_prompt, epic_run, main, planning
from chunk_driver.chunk_run import ChunkRun
from project_config.doubles import configured
from do_epic.config import DoEpicConfig
@@ -30,6 +31,7 @@ from text_files.file_writes import replace_file
from model_routing.route import Route
from model_routing.ladder import Rung
from do_epic.test_do_epic import SETTINGS
from do_epic.backend.jira_start import Start
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
@@ -84,11 +86,11 @@ class DoEpicTest(unittest.TestCase):
self.issues = [issue("ABC-20", "repo:api")]
return folder
def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> main.EpicRun:
def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> epic_run.EpicRun:
config = main.load(self.home)
assert not isinstance(config, Failure)
store, record = self.backend(config, "ABC-12")
return main.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects())
return epic_run.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects())
def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
@@ -104,6 +106,16 @@ class TheJiraBackend(unittest.TestCase):
self.assertEqual((store.epic, store.env_file, store.finish), (Epic("https://acme.atlassian.net", "ABC-12"), pathlib.Path("/h/jira.env"), Finish("Mark as done", "Done"))) # type: ignore[attr-defined]
self.assertEqual((record.description.epic, record.description.env_file), (store.epic, store.env_file)) # type: ignore[attr-defined]
def test_starts_an_issue_as_the_config_says(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", start=Start("In Progress", 6))
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual(store.start, Start("In Progress", 6)) # type: ignore[attr-defined]
def test_files_the_issue_types_the_config_names(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", finding_type="Feature", review_type="Chore")
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual((store.finding_type, store.review_type), ("Feature", "Chore")) # type: ignore[attr-defined]
class TheLauncher(unittest.TestCase):
def test_the_repo_ships_a_do_epic_that_prints_its_help(self) -> None:
@@ -158,6 +170,7 @@ class TheCommand(DoEpicTest):
code, out, err = self.run_main(["ABC-12"], FakeEffects())
self.assertEqual(code, 0, err)
self.assertIn("the epic ABC-12 is not planned in full: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", err)
self.assertTrue(err.endswith("(2**S + 32)`\n"))
self.assertIn("started ABC-20, ABC-21 in the tmux session epic-ABC-12\n", out)
def test_stops_on_an_epic_it_cannot_read(self) -> None:
@@ -267,7 +280,9 @@ MODELS = {"LOOP_CLAUDE_JUDGE_MODEL": "claude-opus-5-5", "LOOP_CLAUDE_WORKER_MODE
class TheHumansRun(DoEpicTest):
def test_shows_the_session_on_a_terminal_and_says_when_tmux_cannot(self) -> None:
fake = FakeEffects(windows="ABC-21\t0\t@9\n")
self.assertEqual(self.run_main(["ABC-12"], fake)[0], 0)
code, out, err = self.run_main(["ABC-12"], fake)
self.assertEqual((code, err), (0, ""))
self.assertEqual(out, "<1790000000> started no chunk\n<1790000000> ABC-20 waits: it is a human's task\n")
self.assertEqual(fake.tmux_calls[-1], ["attach-session", "-t", "=epic-ABC-12"])
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, tmux_on_terminal=lambda args: 1) # type: ignore[method-assign]
code, _, err = self.run_main(["ABC-12"], fake, {"TMUX": "/tmp/tmux"})
@@ -284,14 +299,14 @@ class TheHumansRun(DoEpicTest):
def test_off_a_terminal_it_says_how_to_see_the_chunks(self) -> None:
code, out, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False, windows="ABC-21\t0\t@9\n"))
self.assertEqual((code, err), (0, ""))
self.assertIn("not on a terminal; see the chunks with `tmux attach -t =epic-ABC-12`\n", out)
self.assertTrue(out.endswith("not on a terminal; see the chunks with `tmux attach -t =epic-ABC-12`\n"))
def test_with_no_window_in_the_session_it_shows_none(self) -> None:
self.issues = self.issues[:1]
fake = FakeEffects()
code, out, _ = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0)
self.assertIn("started no chunk\n", out)
self.assertEqual(out, "<1790000000> started no chunk\n<1790000000> ABC-20 waits: it is a human's task\n")
self.assertNotIn("attach-session", [args[0] for args in fake.tmux_calls])
def test_stops_without_its_settings_or_on_a_cap_it_cannot_read(self) -> None:
@@ -360,6 +375,32 @@ class AChunksRun(DoEpicTest):
# The one claude call is the judge's: ABC-22, which no label places, waits for the human's do-epic.
self.assertEqual(len(fake.made("claude")), 1)
def started(self, store: MemoryEpic) -> str:
"""What the chunk of ABC-21 prints as it runs to its end on store."""
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[assignment, method-assign, arg-type]
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n"), MODELS)
self.assertEqual(code, 0, err)
return out
def test_a_starting_chunk_starts_its_issue_in_the_tracker_before_its_first_cycle(self) -> None:
store = MemoryEpic("ABC-12", list(self.issues))
out = self.started(store)
self.assertEqual((store.writes[0], store.issues[1].assignee), ("start ABC-21", "do-epic"))
self.assertNotIn("assigned", out.partition("=== cycle 1")[0])
def test_a_starting_chunk_says_who_else_holds_its_issue_and_leaves_it_theirs(self) -> None:
store = MemoryEpic("ABC-12", [self.issues[0], dataclasses.replace(self.issues[1], assignee="Ada Berg")])
self.assertIn("ABC-21 stays assigned to Ada Berg\n", self.started(store).partition("=== cycle 1")[0])
self.assertEqual(store.issues[1].assignee, "Ada Berg")
def test_a_chunk_runs_though_its_issue_could_not_start_in_the_tracker_and_says_why(self) -> None:
class Unstartable(MemoryEpic):
def start_issue(self, key: str) -> str | None | Failure:
return Failure(f"cannot assign {key}: Jira answered 403")
out = self.started(Unstartable("ABC-12", list(self.issues)))
self.assertIn("not every step that starts ABC-21 in the tracker was made, and its chunk runs all the same: cannot assign ABC-21: Jira answered 403\n", out.partition("=== cycle 1")[0])
self.assertIn("the chunk finished", out)
def test_runs_cycles_until_the_judge_rules_it_finished_then_starts_the_next_chunk(self) -> None:
self.issues.append(issue("ABC-22", "do-epic-claude"))
self.description = DESCRIPTION.replace("2", "1")
@@ -449,6 +490,18 @@ class AChunksRun(DoEpicTest):
self.assertEqual(code, 0, err)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_where_the_teams_automation_moves_issues_a_finished_chunk_without_a_repo_still_moves_its_own(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n', encoding="utf-8")
parent = issue("ABC-23", "split-by-repo")
store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-21", "do-epic-claude", parent="ABC-23"), issue("ABC-22", "do-epic-claude", blockers=("ABC-23",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
# No pull request carries ABC-21, so do-epic moves it; its split item, then all done, closes as ever.
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-23": True, "ABC-21": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_the_last_sub_task_of_a_split_item_to_finish_moves_the_item_to_done_and_starts_what_it_blocks(self) -> None:
parent = issue("ABC-21", "split-by-repo")
tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)]
@@ -460,6 +513,29 @@ class AChunksRun(DoEpicTest):
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-23": True, "ABC-24": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_the_last_sub_task_a_person_filed_to_finish_moves_its_parent_to_done_and_starts_what_it_blocks(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)]
store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), *tasks, issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-23": True, "ABC-24": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_a_parent_jira_will_not_move_is_said_and_the_next_chunk_still_starts(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-22", "do-epic-claude")])
finish = store.finish_issue
store.finish_issue = lambda key: Failure("no way to done") if key == "ABC-21" else finish(key) # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("ABC-21's sub-tasks are all done, but it did not move to done: no way to done; close it in Jira\n", out)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_a_sub_task_that_leaves_another_open_leaves_its_split_item_open(self) -> None:
parent = issue("ABC-21", "split-by-repo")
store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21")])
@@ -746,6 +822,20 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
self.assertIn(fact, prompts[1].split("\n\n")[0])
self.assertNotIn("parked: ", out)
def test_where_a_person_merges_a_finished_chunk_whose_pull_request_no_longer_merges_is_told_until_it_does(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
for unmergeable, why in (({"mergeable": "CONFLICTING"}, "conflicts with its base branch"), ({"merge_state": "BEHIND"}, "is behind its base branch")):
with self.subTest(why=why):
self.forges = [awaiting(decision="APPROVED", **unmergeable), awaiting(decision="APPROVED", **unmergeable), CLEANED]
self.gate_reads = 0
fake = FakeEffects(streams=[self.worker(), self.worker(), self.worker()], claude=[judged("finished"), judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 3), err)
for prompt in prompts[1:]:
for fact in ("keeps the chunk open while its pull request doesn't merge into its base", f"pull request #7 {why}", "run chunk-pr merge again"):
self.assertIn(fact, prompt.split("\n\n")[0])
self.assertNotIn("parked: ", out)
def test_where_a_person_merges_an_unfinished_chunk_goes_on_without_news_or_a_wait(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(pulls=""), awaiting(decision="APPROVED", fails="gh pr checks"), CLEANED]
@@ -763,6 +853,27 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
code, _, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 1), err)
def test_where_the_teams_automation_moves_issues_a_finished_chunk_in_a_repo_moves_none_and_waits_for_the_move(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8")
store = MemoryEpic("ABC-12", [*self.issues[:-1], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.forges = [awaiting(pulls="")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
slept: list[float] = []
def sleep(seconds: float) -> None:
slept.append(seconds)
store.fails = "Jira answered 503" if len(slept) in (1, 2) else None
if len(slept) == 4:
store.change("ABC-20", status="Release Ready")
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
code, out, err, _ = self.parked_run(fake)
self.assertEqual((code, slept), (0, [60, 60, 60, 60]), err)
self.assertEqual(out.count("cannot read the epic, so cannot tell whether ABC-20 has moved; trying again every 60 seconds: Jira answered 503\n"), 1, out)
self.assertEqual([(each.status, each.done) for each in store.issues if each.key == "ABC-20"], [("Release Ready", False)])
self.assertEqual(out.count("ABC-20 is To Do: it waits for the team's automation to move it to Release Ready or Shipped; move it in Jira if the automation doesn't\n"), 1, out)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_where_the_chunk_merges_an_approved_pull_request_parks_no_chunk(self) -> None:
self.forges = [awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
@@ -896,6 +1007,270 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
self.assertIn(f"cannot remove {self.file}: Permission denied", err)
class StepwiseStore:
"""A store whose workflow reaches each status in `after` only from the status it names there; every other call is the wrapped store's."""
def __init__(self, store: typing.Any, after: dict[str, str]) -> None:
self.store, self.after = store, after
def __getattr__(self, name: str) -> typing.Any:
return getattr(self.store, name)
def move_issue(self, key: str, status: str) -> None | Failure:
now = self.store.within(key).status
if status in self.after and now not in (status, self.after[status]):
return Failure(f"{key} has no transition to {status!r} from its status {now!r}")
return self.store.move_issue(key, status)
class LaggingStore:
"""A store whose every read answers `read`, as a search that doesn't show the latest move yet; every other call is the wrapped store's."""
def __init__(self, store: typing.Any, read: typing.Any) -> None:
self.store, self.answer = store, read
def __getattr__(self, name: str) -> typing.Any:
return getattr(self.store, name)
def read(self) -> typing.Any:
return self.answer
class AnEpicsWorkingBranch(DoEpicTest):
"""A chunk in a repo whose config sets `epic-branch`, so its pull request goes into the branch ABC-12."""
def setUp(self) -> None:
super().setUp()
self.repo_config = self.repo_chunk() / "config.toml"
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'epic-branch = "{epic}"\nmerge = "human"\n', encoding="utf-8")
self.checkout = str(self.home / "code/api")
self.store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
self.backend = lambda config, key: (self.store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.git_calls: list[tuple[tuple[str, ...], str | None]] = []
self.git_timeouts: list[tuple[str, object]] = []
def settings(self, more: str) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8")
def with_git(self, fake: FakeEffects, **answers: str | Failure) -> FakeEffects:
"""fake, whose git answers each command by its first word: as answers has it, else as a checkout whose origin has the branch ABC-12, which holds origin/main."""
answered = {"symbolic-ref": "origin/main\n", "fetch": "", "ls-remote": "aaa\trefs/heads/ABC-12\n", "rev-parse": "aaa\n", "rev-list": "0\n", "config": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def git(*args: str, cwd: str | None = None, **more: object) -> str | Failure:
self.git_calls.append((args, cwd))
self.git_timeouts.append((args[0], more.get("timeout")))
return answered.get(args[0], Failure("no git"))
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, git=git) # type: ignore[method-assign]
return fake
def recorded(self, **answers: object) -> Forge:
"""A forge like `awaiting`'s, in a checkout that records ABC-12 as the base of ABC-20's branch."""
forge = awaiting(**answers)
forge.answers["git config"] = "ABC-12\n"
return forge
def test_a_chunk_that_starts_levels_the_branch_and_records_it_as_the_chunks_base(self) -> None:
fake = self.with_git(FakeEffects())
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.epic_based("ABC-20", self.checkout, self.epic_run(fake)), "ABC-12")
self.assertEqual(self.git_calls, [(args, self.checkout) for args in (("symbolic-ref", "--short", "refs/remotes/origin/HEAD"), ("ls-remote", "--heads", "origin", "refs/heads/ABC-12"), ("fetch", "--quiet", "origin"), ("rev-list", "--count", "origin/ABC-12..origin/main"), ("config", "branch.ABC-20.chunk-base", "ABC-12"))])
self.assertIn("origin/ABC-12 already holds origin/main; ABC-20's pull request goes into ABC-12\n", out.getvalue())
def test_a_call_to_origin_that_levels_the_branch_is_stopped_after_a_minute_so_no_window_hangs_before_its_first_cycle(self) -> None:
main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), ls_remote="", push="")))
self.assertEqual([timed for timed in self.git_timeouts if timed[0] in ("fetch", "ls-remote", "push")], [("ls-remote", 60), ("fetch", 60), ("push", 60), ("fetch", 60)])
def test_says_the_default_branchs_whole_name_however_it_ends(self) -> None:
out = io.StringIO()
with contextlib.redirect_stdout(out):
main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), symbolic_ref="origin/BOX\n")))
self.assertIn("origin/ABC-12 already holds origin/BOX; ABC-20's pull request goes into ABC-12\n", out.getvalue())
def test_a_folder_no_checkout_holds_stops_with_the_reason_its_config_cannot_be_found(self) -> None:
elsewhere = self.home / "elsewhere"
elsewhere.mkdir()
unnamed = main.config_located(str(elsewhere), self.home)
assert isinstance(unnamed, Failure), unnamed
self.assertEqual(main.epic_based("ABC-20", str(elsewhere), self.epic_run(self.with_git(FakeEffects()))), main.Stop(1, unnamed.reason))
def test_a_repo_whose_config_sets_no_epic_branch_has_none_and_runs_no_git(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8").replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
self.assertIsNone(main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects()))))
self.assertEqual(self.git_calls, [])
def test_a_default_branch_that_conflicts_stops_the_loop_for_a_person_and_records_no_base(self) -> None:
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), rev_list="1\n", merge_tree=Failure("git merge-tree --write-tree origin/ABC-12 origin/main: "))))
self.assertEqual(stop, main.Stop(1, f"cannot ready the epic's working branch ABC-12 in {self.checkout} for ABC-20: origin/main doesn't merge into origin/ABC-12 cleanly, so a person merges it: check ABC-12 out, run `git merge origin/main`, resolve the conflicts and push; once that is settled, run `do-epic ABC-12` to start the chunk again"))
self.assertNotIn("config", [args[0] for args, _ in self.git_calls])
def test_a_checkout_that_names_no_default_branch_stops_before_the_branch_is_touched(self) -> None:
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), symbolic_ref=Failure("no origin/HEAD"))))
self.assertIsInstance(stop, main.Stop)
self.assertIn("no origin/HEAD", stop.reason)
self.assertEqual(len(self.git_calls), 1)
def test_a_chunk_whose_working_branch_cannot_be_readied_leaves_its_issue_unstarted(self) -> None:
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], self.with_git(FakeEffects(), rev_list="1\n", merge_tree=Failure("git merge-tree --write-tree origin/ABC-12 origin/main: ")), MODELS)
self.assertEqual(code, 1)
self.assertIn("cannot ready the epic's working branch ABC-12", err)
self.assertEqual(self.store.writes, [])
def test_its_issue_moves_as_the_pull_request_opens_and_merges_and_no_person_merges_it(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
self.assertEqual(code, 0, err)
self.assertEqual([write for write in self.store.writes if write.startswith("move ")], ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
self.assertEqual({each.key: (each.status, each.done) for each in self.store.issues}["ABC-20"], ("Release Ready", False))
# Approved, the pull request awaits no person's merge, though the repo's config says `merge = "human"`.
self.assertEqual(out.count("parked: "), 1)
self.assertIn("parked: pull request #7 awaits an approval\n", out)
self.assertIn("the chunk finished; started ABC-22\n", out)
self.assertIn("The chunk's pull request goes into the epic's working branch `ABC-12`", prompts[0])
self.assertIn(("config", "branch.ABC-20.chunk-base", "ABC-12"), [args for args, _ in self.git_calls])
def test_a_chunk_parked_on_a_persons_merge_into_the_default_branch_stays_parked_until_its_pull_request_goes_into_the_branch(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts)
parked.park(self.home / ".local/state/do-epic/ABC-12", parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(session.id), "your merge"))
self.worker()(["--session-id", str(session.id)])
# The pull request was opened into main before the setting was on; a person then changes its base to ABC-12.
self.forges = [self.recorded(decision="APPROVED"), self.recorded(decision="APPROVED"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker()], claude=[judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
self.assertEqual(code, 0, err)
self.assertEqual(out.count("cannot read the gate: pull request #7 merges into main on the forge, but this checkout takes ABC-12 as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config; trying again every 60 seconds\n"), 1)
self.assertEqual(len(prompts), 1)
self.assertTrue(prompts[0].startswith("do-epic parked the chunk while its pull request awaited a person's merge. It resumes now: pull request #7 passed its checks and is approved. "), prompts[0])
def test_a_chunk_that_started_before_the_setting_was_on_keeps_its_merge_for_a_person(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
set_on = self.repo_config.read_text(encoding="utf-8")
self.repo_config.write_text(set_on.replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
worker = self.worker()
def turns_the_setting_on(args: list[str]) -> object:
self.repo_config.write_text(set_on, encoding="utf-8")
return worker(args)
self.forges = [awaiting(decision="APPROVED"), awaiting(decision="APPROVED"), awaiting(pulls=""), CLEANED]
fake = self.with_git(FakeEffects(streams=[turns_the_setting_on, self.worker()], claude=[judged("unfinished"), judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertNotIn("config", [args[0] for args, _ in self.git_calls], "no base recorded, so the pull request goes into the default branch")
self.assertIn("parked: pull request #7 awaits your merge\n", out)
self.assertNotIn("move ABC-20 to Code Review", self.store.writes)
def test_an_issue_that_cannot_move_to_the_open_status_says_so_and_its_chunk_goes_on(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.backend = lambda config, key: (StepwiseStore(self.store, {"Code Review": "QA"}), EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("ABC-20 did not move to 'Code Review' though its pull request is open: ABC-20 has no transition to 'Code Review' from its status 'To Do'\n", out)
def test_a_finished_chunk_whose_issue_has_no_pull_request_into_the_epic_branch_moves_it_to_done(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.WITH_A_HUMAN).code, 0)
self.assertEqual((self.store.issues[0].status, self.store.issues[0].done), ("Done", True))
# A chunk not marked as in a repo moves its issue to done itself, even where the automation moves issues.
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
self.store.change("ABC-22", status="Release Ready")
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(main.handed_on("ABC-22", self.epic_run(FakeEffects(windows=""))).code, 0)
self.assertEqual((self.store.issues[1].status, self.store.issues[1].done), ("Done", True))
def test_a_read_that_does_not_show_the_move_yet_still_counts_the_issue_moved(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
before = self.store.read()
lagging = LaggingStore(self.store, before)
out = io.StringIO()
with contextlib.redirect_stdout(out):
stop = main.handed_on("ABC-20", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=lagging), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertIn("the chunk finished; started ABC-22\n", out.getvalue())
unread = LaggingStore(self.store, Failure("Jira answered 503"))
stop = main.handed_on("ABC-22", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=unread), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but the next could not start: Jira answered 503"))
def test_the_epics_finishing_is_due_once_every_issue_has_the_merged_status(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
for each in ("ABC-20", "ABC-22"):
self.store.change(each, status="Release Ready")
self.assertIsInstance(main.chunk_work("ABC-12", None, "English", self.epic_run(FakeEffects())), tuple)
def test_without_a_merged_status_a_finished_chunk_stops_where_automation_moves_issues_and_is_done_where_it_doesnt(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `jira-pull-request-merged-status` to move it to. Move ABC-20 in Jira, then run `do-epic ABC-12` to start the chunks it blocks"))
self.assertEqual(self.store.writes, [])
self.settings("")
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.ON_EPIC_BRANCH).code, 0)
self.assertTrue(self.store.issues[0].done)
def test_an_issue_whose_workflow_reaches_the_merged_status_only_through_the_open_status_moves_through_it(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
epic = self.epic_run(FakeEffects(windows=""))
stepwise = StepwiseStore(self.store, {"Release Ready": "Code Review"})
with contextlib.redirect_stdout(io.StringIO()):
stop = main.handed_on("ABC-20", dataclasses.replace(epic, store=stepwise), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertEqual(self.store.writes, ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
# An issue the open status doesn't lead on from stops on the move it asked for.
stuck = StepwiseStore(self.store, {"Release Ready": "QA", "Code Review": "QA"})
stop = main.handed_on("ABC-22", dataclasses.replace(epic, store=stuck), main.Landed.ON_EPIC_BRANCH)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': ABC-22 has no transition to 'Release Ready'"), stop.reason)
def test_an_issue_that_cannot_move_to_the_merged_status_stops_and_says_what_to_do(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
self.store.fails = "Jira answered 503"
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': "), stop.reason)
self.assertTrue(stop.reason.endswith("once it has that status in Jira, run `do-epic ABC-12` to start the chunks it blocks"), stop.reason)
class TheMoveOfAFinishedChunksIssue(unittest.TestCase):
def move(self, landed: main.Landed, automated: bool, merged: str | None = None, opened: str | None = None, finishing: bool = False) -> main.Move:
return main.issue_move(landed, automated, merged, opened, finishing)
def test_the_epics_finishing_has_no_issue_to_move(self) -> None:
for automated in (False, True):
with self.subTest(automated=automated):
self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review", finishing=True), main.How.LEFT)
def test_a_humans_task_is_left_where_the_automation_moves_issues_and_done_otherwise(self) -> None:
self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, True, "Release Ready"), main.How.LEFT)
self.assertEqual(self.move(main.Landed.WITH_A_HUMAN, False, "Release Ready"), main.How.TO_DONE)
def test_a_chunk_without_a_repo_moves_to_done(self) -> None:
for automated in (False, True):
with self.subTest(automated=automated):
self.assertEqual(self.move(main.Landed.NOWHERE, automated, "Release Ready", "In Review"), main.How.TO_DONE)
def test_work_on_the_default_branch_awaits_the_automation_or_moves_to_done(self) -> None:
self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, True, "Release Ready", "In Review"), main.How.AWAITED)
self.assertEqual(self.move(main.Landed.ON_DEFAULT_BRANCH, False, "Release Ready", "In Review"), main.How.TO_DONE)
def test_work_on_the_epics_branch_moves_to_the_merged_status_through_the_open_one_where_named(self) -> None:
for automated in (False, True):
with self.subTest(automated=automated):
self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready", "In Review"), main.ToStatus("Release Ready", "In Review"))
self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, automated, "Release Ready"), main.ToStatus("Release Ready", None))
def test_work_on_the_epics_branch_with_no_merged_status_is_stuck_under_automation_and_done_otherwise(self) -> None:
self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, None, "In Review"), main.How.STUCK)
self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, True, "", "In Review"), main.How.STUCK)
self.assertEqual(self.move(main.Landed.ON_EPIC_BRANCH, False, None, "In Review"), main.How.TO_DONE)
class TheStatus(DoEpicTest):
def test_prints_what_each_open_issue_does_and_starts_nothing(self) -> None:
self.issues = [issue("ABC-21", "repo:api"), issue("ABC-24", "repo:api"), issue("ABC-27")]
@@ -910,6 +1285,25 @@ class TheStatus(DoEpicTest):
self.assertEqual({args[0] for args in fake.tmux_calls}, {"-V", "list-windows"})
self.assertTrue(all("epic-ABC-12" in " ".join(args) for args in fake.tmux_calls if args[0] == "list-windows"), fake.tmux_calls)
def test_says_which_issue_starts_after_those_that_start_by_score(self) -> None:
self.issues = [issue("ABC-21", "do-epic-claude"), dataclasses.replace(issue("ABC-24", "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1})]
room = "it has not started; `do-epic ABC-12` starts it once the epic and its repo have room"
out = self.run_main(["ABC-12", "--status"], FakeEffects())[1]
self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [f"ABC-21 waits: {room}, after each issue that holds every score, since it doesn't", f"ABC-24 waits: {room}"])
def test_clones_no_missing_repo_to_print_the_status(self) -> None:
for repo in ("api", "web"):
configured(self, self.home / "code" / repo, home=self.home)
(self.home / "code" / repo / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
shutil.rmtree(self.home / "code/web")
self.description = DESCRIPTION + "\n## Scoring\n`Score = V`\n"
self.issues = [dataclasses.replace(issue(key, label), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key, label in (("ABC-20", "repo:api"), ("ABC-22", "repo:web"))]
fake = FakeEffects(git=["git@host.example:team/api.git"] * 3)
code, out, _ = self.run_main(["ABC-12", "--status"], fake)
self.assertEqual(code, 0)
self.assertIn("ABC-20 waits: it has not started", out)
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_says_so_where_no_issue_is_open_or_the_epic_cannot_be_read(self) -> None:
self.issues = [issue("ABC-20", "repo:api", done=True)]
self.assertIn("the epic ABC-12 has no open issue\n", self.run_main(["ABC-12", "--status"], FakeEffects())[1])
@@ -921,6 +1315,141 @@ class TheStatus(DoEpicTest):
self.assertIn("Jira answered 503\n", err)
BANNER = "dry run: nothing is written to Jira and no window starts, so a line below that says an issue is labelled, split or scored shows what a real run would do. A real run would also start in Jira the issue of each chunk it starts: assign it and, where config.toml says so, move it and add it to a sprint"
class TheDryRun(DoEpicTest):
def setUp(self) -> None:
super().setUp()
for repo in ("api", "web"):
configured(self, self.home / "code" / repo, home=self.home)
(self.home / "code" / repo / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
self.stores: list[MemoryEpic] = []
made = self.backend
self.backend = lambda config, key: (self.stores.append(made(config, key)[0]) or self.stores[-1], EpicRecord(Description(self.description))) # type: ignore[method-assign,assignment]
def test_prints_each_write_and_each_chunk_it_would_start_and_makes_none_of_them(self) -> None:
self.issues = [issue("ABC-20"), issue("ABC-21", "do-epic-claude")]
parts = structured({"parts": [{"repo": "api", "change": "Add the endpoint."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo: api and web."})
fake = FakeEffects(on_terminal=True, claude=[parts])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
shown = out.replace("<1790000000> ", "")
self.assertIn("planning would write to Jira:\n- file ABC-new1 under ABC-20: [api] Do ABC-20, labelled repo:api\n- file ABC-new2 under ABC-20: [web] Do ABC-20, labelled repo:web\n- comment on ABC-20: Split by repo: api and web.\n", shown)
self.assertIn("would start ABC-new1, ABC-new2\nABC-21 waits: the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2\n", shown)
self.assertEqual(self.stores[0].writes, [])
self.assertEqual([each.key for each in self.stores[0].issues], ["ABC-20", "ABC-21"])
changing = {"new-session", "new-window", "kill-window", "set-option", "rename-window"}
self.assertEqual([args for args in fake.tmux_calls if args[0] in changing], [])
def test_prints_each_move_of_a_parent_whose_sub_tasks_a_person_filed(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-sub-tasks-landed-transition = "Release Ready"\njira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
self.issues = [issue("ABC-20", status="In Progress"), issue("ABC-30", "do-epic-claude", parent="ABC-20", status="Release Ready"), issue("ABC-21"), issue("ABC-31", "do-epic-claude", parent="ABC-21", done=True), issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))]
code, out, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects())
self.assertEqual((code, err), (0, ""))
self.assertIn("planning would write to Jira:\n- move ABC-20 by Release Ready\n- finish ABC-21\nwould start ABC-22\n", out.replace("<1790000000> ", ""))
self.assertEqual(self.stores[0].writes, [])
def test_prints_the_label_a_pick_would_give_an_issue(self) -> None:
self.issues = [issue("ABC-20")]
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(claude=[structured({"parts": []}), structured({"pick": "claude"})]))
self.assertEqual(code, 0)
self.assertIn("planning would write to Jira:\n- label ABC-20 with do-epic-claude\nwould start ABC-20\n", out.replace("<1790000000> ", ""))
def test_counts_the_chunks_it_would_start_against_the_epics_cap_and_a_repos_limit(self) -> None:
self.issues = [issue("ABC-21", "do-epic-claude"), issue("ABC-22", "do-epic-claude"), issue("ABC-23", "do-epic-claude")]
self.description = DESCRIPTION.replace("2", "1")
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(on_terminal=True))
self.assertEqual(code, 0)
shown = out.replace("<1790000000> ", "")
self.assertIn("planning wouldn't write anything to Jira\nwould start ABC-21\n", shown)
self.assertIn("ABC-22 waits: the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1\n", shown)
def test_prints_the_question_planning_would_ask_and_asks_none(self) -> None:
self.issues = [issue("ABC-20")]
unclear = structured({"pick": "unclear", "question": "Is the importer in api or in web?"})
fake = FakeEffects(on_terminal=True, claude=[structured({"parts": []}), unclear], inputs=["api"])
code, out, _ = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual(code, 0)
self.assertIn("ABC-20 waits for your answer: Is the importer in api or in web?", out)
self.assertEqual([seam for seam, _ in fake.calls if seam == "input"], [])
self.assertIn("planning wouldn't write anything to Jira\n", out)
def test_works_without_tmux_and_a_chunk_in_a_missing_repo_waits(self) -> None:
self.issues = [issue("ABC-20", "repo:missing"), issue("ABC-21", "do-epic-claude")]
fake = FakeEffects(on_terminal=False, tmux_version="")
code, out, _ = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual(code, 0)
self.assertIn("would start ABC-21\n", out)
self.assertIn("ABC-20 waits: missing is missing", out)
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_prints_the_scores_it_would_write_and_the_order_the_issues_would_start_in(self) -> None:
(self.home / planning.RULE).parent.mkdir(parents=True, exist_ok=True)
(self.home / planning.RULE).write_text("L is how much the item changes.\n", encoding="utf-8")
self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n"
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
answer = {"L": 2, "E": 1, "I": 2, "S": 3, "comment": "Scored to decide what starts first."}
fake = FakeEffects(on_terminal=False, claude=[structured(answer | {"moves": "epic 1 by 2"}), structured(answer | {"moves": "epic 1 by 9"})])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
shown = out.replace("<1790000000> ", "")
self.assertIn("by score, the issues of ABC-12 start in the order ABC-21, ABC-20\n", shown)
self.assertIn("planning would write to Jira:\n- score ABC-20 L 2, E 1, I 2, S 3, Moves epic 1 by 2, with the comment: Scored to decide what starts first.\n- score ABC-21 L 2, E 1, I 2, S 3, Moves epic 1 by 9, with the comment: Scored to decide what starts first.\n", shown)
self.assertIn("would start ABC-21, ABC-20\n", shown)
self.assertEqual(self.stores[0].writes, [])
def test_says_why_the_issues_start_in_backlog_order_and_names_no_order_of_one_issue(self) -> None:
self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key in ("ABC-20", "ABC-21")]
out = io.StringIO()
with contextlib.redirect_stdout(out):
epic_run.chunks_started(self.epic_run(FakeEffects(on_terminal=False)), self.issues, None)
self.assertIn("the issues of ABC-12 start in Jira's backlog order, since they cannot be put in order of score: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", out.getvalue())
self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n"
self.issues = self.issues[:1]
code, out, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects(on_terminal=False))
self.assertEqual((code, err), (0, ""))
self.assertNotIn("by score", out)
def test_clones_no_missing_repo_and_says_so(self) -> None:
shutil.rmtree(self.home / "code/web")
self.description = DESCRIPTION + "\n## Scoring\n`Score = V`\n"
self.issues = [dataclasses.replace(issue(key, label), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key, label in (("ABC-20", "repo:api"), ("ABC-22", "repo:web"))]
fake = FakeEffects(on_terminal=False, git=["git@host.example:team/api.git"] * 3)
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
missing = f"cannot clone git@host.example:team/web to {self.home / 'code/web'}: a dry run doesn't clone a repo, but a real run would. Where does web live?"
# The reason the order of score is missing is said once, by the planning.
self.assertEqual(out.replace("<1790000000> ", ""), f"{BANNER}\nthe epic ABC-12 is not planned in full, so the writes below are those it made before it stopped: {missing}\nthe issues of ABC-12 start in Jira's backlog order, since they cannot be put in order of score\nplanning wouldn't write anything to Jira\nwould start ABC-20\nABC-22 waits: {missing}\n")
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_says_on_stdout_that_planning_stopped_at_a_missing_repo_and_what_the_writes_are(self) -> None:
shutil.rmtree(self.home / "code/web")
self.issues = [issue("ABC-20"), issue("ABC-22", "repo:api"), issue("ABC-23", "repo:web")]
fake = FakeEffects(on_terminal=False, git=["git@host.example:team/api.git", ""])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
stopped = f"the epic ABC-12 is not planned in full, so the writes below are those it made before it stopped: cannot clone git@host.example:team/web to {self.home / 'code/web'}: a dry run doesn't clone a repo, but a real run would. Where does web live?\n"
self.assertIn(stopped, out.replace("<1790000000> ", ""))
self.assertIn("planning wouldn't write anything to Jira\n", out)
def test_indents_the_lines_after_the_first_of_a_comment_under_its_bullet(self) -> None:
self.issues = [issue("ABC-20")]
parts = structured({"parts": [{"repo": "api", "change": "Add it."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo.\nSecond line."})
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(claude=[parts]))
self.assertEqual(code, 0)
self.assertIn("\n- comment on ABC-20: Split by repo.\n Second line.\n", out)
def test_stops_where_the_epic_cannot_be_read(self) -> None:
store = MemoryEpic("ABC-12", [], fails="Jira answered 503")
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
code, _, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects())
self.assertEqual((code, "Jira answered 503\n" in err), (1, True))
def test_is_in_the_help(self) -> None:
self.assertIn("--dry-run", main.HELP)
self.assertEqual(self.run_main(["ABC-12", "--dry-run", "--status"], FakeEffects())[0], 1)
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
import dataclasses
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from do_epic.test_scheduler import issue
from do_epic.backend.fake import MemoryEpic
from do_epic.parent_moves import moved
UNBLOCKING = ("Release Ready", "Teach & Learn")
def family(*tasks: EpicIssue, parent: EpicIssue | None = None) -> list[EpicIssue]:
"""ABC-20, or parent in its place, followed by tasks as its sub-tasks."""
above = parent or issue("ABC-20", status="In Progress")
return [above, *(dataclasses.replace(task, parent=above.key) for task in tasks)]
class MovingAParentWhoseSubTasksAPersonFiled(unittest.TestCase):
def moves(self, issues: list[EpicIssue], landed_by: str | None = "Release Ready", finishes: bool = True) -> tuple[list[str], dict[str, tuple[str, bool]], list[str]]:
"""The writes moved made, each issue's status and whether it is done as moved answers them, and the reasons it gave."""
store = MemoryEpic("ABC-12", list(issues))
after, refused = moved(store, issues, UNBLOCKING, landed_by, finishes)
return store.writes, {each.key: (each.status, each.done) for each in after}, refused
def test_sub_tasks_that_have_all_landed_move_their_parent_by_the_landed_transition(self) -> None:
for tasks in ([issue("ABC-30", status="Release Ready"), issue("ABC-31", status="teach & learn")], [issue("ABC-30", status="Release Ready"), issue("ABC-31", done=True)]):
with self.subTest(tasks=tasks):
writes, after, refused = self.moves(family(*tasks))
self.assertEqual((writes, refused), (["move ABC-20 by Release Ready"], []))
self.assertEqual(after["ABC-20"], ("Release Ready", False))
def test_sub_tasks_that_are_all_done_finish_their_parent(self) -> None:
for status in ("In Progress", "Release Ready"):
with self.subTest(status=status):
writes, after, refused = self.moves(family(issue("ABC-30", done=True), issue("ABC-31", done=True), parent=issue("ABC-20", status=status)))
self.assertEqual((writes, refused), (["finish ABC-20"], []))
self.assertTrue(after["ABC-20"][1])
def test_a_parent_at_or_past_the_target_stays(self) -> None:
landed = [issue("ABC-30", status="Release Ready"), issue("ABC-31", done=True)]
for parent in (issue("ABC-20", status="Release Ready"), issue("ABC-20", status="teach & learn"), issue("ABC-20", done=True)):
with self.subTest(parent=parent):
self.assertEqual(self.moves(family(*landed, parent=parent))[0], [])
self.assertEqual(self.moves(family(issue("ABC-30", done=True), parent=issue("ABC-20", done=True)))[0], [])
def test_a_parent_with_no_sub_task_or_with_one_still_open_is_left_alone(self) -> None:
self.assertEqual(self.moves(family())[0], [])
self.assertEqual(self.moves(family(issue("ABC-30", done=True), issue("ABC-31", status="Release Ready"), issue("ABC-32", status="In Progress")))[0], [])
def test_without_a_landed_transition_only_the_move_to_done_happens_and_only_where_the_config_names_how(self) -> None:
landed = family(issue("ABC-30", status="Release Ready"))
done = family(issue("ABC-30", done=True))
self.assertEqual(self.moves(landed, landed_by=None)[0], [])
self.assertEqual(self.moves(done, landed_by=None)[0], ["finish ABC-20"])
self.assertEqual(self.moves(done, finishes=False), ([], {"ABC-20": ("In Progress", False), "ABC-30": ("Done", True)}, []))
def test_an_item_do_epic_split_or_half_split_is_left_to_its_own_closing(self) -> None:
done = dataclasses.replace(issue("ABC-30", done=True), by_loop=True)
self.assertEqual(self.moves(family(done, parent=issue("ABC-20", "split-by-repo")))[0], [])
self.assertEqual(self.moves(family(done))[0], [])
def test_a_parent_with_a_sub_task_a_person_filed_beside_one_do_epic_filed_moves(self) -> None:
ours = dataclasses.replace(issue("ABC-31", done=True), by_loop=True)
self.assertEqual(self.moves(family(issue("ABC-30", status="Release Ready"), ours))[0], ["move ABC-20 by Release Ready"])
self.assertEqual(self.moves(family(issue("ABC-30", done=True), ours))[0], ["finish ABC-20"])
def test_a_landed_transition_named_unlike_its_status_moves_the_parent_to_an_unblocking_status(self) -> None:
writes, after, refused = self.moves(family(issue("ABC-30", status="Teach & Learn")), landed_by="Mark ready")
self.assertEqual((writes, after["ABC-20"], refused), (["move ABC-20 by Mark ready"], ("Release Ready", False), []))
def test_a_move_jira_refuses_is_answered_with_its_reason_and_the_other_parents_still_move(self) -> None:
issues = [*family(issue("ABC-30", status="Release Ready")), *family(issue("ABC-31", done=True), parent=issue("ABC-21")), *family(issue("ABC-32", done=True), parent=issue("ABC-22"))]
store = MemoryEpic("ABC-12", list(issues))
finish = store.finish_issue
store.move_issue_by = lambda key, transition, to: Failure("ABC-20 has no transition 'Release Ready' from its status") # type: ignore[method-assign]
store.finish_issue = lambda key: Failure("Jira answered 400") if key == "ABC-21" else finish(key) # type: ignore[method-assign]
after, refused = moved(store, issues, UNBLOCKING, "Release Ready", True)
self.assertEqual(refused, [
"ABC-20's sub-tasks have all landed, but it did not move by 'Release Ready', the transition `jira-sub-tasks-landed-transition` names: ABC-20 has no transition 'Release Ready' from its status; move it in Jira",
"ABC-21's sub-tasks are all done, but it did not move to done: Jira answered 400; close it in Jira",
])
self.assertEqual({each.key: (each.status, each.done) for each in after if each.parent == "ABC-12"}, {"ABC-20": ("In Progress", False), "ABC-21": ("To Do", False), "ABC-22": ("To Do", True)})
if __name__ == "__main__":
unittest.main()
+44
View File
@@ -0,0 +1,44 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic import chunk_prompt
from failure import Failure
from do_epic.parking import news_after
from do_epic.gates import Open, Unmergeable, Unopened
UNOPENED = Unopened("no pull request is open")
UNCLEANED = f"{chunk_prompt.DRIVER} keeps the chunk open while its worktree stands: no pull request is open."
UNMERGEABLE = Unmergeable("pull request #7 conflicts with its base branch")
UNLEVELLED = f"{chunk_prompt.DRIVER} keeps the chunk open while its pull request doesn't merge into its base: pull request #7 conflicts with its base branch."
class TheNewsOfAChunkThatIsNotParked(unittest.TestCase):
def test_a_window_that_just_started_has_no_news(self) -> None:
self.assertEqual(news_after(None, finished=True, by_human=True, told=None), "")
def test_a_gate_that_cannot_be_read_or_one_that_lets_the_chunk_go_on_does_not_add_any_news(self) -> None:
for entered in (Failure("no network"), Open("a reviewer requested changes")):
with self.subTest(entered):
self.assertEqual(news_after(entered, finished=True, by_human=True, told=""), "")
def test_an_unfinished_chunk_or_one_that_merges_without_a_person_has_no_news(self) -> None:
for entered in (UNOPENED, UNMERGEABLE):
for finished, by_human in ((False, True), (True, False), (False, False)):
with self.subTest(entered=entered, finished=finished, by_human=by_human):
self.assertEqual(news_after(entered, finished, by_human, told=""), "")
def test_a_finished_chunk_a_person_merges_is_told_its_worktree_stands_once(self) -> None:
self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=""), UNCLEANED)
self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=UNLEVELLED), UNCLEANED)
self.assertEqual(news_after(UNOPENED, finished=True, by_human=True, told=f"Before. {UNCLEANED}"), "")
def test_a_finished_chunk_a_person_merges_is_told_after_every_cycle_that_its_pull_request_doesnt_merge(self) -> None:
self.assertEqual(news_after(UNMERGEABLE, finished=True, by_human=True, told=""), UNLEVELLED)
self.assertEqual(news_after(UNMERGEABLE, finished=True, by_human=True, told=UNLEVELLED), UNLEVELLED)
if __name__ == "__main__":
unittest.main()
+220 -19
View File
@@ -23,14 +23,16 @@ from plan.todo_table import parse_moves
from do_epic import planning
RANKED = "## Goals\n1. **Achieve:** Ship the import.\n\n## Audience\nThe client's team.\n\n## Scoring\n`Score = V`\n"
GOALS = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n"
ANSWER = {"L": 2, "E": 1, "I": 2, "S": 3, "moves": "epic 1 by 9", "comment": "Scored to decide what starts first."}
LIMIT = {"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"}
def scored(key: str, moves: str, *labels: str, blockers: tuple[str, ...] = (), by_loop: bool = True) -> EpicIssue:
def scored(key: str, moves: str, *labels: str, blockers: tuple[str, ...] = (), by_loop: bool = True, parent: str = "ABC-12") -> EpicIssue:
"""An open issue the loop filed, holding scores and moving the goals moves names."""
parsed = parse_moves(key, moves)
assert not isinstance(parsed, Failure), parsed
return dataclasses.replace(issue(key, *labels, blockers=blockers), scores={"L": 1, "E": 1, "I": 1, "S": 1}, moves=parsed, by_loop=by_loop)
return dataclasses.replace(issue(key, *labels, blockers=blockers, parent=parent), scores={"L": 1, "E": 1, "I": 1, "S": 1}, moves=parsed, by_loop=by_loop)
class Planning(DoEpicTest):
@@ -44,14 +46,28 @@ class Planning(DoEpicTest):
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(self.asked):
read = store.read()
assert not isinstance(read, Failure)
self.epic = epic
issues, stopped = planning.planned(epic, read)
return issues if stopped is None else stopped, store, out.getvalue()
def rule(self) -> None:
"""Writes the rule every plan item is scored by."""
(self.home / planning.RULE).parent.mkdir(parents=True, exist_ok=True)
(self.home / planning.RULE).write_text("L is how much the item changes.\n", encoding="utf-8")
def repo(self, name: str) -> None:
"""Checks out the repo called name, whose goals file voids code health and states one achieve goal."""
checkout = self.home / "code" / name
configured(self, checkout, home=self.home)
(checkout / "README.md").write_text(GOALS, encoding="utf-8")
def labels(self, store: MemoryEpic) -> dict[str, tuple[str, ...]]:
return {each.key: each.labels for each in store.issues}
def test_an_issue_a_label_places_is_planned_without_claude(self) -> None:
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "split-by-repo"), issue("ABC-23", done=True)]
self.description = RANKED
self.repo("api")
self.issues = [scored("ABC-20", "epic 1 by 9", "repo:api"), scored("ABC-21", "epic 1 by 2", "do-epic-claude"), issue("ABC-22", "split-by-repo"), issue("ABC-23", done=True)]
fake = FakeEffects()
found, _, out = self.plan(fake)
self.assertEqual((found, out, fake.made("claude")), (self.issues, "", []))
@@ -59,13 +75,16 @@ class Planning(DoEpicTest):
def test_an_epic_shaped_as_a_teams_is_planned_without_claude_and_without_a_write(self) -> None:
with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config:
config.write('\n[label-repos]\ntwu-4 = "tenant-web-ui-4"\ncore-4 = "core-4"\n')
self.description = RANKED
self.repo("tenant-web-ui-4")
self.repo("core-4")
self.issues = [
issue("ABC-19", "twu-4"),
scored("ABC-19", "epic 1 by 5", "twu-4", by_loop=False),
issue("ABC-20"),
issue("ABC-23", "core-4", parent="ABC-20"),
issue("ABC-24", "twu-4", parent="ABC-20"),
scored("ABC-23", "epic 1 by 5", "core-4", by_loop=False, parent="ABC-20"),
scored("ABC-24", "epic 1 by 5", "twu-4", by_loop=False, parent="ABC-20"),
issue("ABC-21", "urgent"),
issue("ABC-25", "core-4", parent="ABC-21"),
scored("ABC-25", "epic 1 by 5", "core-4", by_loop=False, parent="ABC-21"),
]
fake = FakeEffects()
found, store, out = self.plan(fake)
@@ -93,9 +112,8 @@ class Planning(DoEpicTest):
def test_splits_an_issue_that_changes_several_repos_into_a_sub_task_for_each_and_picks_no_repo_for_it(self) -> None:
self.issues = [issue("ABC-20")]
fake = FakeEffects(claude=[says({"parts": [{"repo": "api", "change": "Add the endpoint."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo: api and web."})])
found, store, out = self.plan(fake)
assert not isinstance(found, Failure | Limited), found
self.assertEqual([(each.key, each.parent, each.labels) for each in found], [("ABC-20", "ABC-12", ("split-by-repo",)), ("ABC-101", "ABC-20", ("repo:api",)), ("ABC-102", "ABC-20", ("repo:web",))])
_, store, out = self.plan(fake)
self.assertEqual([(each.key, each.parent, each.labels) for each in store.issues], [("ABC-20", "ABC-12", ("split-by-repo",)), ("ABC-101", "ABC-20", ("repo:api",)), ("ABC-102", "ABC-20", ("repo:web",))])
# A person filed ABC-20, so the team is told.
self.assertEqual(store.comments, {"ABC-20": ["Split by repo: api and web."]})
self.assertIn("ABC-20 is split into a sub-task for each of api, web\n", out)
@@ -168,7 +186,27 @@ class Planning(DoEpicTest):
self.issues = [issue("ABC-20")]
fake = FakeEffects(claude=[says({"parts": []}), says({"pick": "unclear", "question": "Is the importer in api or in web?"})], inputs=["backend"])
found, _, _ = self.plan(fake)
self.assertEqual((found, fake.made("input")), ([issue("ABC-20", "repo:api")], ["The label that says where ABC-20 is worked, `repo:<name>`, `do-epic-claude` or `do-epic-human` (or the team's `backend`), or Enter alone to leave it waiting: "]))
self.assertEqual((found, fake.made("input")), ([issue("ABC-20", "backend")], ["The label that says where ABC-20 is worked, `repo:<name>`, `do-epic-claude` or `do-epic-human` (or the team's `backend`), or Enter alone to leave it waiting: "]))
def configure_team(self, *above: str) -> None:
"""Gives the config the team's label `backend` for api, and the settings in above."""
path = self.home / ".claude-projects/do-epic/config.toml"
path.write_text("".join(f"{line}\n" for line in above) + path.read_text(encoding="utf-8") + '\n[label-repos]\nbackend = "api"\n', encoding="utf-8")
def test_files_sub_tasks_under_the_teams_label_and_summary_template(self) -> None:
self.configure_team('sub-task-summary = "{label}: {Summary}"')
self.issues = [issue("ABC-20")]
parts = says({"parts": [{"repo": "api", "change": "Add the endpoint."}, {"repo": "web", "change": "Call it."}], "comment": "Delat per repo."})
_, store, _ = self.plan(FakeEffects(claude=[parts]))
self.assertEqual([(each.summary, each.labels) for each in store.issues if each.parent == "ABC-20"], [("backend: Do ABC-20", ("backend",)), ("web: Do ABC-20", ("repo:web",))])
def test_records_the_teams_label_for_a_repo_the_human_types_by_name_and_names_it(self) -> None:
self.configure_team()
self.issues = [issue("ABC-20")]
fake = FakeEffects(claude=[says({"parts": []}), says({"pick": "unclear", "question": "api or web?"})], inputs=["api", "backend"])
found, _, _ = self.plan(fake)
self.assertEqual(found, [issue("ABC-20", "backend")])
self.assertIn("the repo api's label is `backend`", self.asked.getvalue())
def test_asks_the_human_for_the_label_of_an_issue_the_rule_leaves_unclear_until_one_is_typed(self) -> None:
self.issues = [issue("ABC-20")]
@@ -250,17 +288,15 @@ class Planning(DoEpicTest):
def test_re_ranks_the_loops_scored_issues_by_score_with_a_blocker_first_and_leaves_every_other_issue_in_place(self) -> None:
self.description = RANKED
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("ABC-21", "epic 1 by 9", "do-epic-claude", by_loop=False), scored("ABC-22", "epic 1 by 5", "do-epic-claude", blockers=("ABC-24",)), dataclasses.replace(issue("ABC-23", "do-epic-claude"), by_loop=True), scored("ABC-24", "epic 1 by 3", "do-epic-claude")]
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("ABC-21", "epic 1 by 9", "do-epic-claude", by_loop=False), scored("ABC-22", "epic 1 by 5", "do-epic-claude", blockers=("ABC-24",)), dataclasses.replace(issue("ABC-23", "do-epic-human"), by_loop=True), scored("ABC-24", "epic 1 by 3", "do-epic-claude")]
found, store, out = self.plan(FakeEffects())
assert not isinstance(found, Failure | Limited), found
# ABC-22 scores highest, and ABC-24 blocks it. ABC-21 is a person's, and nobody scored ABC-23.
# ABC-22 scores highest, and ABC-24 blocks it. ABC-21 is a person's, and ABC-23 is a human's task, which holds no scores.
self.assertEqual([each.key for each in found], ["ABC-24", "ABC-21", "ABC-22", "ABC-23", "ABC-20"])
self.assertIn("re-ranking the issues do-epic filed in ABC-12's backlog\n", out)
def test_ranks_an_issue_in_a_repo_by_that_repos_goals_after_the_epics(self) -> None:
checkout = self.home / "code" / "api"
configured(self, checkout, home=self.home)
(checkout / "README.md").write_text("## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
self.repo("api")
self.description = RANKED
self.issues = [scored("ABC-20", "repo 1 by 9", "repo:api"), scored("ABC-21", "epic 1 by 9", "do-epic-claude")]
found, _, _ = self.plan(FakeEffects())
@@ -284,10 +320,33 @@ class Planning(DoEpicTest):
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("ABC-21", "epic 1 by 9", "do-epic-claude")]
self.assertIsInstance(self.plan(FakeEffects())[0], Failure)
def test_fails_where_two_issues_to_rank_share_a_number(self) -> None:
def test_orders_issues_of_two_jira_projects_that_share_a_number(self) -> None:
self.description = RANKED
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("XYZ-20", "epic 1 by 9", "do-epic-claude")]
self.assertEqual(self.plan(FakeEffects())[0], Failure("ABC-20 and XYZ-20 share a number in different Jira projects, so the issues do-epic filed in the epic ABC-12 cannot be ranked; move one of the two to the other's Jira project"))
found = self.plan(FakeEffects())[0]
assert not isinstance(found, Failure | Limited), found
self.assertEqual(planning.start_order(self.epic, found), ["XYZ-20", "ABC-20"])
def test_issues_that_score_the_same_start_in_the_trackers_order(self) -> None:
self.description = RANKED
self.issues = [scored("ABC-30", "epic 1 by 5", "do-epic-claude", by_loop=False), scored("ABC-20", "epic 1 by 5", "do-epic-claude", by_loop=False)]
self.plan(FakeEffects())
self.assertEqual(planning.start_order(self.epic, self.issues), ["ABC-30", "ABC-20"])
def test_names_the_issue_by_its_key_where_the_order_of_score_fails(self) -> None:
self.description = RANKED
self.issues = [scored("ABC-30", "epic 1 by 5", "do-epic-claude", by_loop=False), scored("ABC-20", "epic 7 by 5", "do-epic-claude", by_loop=False)]
self.plan(FakeEffects())
self.assertEqual(planning.start_order(self.epic, self.issues), Failure("ABC-20 names epic 7, which the epic's ## Goals does not number"))
def test_quotes_a_formula_that_names_an_item_as_the_epic_states_it(self) -> None:
self.description = RANKED.replace("Score = V", "Score = item 1")
self.issues = [scored("ABC-30", "epic 1 by 5", "do-epic-claude", by_loop=False), scored("ABC-20", "epic 1 by 5", "do-epic-claude", by_loop=False)]
self.plan(FakeEffects())
failed = planning.start_order(self.epic, self.issues)
assert isinstance(failed, Failure), failed
self.assertIn("item 1", failed.reason)
self.assertNotIn("ABC-30", failed.reason)
def test_fails_where_the_description_cannot_be_read_to_rank_by(self) -> None:
self.description = Failure("Jira answered 503")
@@ -312,9 +371,151 @@ class Planning(DoEpicTest):
self.assertEqual([each.key for each in found], ["ABC-21", "ABC-20"])
def test_one_scored_issue_needs_no_formula(self) -> None:
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), issue("ABC-21", "do-epic-human")]
self.assertEqual(self.plan(FakeEffects())[0], self.issues)
def test_scores_each_bare_issue_whoever_filed_it_and_tells_its_team_without_ranking_a_persons(self) -> None:
self.rule()
self.description = RANKED
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude", by_loop=False), issue("ABC-21", "do-epic-claude")]
# An earlier run made the folder the scoring runs in.
(self.home / planning.STATE / "ABC-12").mkdir(parents=True, exist_ok=True)
fake = FakeEffects(claude=[says(ANSWER)])
found, store, out = self.plan(fake)
assert not isinstance(found, Failure | Limited), found
# ABC-20's scores stay, and a person filed both, so neither changes its position in the backlog.
self.assertEqual([(each.key, each.scores) for each in found], [("ABC-20", {"L": 1, "E": 1, "I": 1, "S": 1}), ("ABC-21", {"L": 2, "E": 1, "I": 2, "S": 3})])
self.assertEqual(store.writes, ["score ABC-21 L 2, E 1, I 2, S 3, Moves epic 1 by 9, with the comment: Scored to decide what starts first."])
self.assertEqual(out, "<1790000000> scoring ABC-21\n<1790000000> ABC-21 is scored L 2, E 1, I 2, S 3, Moves epic 1 by 9\n")
self.assertEqual(planning.start_order(self.epic, found), ["ABC-21", "ABC-20"])
(asked,) = fake.made("claude")
for part in ("L is how much the item changes.", "Write the comment in English", "An item moves only these: `epic 1`.", "## Item ABC-21: Do ABC-21", "Labels: do-epic-claude"):
self.assertIn(part, asked[1])
self.assertIn("--json-schema", asked[0])
def test_scores_no_human_task_and_no_issue_that_is_the_only_one_to_start(self) -> None:
self.rule()
self.description = RANKED
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-human")]
fake = FakeEffects()
found, store, out = self.plan(fake)
self.assertEqual((found, store.writes, out, fake.made("claude")), (self.issues, [], "", []))
def test_scores_no_issue_whose_work_has_landed(self) -> None:
with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config:
config.write('\njira-unblocking-statuses = ["Release Ready"]\n')
self.rule()
self.description = RANKED
self.issues = [issue("ABC-20", "do-epic-claude", status="release ready"), issue("ABC-21", "do-epic-claude"), scored("ABC-22", "epic 1 by 2", "do-epic-claude")]
fake = FakeEffects(claude=[says(ANSWER)])
found, store, _ = self.plan(fake)
assert not isinstance(found, Failure | Limited), found
self.assertEqual([write.split(" L ")[0] for write in store.writes], ["score ABC-21"])
self.assertEqual(planning.start_order(self.epic, found), ["ABC-21", "ABC-22"])
def test_names_an_issue_whose_scoring_fails_and_scores_the_next(self) -> None:
self.rule()
self.description = RANKED
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "do-epic-claude"), issue("ABC-23", "do-epic-claude")]
fake = FakeEffects(claude=[says({"L": "big"}), says(ANSWER | {"moves": "epic 7 by 5"}), says(ANSWER | {"L": 99}), says(ANSWER)])
found, store, out = self.plan(fake)
assert not isinstance(found, Failure | Limited), found
self.assertIn('ABC-20 is not scored: the scoring answered {"L": "big"}; expected a whole number for each of L, E, I, S, the moves as text and a comment\n', out)
self.assertIn("ABC-21 is not scored: ABC-21 names epic 7, which the epic's ## Goals does not number\n", out)
self.assertIn("ABC-22 is not scored: ", out)
self.assertEqual([each.key for each in found if each.scores], ["ABC-23"])
self.assertEqual([write.split(" L ")[0] for write in store.writes], ["score ABC-23"])
# An issue without scores starts after each that holds them, in the backlog's order.
self.assertEqual(planning.start_order(self.epic, found), ["ABC-23"])
def test_names_each_issue_whose_goals_cannot_be_read_and_asks_claude_about_none(self) -> None:
self.rule()
self.description = RANKED.replace("1. **Achieve:** ", "")
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
fake = FakeEffects()
out = self.plan(fake)[2]
self.assertIn("ABC-20 is not scored: the epic's ## Goals has no numbered goal\n", out)
self.assertIn("ABC-21 is not scored: the epic's ## Goals has no numbered goal\n", out)
self.assertEqual(fake.made("claude"), [])
def test_the_scoring_call_runs_in_the_epics_state_folder(self) -> None:
self.rule()
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
effects, folders = FakeEffects(claude=[says(ANSWER), says(ANSWER)]).effects(), []
def claude(args: object, cwd: str, stdin: object) -> object:
folders.append(cwd)
return effects.claude(args, cwd, stdin) # type: ignore[arg-type]
config = load(self.home)
epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description(RANKED)), self.home, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type]
with contextlib.redirect_stdout(io.StringIO()):
planning.planned(epic, list(self.issues))
self.assertEqual(folders, [str(self.home / ".local" / "state" / "do-epic" / "ABC-12")] * 2)
self.rule()
self.description = RANKED
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
fake = FakeEffects(claude=[subprocess.CompletedProcess([], 0, json.dumps(LIMIT), "")])
found, store, _ = self.plan(fake)
self.assertIsInstance(found, Limited)
self.assertEqual((store.writes, len(fake.made("claude"))), ([], 1))
def test_names_a_score_the_tracker_refuses(self) -> None:
self.rule()
self.description = RANKED
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-human"), scored("ABC-22", "epic 1 by 2", "do-epic-claude")]
store = MemoryEpic("ABC-12", list(self.issues))
store.fails = "Jira answered 503"
out = io.StringIO()
config = load(self.home)
assert not isinstance(config, Failure), config
epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, FakeEffects(claude=[says(ANSWER)]).effects()) # type: ignore[arg-type]
with contextlib.redirect_stdout(out):
found, stopped = planning.scored(epic, list(self.issues))
self.assertEqual((found, stopped, out.getvalue()), (self.issues, None, "<1790000000> scoring ABC-20\n<1790000000> ABC-20 is not scored: Jira answered 503\n"))
def test_scores_no_issue_without_the_scoring_rule_or_the_epics_formula(self) -> None:
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
self.description = RANKED
fake = FakeEffects()
found, _, _ = self.plan(fake)
assert isinstance(found, Failure), found
self.assertIn(f"cannot read the scoring rule {self.home}/.claude/rules/todo-items.md, so no issue is scored: ", found.reason)
self.rule()
self.description = "## Goals\n1. **Achieve:** Ship the import.\n\n## Audience\nThe client's team.\n\n## Scoring\n"
found, _, _ = self.plan(fake)
assert isinstance(found, Failure), found
self.assertIn("states `Score = ...` 0 times under ## Scoring", found.reason)
self.assertEqual(fake.made("claude"), [])
def test_scores_a_sub_task_on_its_own_against_its_repos_goals_in_the_epics_language(self) -> None:
self.rule()
self.repo("api")
self.description = RANKED + "\n**Language:** Swedish\n"
self.issues = [issue("ABC-20", "split-by-repo"), issue("ABC-30", "repo:api", parent="ABC-20"), scored("ABC-21", "epic 1 by 2", "do-epic-claude")]
fake = FakeEffects(claude=[says(ANSWER | {"moves": "repo 1 by 4"})])
found, store, _ = self.plan(fake)
assert not isinstance(found, Failure | Limited), found
self.assertEqual(store.writes, ["score ABC-30 L 2, E 1, I 2, S 3, Moves repo 1 by 4, with the comment: Scored to decide what starts first."])
(asked,) = fake.made("claude")
for part in ("The goals of the repo api, each named `repo <its number>`:", "Serve the API.", "An item moves only these: `epic 1`, `repo 1`.", "Write the comment in Swedish"):
self.assertIn(part, asked[1])
self.assertNotIn("`code health` is the goal", asked[1])
def test_starts_what_blocks_an_issue_or_its_parent_before_it_and_a_split_blockers_sub_tasks_too(self) -> None:
self.repo("api")
self.description = RANKED
self.issues = [
scored("ABC-20", "epic 1 by 9", "do-epic-claude", blockers=("ABC-21",)),
dataclasses.replace(issue("ABC-21", "split-by-repo"), blockers=("ABC-22",)),
scored("ABC-30", "epic 1 by 5", "repo:api", parent="ABC-21"),
scored("ABC-22", "epic 1 by 1", "do-epic-claude"),
]
found, _, _ = self.plan(FakeEffects())
assert not isinstance(found, Failure | Limited), found
# By score alone the order is ABC-20, ABC-30, ABC-22.
self.assertEqual(planning.start_order(self.epic, found), ["ABC-22", "ABC-30", "ABC-20"])
def planned_on(self, store: MemoryEpic, fake: FakeEffects) -> tuple[list[EpicIssue], Failure | Limited | None]:
"""What planning answers for self.issues on a store that doesn't read as MemoryEpic does."""
config = load(self.home)
+26 -3
View File
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.ranking import chain, EpicItem, rank_moves, ranked, RepoRanking, reranked
from do_epic.ranking import chain, EpicItem, goals_named, rank_moves, ranked, RepoRanking, reranked
from failure import Failure
from plan.todo_table import Item, parse_moves
from do_epic.backend.fake import MemoryEpic
@@ -24,7 +24,7 @@ TOTAL = 1 + 0.97
def item(id_: int, moves: str, repo: str | None = "billing-api", exempt: str = "", blocked_by: tuple[int, ...] = ()) -> EpicItem:
parsed = parse_moves(f"item {id_}", moves)
assert not isinstance(parsed, Failure), parsed
return EpicItem(Item(id_, (0, 0, 0), exempt, f"**Item {id_}.**", {"L": 1, "E": 1, "I": 1, "S": 1}, parsed, blocked_by), repo) # type: ignore[arg-type]
return EpicItem(Item(id_, (0, 0, 0), exempt, f"**Item {id_}.**", {"L": 1, "E": 1, "I": 1, "S": 1}, parsed, blocked_by), repo, f"item {id_}") # type: ignore[arg-type]
def order(items: list[EpicItem], repos: dict[str, RepoRanking], formula: str = "V") -> list[int] | Failure:
@@ -55,6 +55,23 @@ class ChainTest(unittest.TestCase):
self.assertEqual(chain("Ship it.\n", None, None), Failure("the epic's ## Goals has no numbered goal"))
class GoalsNamedTest(unittest.TestCase):
EPIC = "1. **Maintain:** Break no import.\n2. **Achieve:** Ship the import.\n"
def test_names_only_the_epics_achieve_goals_for_an_item_without_a_repo(self) -> None:
self.assertEqual(goals_named(self.EPIC, None, None), "The epic's goals, each named `epic <its number>`:\n\n1. **Maintain:** Break no import.\n2. **Achieve:** Ship the import.\n\nAn item moves only these: `epic 2`.")
self.assertTrue(str(goals_named("1. **Maintain:** Break no import.\n", None, None)).endswith("An item moves only these: none, so leave the moves empty."))
def test_names_code_health_and_the_repos_goals_for_an_item_in_a_repo(self) -> None:
own = RepoRanking("## Goals\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n", "", "", decimal.Decimal(7))
found = goals_named(self.EPIC, "api", own)
assert isinstance(found, str), found
self.assertIn("\n\n`code health` is the goal that the code of api stays easy to read, change safely and debug.\n\nThe goals of the repo api, each named `repo <its number>`:\n\n1. **Achieve:** Serve the API.\n\nAn item moves only these: `epic 2`, `code health`, `repo 1`.", found)
def test_fails_on_goals_that_cannot_be_read(self) -> None:
self.assertIsInstance(goals_named(self.EPIC, "api", RepoRanking("No goals here.\n", "", "", decimal.Decimal(7))), Failure)
class RankedTest(unittest.TestCase):
def test_each_goal_weighs_0_97_of_the_one_above_it_in_the_chain(self) -> None:
found = ranked([item(1, "repo 1 by 10"), item(2, "epic 2 by 10"), item(3, "epic 1 by 10")], "V", EPIC_GOALS, {"billing-api": VOIDED})
@@ -100,7 +117,7 @@ class RankedTest(unittest.TestCase):
self.assertAlmostEqual(value, expected)
def test_an_item_without_a_score_fails_naming_it(self) -> None:
unscored = EpicItem(dataclasses.replace(item(4, "").item, scores={}), None)
unscored = EpicItem(dataclasses.replace(item(4, "").item, scores={}), None, "item 4")
self.assertEqual(ranked([unscored], "V", EPIC_GOALS, {}), Failure("item 4 has no L: score it on L, E, I and S before it is ranked"))
def test_an_epic_that_numbers_a_goal_twice_fails(self) -> None:
@@ -153,6 +170,12 @@ class RankedTest(unittest.TestCase):
def test_a_blocker_ranks_above_the_item_it_blocks_and_a_tie_goes_to_the_older_item(self) -> None:
self.assertEqual(order([item(1, "epic 1 by 9", blocked_by=(3,)), item(2, "epic 1 by 2"), item(3, "epic 1 by 1"), item(5, "epic 1 by 2")], {"billing-api": VOIDED}), [3, 1, 2, 5])
def test_names_by_their_names_the_items_that_block_each_other_in_a_loop(self) -> None:
looped = [dataclasses.replace(item(1, "epic 1 by 9", blocked_by=(2,)), name="ABC-1"), dataclasses.replace(item(2, "epic 1 by 2", blocked_by=(1,)), name="XYZ-1"), item(3, "epic 1 by 1")]
self.assertEqual(ranked(looped, "V", EPIC_GOALS, {"billing-api": VOIDED}), Failure("ABC-1 and XYZ-1 block each other in a loop; drop one of the blockers"))
three = [item(1, "epic 1 by 9", blocked_by=(3,)), item(2, "epic 1 by 2", blocked_by=(1,)), item(3, "epic 1 by 1", blocked_by=(2,))]
self.assertEqual(ranked(three, "V", EPIC_GOALS, {"billing-api": VOIDED}), Failure("item 1, item 2 and item 3 block each other in a loop; drop one of the blockers"))
def test_a_formula_that_cannot_be_read_fails(self) -> None:
self.assertIsInstance(order([item(1, "epic 1 by 9")], {"billing-api": VOIDED}, "V +"), Failure)
+20 -3
View File
@@ -6,7 +6,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.repo_pick import also, CLAUDE_LABEL, ClaudeWork, HUMAN_LABEL, HumanTask, label_of, PICK_SCHEMA, picked, recorded, Repo, REPO_PREFIX, Unclear
from do_epic.repo_pick import also, CLAUDE_LABEL, ClaudeWork, HUMAN_LABEL, HumanTask, label_of, PICK_SCHEMA, picked, record, recorded, Repo, REPO_PREFIX, Unclear
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from claude_code.reply import Limited
@@ -57,7 +57,7 @@ class RepoPick(unittest.TestCase):
self.pick(claude)
args, cwd, _ = claude.calls[0]
self.assertEqual(cwd, "/rules")
self.assertEqual(args[:9], ["-p", "--json-schema", json.dumps(PICK_SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", ""])
self.assertEqual(args[:10], ["-p", "--json-schema", json.dumps(PICK_SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", "", "--strict-mcp-config"])
def test_puts_the_rule_and_the_item_in_the_prompt(self) -> None:
claude = says({"pick": "claude"})
@@ -137,7 +137,7 @@ class RepoPick(unittest.TestCase):
def test_the_label_of_a_pick_reads_back_as_that_pick(self) -> None:
for pick in (Repo("payments-api"), ClaudeWork(), HumanTask()):
with self.subTest(pick=pick):
self.assertEqual(recorded(EpicIssue(self.key, "s", "", (label_of(pick),), None, "To Do", False, "ABC-12"), {}), pick)
self.assertEqual(recorded(EpicIssue(self.key, "s", "", (label_of(pick, {}),), None, "To Do", False, "ABC-12"), {}), pick)
def test_a_label_the_teams_table_maps_records_its_repo_without_asking_claude(self) -> None:
self.store.add_label(self.key, "twu-4")
@@ -159,6 +159,23 @@ class RepoPick(unittest.TestCase):
self.store.add_label(self.key, "repo:core-4")
self.assertEqual(recorded(self.issue(), TEAM), Failure(f"{self.key} is labelled with 2 picks: core-4, repo:core-4, twu-4; remove the labels of all but the right one"))
def test_a_repo_the_teams_table_names_is_recorded_as_the_teams_label_and_any_other_as_repo_name(self) -> None:
for pick, label in ((Repo("tenant-web-ui-4"), "twu-4"), (Repo("core-4"), "core-4"), (Repo("api-3"), "repo:api-3"), (ClaudeWork(), CLAUDE_LABEL), (HumanTask(), HUMAN_LABEL)):
with self.subTest(pick=pick):
self.assertEqual(label_of(pick, TEAM), label)
def test_the_first_line_of_the_table_stands_for_a_repo_it_names_twice(self) -> None:
self.assertEqual(label_of(Repo("core-4"), {"zeta": "core-4", "core-4": "core-4"}), "zeta")
def test_a_pick_by_claude_is_labelled_with_the_teams_label_and_no_repo_label(self) -> None:
picked(self.store, self.issue(), TEAM, RULE, RUNG, says({"pick": "repo", "repo": "tenant-web-ui-4"}), "/rules")
self.assertEqual(self.issue().labels, ("api", "twu-4"))
def test_a_recorded_answer_is_labelled_the_same_way(self) -> None:
self.assertEqual((record(self.store, self.issue(), Repo("core-4"), TEAM), self.issue().labels), (Repo("core-4"), ("api", "core-4")))
self.assertEqual(record(self.store, self.issue(), Repo("api-3"), TEAM), Repo("api-3"))
self.assertEqual(self.issue().labels, ("api", "core-4", "repo:api-3"))
def test_a_label_with_the_prefix_alone_is_no_pick(self) -> None:
self.store.add_label(self.key, "repo:")
self.assertIsNone(recorded(self.issue(), {}))
+75 -4
View File
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.scheduler import Chunk, chunks, Epic, HUMAN_WAIT, refusal, RepoRoom, resume, start_chunks, Started, Waits
from do_epic.scheduler import Chunk, chunks, Epic, held_up, HUMAN_WAIT, refusal, RepoRoom, resume, start_chunks, Started, Waits
from chunk_driver.claims import CHUNK_FLAG
from do_epic import chunk_prompt
from do_epic.backend.protocol import EpicIssue
@@ -21,8 +21,8 @@ from project_config import settings
from agent_cycle import tmux
def issue(key: str, *labels: str, done: bool = False, blockers: tuple[str, ...] = (), parent: str = "ABC-12") -> EpicIssue:
return EpicIssue(key, f"Do {key}", "", tuple(sorted(labels)), None, "Done" if done else "To Do", done, parent, blockers=blockers)
def issue(key: str, *labels: str, done: bool = False, blockers: tuple[str, ...] = (), parent: str = "ABC-12", status: str | None = None) -> EpicIssue:
return EpicIssue(key, f"Do {key}", "", tuple(sorted(labels)), None, status or ("Done" if done else "To Do"), done, parent, blockers=blockers)
class TheCapLine(unittest.TestCase):
@@ -120,6 +120,39 @@ class WhichIssuesAreChunks(unittest.TestCase):
found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")], {})
self.assertEqual(found, ([Chunk("ABC-19", "api")], [Waits("ABC-23", "ABC-19 blocks it")]))
def test_an_issue_in_an_unblocking_status_unblocks_what_it_blocks_and_waits_to_be_done_itself(self) -> None:
issues = [issue("ABC-19", "repo:api", status="Release Ready"), issue("ABC-20", "repo:api", blockers=("ABC-19",)), issue("ABC-21", "repo:api", status="Code Review"), issue("ABC-22", "repo:api", blockers=("ABC-21",)), issue("ABC-23", "repo:api", done=True), issue("ABC-24", "repo:api", blockers=("ABC-23", "ABC-21", "ABC-22"))]
self.assertEqual(chunks(issues, {}, ("Release Ready", "Shipped")), ([Chunk("ABC-20", "api"), Chunk("ABC-21", "api")], [
Waits("ABC-19", "its work has landed: it is Release Ready, and the epic's finishing waits until Jira counts it done"),
Waits("ABC-22", "ABC-21 blocks it, until it is Release Ready, Shipped or done"),
Waits("ABC-24", "ABC-21 and ABC-22 block it, until each is Release Ready, Shipped or done"),
]))
self.assertEqual(chunks(issues[:2], {}), ([Chunk("ABC-19", "api")], [Waits("ABC-20", "ABC-19 blocks it")]))
self.assertEqual(held_up(issues, ("Release Ready", "Shipped")), {"ABC-21": ["ABC-22", "ABC-24"], "ABC-22": ["ABC-24"]})
def test_a_humans_task_gets_no_window_for_an_issue_it_blocks_that_is_in_an_unblocking_status(self) -> None:
issues = [issue("ABC-19", "do-epic-human"), issue("ABC-20", "repo:api", blockers=("ABC-19",), status="Release Ready")]
self.assertEqual(chunks(issues, {}, ("Release Ready",))[0], [])
def test_an_unblocking_status_matches_whatever_its_case(self) -> None:
issues = [issue("ABC-19", "repo:api", status="Release Ready"), issue("ABC-20", "repo:api", blockers=("ABC-19",))]
self.assertEqual(chunks(issues, {}, ("release ready",)), ([Chunk("ABC-20", "api")], [Waits("ABC-19", "its work has landed: it is Release Ready, and the epic's finishing waits until Jira counts it done")]))
def test_names_an_unblocking_status_only_for_a_blocker_inside_the_epic(self) -> None:
unseen = "outside the epic, finish: remove such a link in Jira once its issue is done"
issues = [issue("ABC-19", "repo:api"), issue("ABC-20", "repo:api", blockers=("XYZ-1",)), issue("ABC-21", "repo:api", blockers=("ABC-19", "XYZ-1")), issue("ABC-22", "repo:api", blockers=("ABC-19", "ABC-20", "XYZ-1"))]
self.assertEqual(chunks(issues, {}, ("Release Ready",))[1], [
Waits("ABC-20", f"XYZ-1 blocks it; do-epic cannot see XYZ-1, {unseen}"),
Waits("ABC-21", f"ABC-19 and XYZ-1 block it, until ABC-19 is Release Ready or done; do-epic cannot see XYZ-1, {unseen}"),
Waits("ABC-22", f"ABC-19 and ABC-20 and XYZ-1 block it, until ABC-19 and ABC-20 are Release Ready or done; do-epic cannot see XYZ-1, {unseen}"),
])
def test_a_split_item_unblocks_what_it_blocks_once_each_sub_task_is_in_an_unblocking_status(self) -> None:
issues = [issue("ABC-20", "split-by-repo"), issue("ABC-23", "repo:api", parent="ABC-20", status="Release Ready"), issue("ABC-24", "repo:web", parent="ABC-20", done=True), issue("ABC-21", "repo:api", blockers=("ABC-20",))]
self.assertEqual(chunks(issues, {}, ("Release Ready",))[0], [Chunk("ABC-21", "api")])
self.assertEqual(chunks(issues, {})[0], [Chunk("ABC-23", "api")])
self.assertEqual(chunks([*issues[:2], issue("ABC-24", "repo:web", parent="ABC-20"), issues[3]], {}, ("Release Ready",))[0], [Chunk("ABC-24", "web")])
class RoomInARepo(unittest.TestCase):
def test_a_repo_with_room_and_no_loop_claude_takes_a_chunk(self) -> None:
@@ -171,12 +204,13 @@ class StartingAnEpicsChunks(unittest.TestCase):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.home = pathlib.Path(folder.name)
self.order: tuple[str, ...] = ()
def epic(self, cap: int, **limits: int) -> Epic:
"""An epic whose repos are checked out under the home folder, each with its `parallel-chunks`."""
def locate(name: str) -> tuple[pathlib.Path, int] | Failure:
return (self.home / "code" / name, limits[name]) if name in limits else Failure(f"no project config names {name}")
return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"LOOP_CLAUDE_X": "1", "OTHER": "2"}, {})
return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"LOOP_CLAUDE_X": "1", "OTHER": "2"}, {}, self.order)
def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started:
found = start_chunks(epic, issues, False, own, run)
@@ -195,6 +229,18 @@ class StartingAnEpicsChunks(unittest.TestCase):
def parked(self, issue_key: str, on: str = "an approval") -> None:
self.assertIsNone(park(self.home / ".local/state/do-epic/ABC-12", Parked(issue_key, f"/code/api-{issue_key}", "7", "0c0f", on)))
def test_starts_the_chunks_in_the_epics_start_order_and_those_it_leaves_out_last_in_backlog_order(self) -> None:
self.order = ("ABC-23", "ABC-21")
run = Tmux()
issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "do-epic-claude"), issue("ABC-23", "do-epic-claude")]
found = self.start(self.epic(3), issues, run)
self.assertEqual(found, Started(["ABC-23", "ABC-21", "ABC-20"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 3")]))
def test_the_epics_finishing_starts_whatever_the_start_order_names(self) -> None:
self.order = ("ABC-20",)
found = start_chunks(self.epic(1), [issue("ABC-20", "do-epic-claude", done=True)], True, None, Tmux())
self.assertEqual(found, Started(["ABC-12"], []))
def test_a_parked_chunk_waits_in_its_window_and_takes_no_slot_of_the_epic_or_its_repo(self) -> None:
self.parked("ABC-20")
run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, ""))
@@ -393,6 +439,8 @@ class TheFirstPrompt(unittest.TestCase):
self.assertIn("--file \"<summary>\" --blocked-by ABC-23 --parent ABC-20 --label repo:api` and its detail on stdin.", task)
task = chunk_prompt.task(issue("ABC-20", "twu-4", "urgent"), "ABC-12", {"twu-4": "tenant-web-ui-4"}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", CONFIG)
self.assertIn("--file \"<summary>\" --blocked-by ABC-20 --label twu-4` and its detail on stdin.", task)
task = chunk_prompt.task(issue("ABC-20", "repo:tenant-web-ui-4"), "ABC-12", {"twu-4": "tenant-web-ui-4"}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", CONFIG)
self.assertIn("--file \"<summary>\" --blocked-by ABC-20 --label twu-4` and its detail on stdin.", task)
def test_a_chunk_without_a_repo_is_told_nothing_of_shipping(self) -> None:
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, None, pathlib.Path("/b/do-epic"), "Swedish", None)
@@ -417,6 +465,29 @@ class TheFirstPrompt(unittest.TestCase):
self.assertIn("leave the changelog as it is", told)
self.assertNotIn("## Unreleased", told)
def test_a_repo_with_an_epic_branch_is_told_to_branch_off_it_and_that_the_merge_needs_no_person(self) -> None:
config = dataclasses.replace(CONFIG, epic_branch="epic/{epic}", merge="human")
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", config)
self.assertIn("The chunk's pull request goes into the epic's working branch `epic/ABC-12`, not into the default branch", task)
self.assertIn("make the chunk's worktree and branch off `origin/epic/ABC-12`", task)
self.assertIn("`chunk-pr merge` merges into `epic/ABC-12` without waiting for a person. Where the chunk's tests run", task)
self.assertNotIn("leaves the pull request ready for a person to merge", task)
self.assertIn("Where the chunk's tests run other repos of the epic, run each at its branch `epic/ABC-12` where it has one, else at its default branch, and name in the chunk's summary each repo that ran at its default branch.", task)
self.assertNotIn("chunk-pr push", task)
self.assertIn(f"{chunk_prompt.shipping(config)} {chunk_prompt.epic_branch_rule(config, 'ABC-12')} Its summary: ", task)
def test_a_repo_whose_reviewer_is_asked_by_a_comment_is_told_to_push_with_chunk_pr(self) -> None:
config = dataclasses.replace(CONFIG, epic_branch="{epic}", review_request_comment="@reviewbot review")
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", config)
self.assertIn("`chunk-pr merge` merges into `ABC-12` without waiting for a person. After `chunk-pr ready`, push each commit with `chunk-pr push`, which asks the repo's auto-reviewer to review the new head, and wait for that review. Where the chunk's tests run", task)
def test_a_repo_without_an_epic_branch_is_told_nothing_of_one(self) -> None:
config = dataclasses.replace(CONFIG, merge="human")
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", {}, "/code/api", pathlib.Path("/b/do-epic"), "Swedish", config)
self.assertEqual(chunk_prompt.epic_branch_rule(config, "ABC-12"), "")
self.assertNotIn("working branch", task)
self.assertIn("leaves the pull request ready for a person to merge", task)
def test_an_answer_the_judge_quoted_names_the_epics_description_first(self) -> None:
self.assertTrue(chunk_prompt.WORKER.answered("Q", "A", Route(Rung("off-the-ladder")), None, False).startswith("Your question: Q\n\nthe epic's description, "))
+24 -7
View File
@@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.test_repo_pick import Claude, says
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from do_epic.split import finished, is_split, Split, split, SPLIT_LABEL, SPLIT_SCHEMA
from do_epic.split import finished, is_split, Split, split, SPLIT_LABEL, SPLIT_SCHEMA, task_summary
from claude_code.reply import Limited
from do_epic.backend.fake import MemoryEpic
from model_routing.ladder import Rung
@@ -51,7 +51,7 @@ class Split_(unittest.TestCase):
return [issue for issue in self.issues() if issue.parent == self.key]
def run_split(self, claude: Claude, by_person: bool = False): # type: ignore[no-untyped-def]
return split(self.store, self.issue(), {}, by_person, RULE, "Swedish", ("/repos/api", "/repos/web"), RUNG, claude, "/rules")
return split(self.store, self.issue(), {}, by_person, RULE, "Swedish", ("/repos/api", "/repos/web"), RUNG, claude, "/rules", None)
def test_files_a_sub_task_per_repo_labelled_for_it_and_marks_the_parent(self) -> None:
done = self.run_split(says(TWO))
@@ -61,6 +61,23 @@ class Split_(unittest.TestCase):
self.assertEqual(self.issue().labels, ("api", SPLIT_LABEL))
self.assertEqual(self.store.comments, {})
def test_files_each_sub_task_as_the_teams_template_and_label_say(self) -> None:
team = {"twu-4": "web", "core-4": "api"}
done = split(self.store, self.issue(), team, False, RULE, "Swedish", (), RUNG, says(TWO), "/rules", "{label}: {Summary}")
self.assertEqual((done, [(task.summary, task.labels) for task in self.tasks()]), (Split(("api", "web"), tuple(task.key for task in self.tasks())), [("core-4: Count the runs.", ("core-4",)), ("twu-4: Count the runs.", ("twu-4",))]))
def test_a_template_names_the_repo_where_the_table_does_not(self) -> None:
self.assertEqual(task_summary("api", "bygg stöd", {}, "{label}: {Summary}"), "api: Bygg stöd")
def test_a_template_names_the_teams_label_where_the_table_names_the_repo(self) -> None:
self.assertEqual(task_summary("api", "bygg stöd", {"core": "api"}, "{Summary} ({label})"), "Bygg stöd (core)")
def test_a_template_leaves_an_empty_summary_empty(self) -> None:
self.assertEqual(task_summary("api", "", {}, "{Summary}"), "")
def test_without_a_template_the_summary_is_the_repo_in_brackets_and_the_item_summary(self) -> None:
self.assertEqual(task_summary("api", "bygg stöd", {"core": "api"}, None), "[api] bygg stöd")
def test_an_item_a_person_filed_a_sub_task_under_is_left_alone_without_asking_claude(self) -> None:
self.store.issues.append(EpicIssue("ABC-90", "twu-4: Count them.", "", ("twu-4",), None, "To Do", False, self.key))
claude = says(TWO)
@@ -68,7 +85,7 @@ class Split_(unittest.TestCase):
def test_a_sub_task_with_the_teams_label_counts_as_its_repos_when_a_failed_run_is_taken_up(self) -> None:
self.store.issues.append(EpicIssue("ABC-90", "Serve it.", "", ("backend",), None, "To Do", False, self.key, by_loop=True))
done = split(self.store, self.issue(), {"backend": "api"}, False, RULE, "Swedish", (), RUNG, says(TWO), "/rules")
done = split(self.store, self.issue(), {"backend": "api"}, False, RULE, "Swedish", (), RUNG, says(TWO), "/rules", None)
self.assertEqual((done, [task.labels for task in self.tasks()]), (Split(("api", "web"), (self.tasks()[1].key,)), [("backend",), ("repo:web",)]))
def test_comments_on_a_persons_issue_for_the_team_once_its_sub_tasks_are_filed(self) -> None:
@@ -139,8 +156,8 @@ class Split_(unittest.TestCase):
self.run_split(claude)
args, cwd, prompt = claude.calls[0]
self.assertEqual(cwd, "/rules")
self.assertEqual(args[:12], ["-p", "--json-schema", json.dumps(SPLIT_SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", "Read,Grep,Glob", "--add-dir", "/repos/api", "--add-dir"])
self.assertEqual(args[12], "/repos/web")
self.assertEqual(args[:13], ["-p", "--json-schema", json.dumps(SPLIT_SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", "Read,Grep,Glob", "--strict-mcp-config", "--add-dir", "/repos/api", "--add-dir"])
self.assertEqual(args[13], "/repos/web")
self.assertIn(RULE, prompt)
self.assertIn("## Item ABC-100: Count the runs.", prompt)
self.assertIn("write each part's change in Swedish.", prompt)
@@ -154,7 +171,7 @@ class Split_(unittest.TestCase):
assert isinstance(key, str)
bare = next(issue for issue in self.issues() if issue.key == key)
claude = says(TWO)
split(self.store, bare, {}, False, RULE, "Swedish", (), RUNG, claude, "/rules")
split(self.store, bare, {}, False, RULE, "Swedish", (), RUNG, claude, "/rules", None)
prompt = claude.calls[0][2]
self.assertIn("checked out at: none. Read them", prompt)
self.assertTrue(prompt.endswith("\nLabels: none\n\n(no description)\n"))
@@ -164,7 +181,7 @@ class Split_(unittest.TestCase):
key = self.store.file("ABC-12", "Two labels.", "Why.", ("api", "urgent"))
assert isinstance(key, str)
claude = says(TWO)
split(self.store, next(issue for issue in self.issues() if issue.key == key), {}, False, RULE, "Swedish", (), RUNG, claude, "/rules")
split(self.store, next(issue for issue in self.issues() if issue.key == key), {}, False, RULE, "Swedish", (), RUNG, claude, "/rules", None)
self.assertIn("\nLabels: api, urgent\n", claude.calls[0][2])
def test_asks_a_persons_issue_for_a_comment(self) -> None:
+19 -2
View File
@@ -1,3 +1,4 @@
import dataclasses
import os
import pathlib
import tempfile
@@ -23,13 +24,21 @@ class TheStatusLines(unittest.TestCase):
parked.park(self.folder, parked.Parked(key, f"/code/api-{key}", "7", "s", on))
os.utime(parked.file_of(self.folder, key), (SINCE, SINCE))
def lines(self, issues: list, *windows: tuple[str, str, bool, str]) -> list[str] | Failure:
return status.lines("ABC-12", self.home, issues, {}, Tmux(*windows))
def lines(self, issues: list, *windows: tuple[str, str, bool, str], unblocking: tuple[str, ...] = ()) -> list[str] | Failure:
return status.lines("ABC-12", self.home, issues, {}, unblocking, Tmux(*windows), ())
def test_a_chunk_that_asks_says_where_to_answer_and_one_that_works_runs(self) -> None:
found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20 ?", False, ""), (EPIC, "ABC-21", False, ""))
self.assertEqual(found, ["ABC-20 asks you: answer its question in the tmux window epic-ABC-12:ABC-20", "ABC-21 runs"])
def test_names_the_status_a_blocker_must_reach_and_the_one_a_merged_issue_is_in(self) -> None:
found = self.lines([issue("ABC-20", "repo:api", status="Release Ready"), issue("ABC-21", "repo:api", status="Code Review"), issue("ABC-22", "repo:api", blockers=("ABC-21",))], (EPIC, "ABC-21", False, ""), unblocking=("Release Ready",))
self.assertEqual(found, [
"ABC-20 waits: its work has landed: it is Release Ready, and the epic's finishing waits until Jira counts it done",
"ABC-21 runs",
"ABC-22 waits: ABC-21 blocks it, until it is Release Ready or done",
])
def test_a_parked_chunk_says_what_it_awaits_and_since_when(self) -> None:
self.park("ABC-20", "an approval")
self.assertEqual(self.lines([issue("ABC-20", "repo:api")], (EPIC, "ABC-20 awaits its checks", False, "")), [f"ABC-20 waits: it is parked: its pull request #7 awaits its checks, since {SINCE_ON}"])
@@ -42,6 +51,14 @@ class TheStatusLines(unittest.TestCase):
self.park("ABC-20", "an approval")
self.assertEqual(self.lines([issue("ABC-20", "repo:api")]), [f"ABC-20 waits: it is parked: its pull request #7 awaits an approval, since {SINCE_ON}, and its window stopped; run `do-epic ABC-12` to start it again"])
def test_an_issue_without_scores_says_that_it_starts_after_each_that_holds_them(self) -> None:
held = dataclasses.replace(issue("ABC-21", "repo:api"), scores={"L": 1, "E": 1, "I": 1, "S": 1})
room = "it has not started; `do-epic ABC-12` starts it once the epic and its repo have room"
found = status.lines("ABC-12", self.home, [issue("ABC-20", "repo:api"), held], {}, (), Tmux(), ("ABC-21",))
self.assertEqual(found, [f"ABC-20 waits: {room}, after each issue that holds every score, since it doesn't", f"ABC-21 waits: {room}"])
# Where no issue starts by score, each starts in the tracker's rank order.
self.assertEqual(self.lines([issue("ABC-20", "repo:api"), held]), [f"ABC-20 waits: {room}", f"ABC-21 waits: {room}"])
def test_a_stopped_chunk_and_one_not_started_say_so(self) -> None:
found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20", True, ""))
self.assertEqual(found, ["ABC-20 waits: its window stopped; run `do-epic ABC-12` to start it again", "ABC-21 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room"])
+5 -2
View File
@@ -24,12 +24,15 @@ def url_beside(origin_url: str, name: str) -> str | None:
return place.group(1) + name if place and not place.group(1).endswith("//") else None
def runner(cwd: str) -> Run:
def runner(cwd: str, timeout: float | None = None) -> Run:
"""Runs a command in cwd, stopped after timeout seconds where one is given."""
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)
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout)
except OSError as failure:
return Failure(f"{command[0]} could not start: {failure}")
except subprocess.TimeoutExpired:
return Failure(f"{' '.join(command[:3])}: stopped after {timeout} s")
if done.returncode:
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
return done.stdout
+91 -1
View File
@@ -1,11 +1,13 @@
"""Finding a pull request from origin's own branch, and waiting for the checks on its head commit."""
"""Finding a pull request from origin's own branch, listing the ready ones, reading whether one merges into its base, and waiting for the checks on its head commit."""
import dataclasses
import fnmatch
import json
import re
import typing
from failure import Failure
from forge.commands import Forge, gitea, Run
from forge.reviews import GITEA_DRAFT
# 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
@@ -44,6 +46,94 @@ 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]}")
@dataclasses.dataclass(frozen=True)
class ReadyPull:
"""An open pull request from one of origin's own branches that is no draft."""
number: str
url: str
# The commit ID of its head.
head: str
def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure:
"""Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT); Gitea names no head repo for a fork that was deleted. A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it."""
if forge == "gh":
# A limit: an awaited pull request past the first 100 open ones, drafts and forks counted, is not seen. `--draft=false` would make gh search, and GitHub's search index lags a pull request just marked ready.
listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"])
if isinstance(listed, Failure):
return listed
rows = [line.split("\t") for line in listed.splitlines()]
found = [ReadyPull(*row[:3]) for row in rows if row[3:] == ["false", "false"]]
else:
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
if isinstance(pulls, Failure):
return pulls
try:
found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if (pull["head"]["repo"] or {}).get("full_name") == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)]
except (AttributeError, KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
return [pull for pull in found if pull.number.isascii() and pull.number.isdigit() and isinstance(pull.head, str) and re.fullmatch(r"[0-9a-f]{40,64}", pull.head)]
# Why a pull request doesn't merge into its base as it stands, as the words after "pull request #<N>".
CONFLICTS = "conflicts with its base branch"
BEHIND = "is behind its base branch, whose protection requires it up to date"
def unmergeable(forge: Forge, number: str, run: Run) -> str | None | Failure:
"""Why pull request number doesn't merge into its base as it stands: CONFLICTS or BEHIND. None where it merges, and while GitHub still computes whether it does.
GitHub reports a pull request as behind only where the base's protection requires an up-to-date branch. Gitea's `mergeable` never tells that case. Gitea also answers false for the seconds it checks for conflicts after a push to either branch, which reads as CONFLICTS here.
"""
if forge == "gh":
viewed = run(["gh", "pr", "view", number, "--json", "mergeable,mergeStateStatus"])
if isinstance(viewed, Failure):
return viewed
try:
state = json.loads(viewed)
return CONFLICTS if state["mergeable"] == "CONFLICTING" else BEHIND if state["mergeStateStatus"] == "BEHIND" else None
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no mergeability: {viewed.strip()[:200]}")
pull = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}")
if isinstance(pull, Failure):
return pull
try:
return CONFLICTS if pull["mergeable"] is False else None
except (KeyError, TypeError):
return Failure(f"tea api answered pull request {number} in a shape that can't be read: {str(pull)[:200]}")
def other_base(forge: Forge, number: str, base: str, run: Run) -> Failure | None:
"""A Failure, naming both branches, where the forge merges pull request number into another branch than base, the one its checkout takes. None where the two agree.
A tool decides from the checkout's base who merges the pull request, so it doesn't act on one the forge would merge elsewhere."""
onto = base_branch(forge, number, run)
if isinstance(onto, Failure) or onto == base:
return onto if isinstance(onto, Failure) else None
return Failure(f"pull request #{number} merges into {onto} on the forge, but this checkout takes {base} as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config")
def base_branch(forge: Forge, number: str, run: Run) -> str | Failure:
"""The branch the forge merges pull request number into."""
if forge == "gh":
viewed = run(["gh", "pr", "view", number, "--json", "baseRefName"])
if isinstance(viewed, Failure):
return viewed
try:
name = json.loads(viewed)["baseRefName"]
except (ValueError, KeyError, TypeError):
name = None
return name if name and isinstance(name, str) else Failure(f"gh pr view printed no base branch: {viewed.strip()[:200]}")
pull = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}")
if isinstance(pull, Failure):
return pull
try:
name = pull["base"]["ref"]
except (KeyError, TypeError):
name = None
return name if name and isinstance(name, str) else Failure(f"tea api answered pull request {number} in a shape that can't be read: {str(pull)[:200]}")
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.
+108 -2
View File
@@ -1,14 +1,17 @@
import itertools
import json
import os
import pathlib
import sys
import tempfile
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, required_checks, WAIT_SECONDS
from forge.pulls import BEHIND, CheckFailed, checks_now, checks_passed, CONFLICTS, open_pull, other_base, Pending, POLL_SECONDS, ready_pulls, ReadyPull, required_checks, unmergeable, WAIT_SECONDS
from failure import Failure
from forge.commands import forge_of, gitea, url_beside
from forge.commands import forge_of, gitea, runner, url_beside
class ForgeOf(unittest.TestCase):
@@ -47,6 +50,71 @@ class OpenPull(unittest.TestCase):
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]}")
class Unmergeable(unittest.TestCase):
def gh(self, mergeable: str, state: str) -> str | None | Failure:
commands: list[list[str]] = []
answer = unmergeable("gh", "7", lambda command: commands.append(command) or f'{{"mergeable": "{mergeable}", "mergeStateStatus": "{state}"}}')
self.assertEqual(commands, [["gh", "pr", "view", "7", "--json", "mergeable,mergeStateStatus"]])
return answer
def test_a_github_pull_request_that_conflicts_with_its_base_says_so(self):
self.assertEqual(self.gh("CONFLICTING", "DIRTY"), CONFLICTS)
def test_a_github_pull_request_behind_a_base_that_requires_it_up_to_date_says_so(self):
self.assertEqual(self.gh("MERGEABLE", "BEHIND"), BEHIND)
def test_a_github_pull_request_merges_whatever_else_holds_it_and_while_github_computes(self):
for mergeable, state in (("MERGEABLE", "CLEAN"), ("MERGEABLE", "BLOCKED"), ("MERGEABLE", "UNSTABLE"), ("UNKNOWN", "UNKNOWN")):
with self.subTest(mergeable=mergeable, state=state):
self.assertIsNone(self.gh(mergeable, state))
def test_a_gitea_pull_request_conflicts_only_where_gitea_says_it_is_not_mergeable(self):
commands: list[list[str]] = []
self.assertEqual(unmergeable("tea", "7", lambda command: commands.append(command) or '{"number": 7, "mergeable": false}'), CONFLICTS)
self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls/7"]])
self.assertIsNone(unmergeable("tea", "7", lambda command: '{"number": 7, "mergeable": true}'))
def test_fails_where_the_forge_cannot_be_read_or_answers_in_another_shape(self):
unread = Failure("no network")
for forge in ("gh", "tea"):
with self.subTest(forge=forge):
self.assertIs(unmergeable(forge, "7", lambda command: unread), unread)
self.assertEqual(unmergeable("gh", "7", lambda command: LONG).reason, f"gh pr view printed no mergeability: {LONG[:200]}")
self.assertEqual(unmergeable("gh", "7", lambda command: "not json").reason, "gh pr view printed no mergeability: not json")
self.assertEqual(unmergeable("gh", "7", lambda command: '{"mergeable": "MERGEABLE"}').reason, 'gh pr view printed no mergeability: {"mergeable": "MERGEABLE"}')
self.assertEqual(unmergeable("tea", "7", lambda command: LONG).reason, f"tea api answered pull request 7 in a shape that can't be read: {LONG[:200]}")
self.assertEqual(unmergeable("tea", "7", lambda command: '{"number": 7}').reason, "tea api answered pull request 7 in a shape that can't be read: {'number': 7}")
class OtherBase(unittest.TestCase):
ELSEWHERE = "pull request #7 merges into main on the forge, but this checkout takes ABC-12 as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config"
def test_a_github_pull_request_into_the_base_given_passes_and_one_into_another_fails_naming_both(self):
commands: list[list[str]] = []
self.assertIsNone(other_base("gh", "7", "main", lambda command: commands.append(command) or '{"baseRefName": "main"}'))
self.assertEqual(commands, [["gh", "pr", "view", "7", "--json", "baseRefName"]])
self.assertEqual(other_base("gh", "7", "ABC-12", lambda command: '{"baseRefName": "main"}'), Failure(self.ELSEWHERE))
def test_a_gitea_pull_request_into_the_base_given_passes_and_one_into_another_fails_naming_both(self):
commands: list[list[str]] = []
self.assertIsNone(other_base("tea", "7", "main", lambda command: commands.append(command) or '{"number": 7, "base": {"ref": "main"}}'))
self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls/7"]])
self.assertEqual(other_base("tea", "7", "ABC-12", lambda command: '{"number": 7, "base": {"ref": "main"}}'), Failure(self.ELSEWHERE))
def test_fails_where_the_forge_cannot_be_read_or_names_no_base(self):
unread = Failure("no network")
for forge in ("gh", "tea"):
with self.subTest(forge=forge):
self.assertIs(other_base(forge, "7", "main", lambda command: unread), unread)
self.assertEqual(other_base("gh", "7", "main", lambda command: LONG).reason, f"gh pr view printed no base branch: {LONG[:200]}")
self.assertEqual(other_base("gh", "7", "main", lambda command: "not json").reason, "gh pr view printed no base branch: not json")
self.assertEqual(other_base("gh", "7", "main", lambda command: '{"baseRefName": ""}').reason, 'gh pr view printed no base branch: {"baseRefName": ""}')
self.assertEqual(other_base("tea", "7", "main", lambda command: '{"base": {"ref": 7}}').reason, "tea api answered pull request 7 in a shape that can't be read: {'base': {'ref': 7}}")
self.assertEqual(other_base("tea", "7", "main", lambda command: LONG).reason, f"tea api answered pull request 7 in a shape that can't be read: {LONG[:200]}")
self.assertEqual(other_base("tea", "7", "main", lambda command: '{"number": 7, "base": {}}').reason, "tea api answered pull request 7 in a shape that can't be read: {'number': 7, 'base': {}}")
self.assertEqual(other_base("tea", "7", "main", lambda command: '{"number": 7, "base": {"ref": null}}').reason, "tea api answered pull request 7 in a shape that can't be read: {'number': 7, 'base': {'ref': None}}")
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)
@@ -135,6 +203,44 @@ class ChecksPassed(unittest.TestCase):
self.assertEqual(checks_passed("tea", "1", "abc", set(), tea([LONG]), self.fail).reason, f"tea api printed no commit status for abc: {LONG[:200]}")
SHA = "a" * 40
GITEA_PULL = {"number": 7, "html_url": "https://gitea.example/o/r/pulls/7", "title": "Do 7", "head": {"sha": SHA, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}}
class ReadyPulls(unittest.TestCase):
def test_lists_on_gh_each_open_pull_request_from_origins_own_branches_that_is_no_draft(self):
commands: list[list[str]] = []
listed = f"7\thttps://github.com/o/r/pull/7\t{SHA}\tfalse\tfalse\n8\thttps://github.com/o/r/pull/8\t{SHA}\ttrue\tfalse\n9\thttps://github.com/o/r/pull/9\t{SHA}\tfalse\ttrue\n"
self.assertEqual(ready_pulls("gh", lambda command: commands.append(command) or listed), [ReadyPull("7", "https://github.com/o/r/pull/7", SHA)])
self.assertEqual(commands, [["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]])
def test_leaves_out_on_gh_a_row_whose_head_is_no_commit_id(self):
self.assertEqual(ready_pulls("gh", lambda command: "7\thttps://github.com/o/r/pull/7\t--upload-pack=x\tfalse\tfalse\n"), [])
def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self):
fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}}
draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"}
deleted_fork = {**GITEA_PULL, "number": 10, "head": {"sha": SHA, "repo": None}}
commands: list[list[str]] = []
self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft, deleted_fork])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)])
self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]])
def test_fails_where_the_forge_cannot_list_them(self):
self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network")
self.assertEqual(ready_pulls("tea", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}")
class Runner(unittest.TestCase):
def test_prints_what_a_command_printed_and_fails_where_it_exits_nonzero_cannot_start_or_outlasts_its_timeout(self):
self.assertEqual(runner("/")(["echo", "hello"]), "hello\n")
self.assertEqual(runner("/")(["sh", "-c", "echo no >&2; exit 3"]), Failure("sh -c echo no >&2; exit 3: no"))
failed = runner("/")(["no-such-forge-cli", "pr", "list"])
self.assertIsInstance(failed, Failure)
self.assertTrue(failed.reason.startswith("no-such-forge-cli could not start: "), failed.reason)
self.assertEqual(runner("/", 0.05)(["sh", "-c", "sleep 5", "later"]), Failure("sh -c sleep 5: stopped after 0.05 s"))
with tempfile.TemporaryDirectory() as folder:
self.assertEqual(runner(folder)(["pwd", "-P"]), os.path.realpath(folder) + "\n")
if __name__ == "__main__":
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""Keep an epic's working branch on origin: made off the default branch by the epic's first chunk, and level with it before each chunk starts and before the epic's own pull request opens (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`)."""
import re
from failure import Failure
from git_cli.git_repo import Git, git
def levelled(branch: str, default: str, cwd: str | None = None, timeout: float | None = None, run: Git = git, again: bool = True) -> str | Failure:
"""Brings origin's branch level with default, the default branch's ref, such as `origin/main`, and fetches it: what it did, as a sentence. Where origin has no such branch, it makes one at default.
A call to origin still running after timeout seconds fails. again is False in the second try `merged` makes after a push that failed."""
# Asked before the fetch: a branch another chunk makes after the fetch would be on origin and missing here.
held = on_origin(branch, cwd, timeout, run)
failed = held if isinstance(held, Failure) else fetched(cwd, timeout, run)
if isinstance(failed, Failure):
return failed
if not held:
return pushed(default, branch, cwd, timeout, run) or f"Made origin/{branch} off {default}."
return merged(branch, default, cwd, timeout, run, again)
def fetched(cwd: str | None, timeout: float | None, run: Git) -> Failure | None:
"""Fetches origin, and once more where that fails: chunks that start at once fetch into one checkout, and git fails the fetch that finds a ref another one just moved."""
fetch = ("fetch", "--quiet", "origin")
if not isinstance(run(*fetch, cwd=cwd, timeout=timeout), Failure):
return None
second = run(*fetch, cwd=cwd, timeout=timeout)
return second if isinstance(second, Failure) else None
def on_origin(branch: str, cwd: str | None, timeout: float | None, run: Git) -> bool | Failure:
"""Whether origin has branch, asked of origin itself: a fetch keeps this checkout's `origin/<branch>` after origin deleted the branch."""
listed = run("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=cwd, timeout=timeout)
return listed if isinstance(listed, Failure) else bool(listed.strip())
def merged(branch: str, default: str, cwd: str | None, timeout: float | None, run: Git, again: bool) -> str | Failure:
"""Merges default into origin's branch, as this checkout fetched it, and pushes the merge: what it did, as a sentence.
It merges with a merge commit, never a rebase, since several chunks share the branch, and without a checkout, since no worktree has the branch checked out. A Failure where the two don't merge cleanly: a person resolves that, never the loop. Where the push fails, as when another chunk pushed its own merge first, it levels the branch once more from a fresh fetch, unless again is False."""
ours = f"origin/{branch}"
behind = run("rev-list", "--count", f"{ours}..{default}", cwd=cwd)
if isinstance(behind, Failure):
return behind
if behind.strip() == "0":
return f"{ours} already holds {default}."
# git 2.38 or later: merges two commits into a tree without a checkout.
tree = run("merge-tree", "--write-tree", ours, default, cwd=cwd)
if isinstance(tree, Failure):
return unmerged(tree, branch, default)
commit = run("commit-tree", tree.strip(), "-p", ours, "-p", default, "-m", f"Merge remote-tracking branch '{default}' into {branch}", cwd=cwd)
if isinstance(commit, Failure):
return commit
failed = pushed(commit.strip(), branch, cwd, timeout, run)
if failed and again:
return levelled(branch, default, cwd, timeout, run, again=False)
return failed or f"Merged {default} into {ours}."
def unmerged(failed: Failure, branch: str, default: str) -> Failure:
"""Why `git merge-tree --write-tree` didn't merge default into origin's branch, from its Failure.
A conflict prints nothing on stderr, so its reason ends at `git <command>:`, or, from a runner that shows stdout in place of an empty stderr, goes on with the merged tree's id. Git older than 2.38 reads --write-tree as a commit, which it doesn't find. Any other Failure is git's own."""
ours = f"origin/{branch}"
if re.fullmatch(r"git merge-tree [^:]*:\s*(?:[0-9a-f]{40,64}\b.*)?", failed.reason, re.DOTALL):
return Failure(f"{default} doesn't merge into {ours} cleanly, so a person merges it: check {branch} out, run `git merge {default}`, resolve the conflicts and push")
if "unknown rev --write-tree" in failed.reason:
return Failure(f"levelling {ours} with {default} needs git 2.38 or later: {failed.reason}")
return failed
def pushed(commit: str, branch: str, cwd: str | None, timeout: float | None, run: Git) -> Failure | None:
"""Pushes commit as origin's branch, without force, so a push that raced another's fails, and fetches it."""
done = run("push", "--quiet", "origin", f"{commit}:refs/heads/{branch}", cwd=cwd, timeout=timeout)
return done if isinstance(done, Failure) else fetched(cwd, timeout, run)
+22 -1
View File
@@ -23,6 +23,10 @@ GUARD_SETTINGS = [
]
# The key, under `branch.<a chunk's branch>` in a checkout's git config, that names the epic's working branch the chunk merges into (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).
CHUNK_BASE = "chunk-base"
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict", env: typing.Mapping[str, str] | None = None) -> str | Failure:
"""What git printed, run in cwd, else in the current directory.
@@ -72,13 +76,15 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
"""The ref the branch checked out merges into, as last fetched, read in cwd, else in the current directory. That is the default branch's: `origin/<branch>` with that remote, else the local main or master. On a chunk's branch that merges into an epic's working branch (`chunk_base`), it is `origin/<that branch>`, so each tool that measures a chunk against its base reads the chunk's own commits and not the epic's. run runs git.
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
remotes = run("remote", cwd=cwd, guarded=guarded)
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
if base := chunk_base(cwd, guarded, run):
return f"origin/{base}"
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
if not isinstance(recorded, Failure):
return recorded.strip()
@@ -89,6 +95,21 @@ def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: b
return Failure("no origin remote, and no main or master branch to take as the default branch")
def chunk_base(cwd: str | None = None, guarded: bool = False, run: Git = git) -> str | None:
"""The epic's working branch that the branch checked out in cwd merges into, as `record_chunk_base` recorded it; None where none is recorded, as for every branch that merges into the default branch, and on a detached HEAD."""
branch = run("symbolic-ref", "--quiet", "--short", "HEAD", cwd=cwd, guarded=guarded)
if isinstance(branch, Failure):
return None
base = run("config", "--get", f"branch.{branch.strip()}.{CHUNK_BASE}", cwd=cwd, guarded=guarded)
return None if isinstance(base, Failure) else base.strip() or None
def record_chunk_base(branch: str, base: str, cwd: str | None = None, run: Git = git) -> Failure | None:
"""Records in the checkout's git config that the chunk's branch merges into base, an epic's working branch. The branch need not exist yet, and deleting it removes the record."""
recorded = run("config", f"branch.{branch}.{CHUNK_BASE}", base, cwd=cwd)
return recorded if isinstance(recorded, Failure) else None
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
+228
View File
@@ -0,0 +1,228 @@
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 git_cli import git_repo
from git_cli.epic_branch import levelled
from forge.commands import runner
def sh(cwd: pathlib.Path, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=T", "-c", "user.email=t@example.com", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
def scripted(calls: list[tuple[str, ...]], **answers: str | Failure | list[str | Failure]) -> git_repo.Git:
"""A git that records each command in calls and answers it by its first word: as answers has it, else as a checkout where origin/ABC-1 lacks a commit of origin/main that merges in cleanly. A list answers one call with each entry, in order, and every later call with its last."""
answered = {"fetch": "", "ls-remote": "abc\trefs/heads/ABC-1\n", "rev-list": "1\n", "merge-tree": "7ree\n", "commit-tree": "c0mm17\n", "push": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
calls.append(args)
answer = answered[args[0]]
if not isinstance(answer, list):
return answer
return answer.pop(0) if len(answer) > 1 else answer[0]
return run
LOCKED = Failure("git fetch --quiet origin: error: cannot lock ref 'refs/remotes/origin/main': is at 2222 but expected 1111")
class Levelled(unittest.TestCase):
def setUp(self) -> None:
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.origin, self.clone = pathlib.Path(folder.name) / "origin.git", pathlib.Path(folder.name) / "clone"
sh(pathlib.Path(folder.name), "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
sh(pathlib.Path(folder.name), "clone", "--quiet", str(self.origin), str(self.clone))
sh(self.clone, "config", "user.name", "T")
sh(self.clone, "config", "user.email", "t@example.com")
self.commit("main", "a.txt", "one\n")
def commit(self, branch: str, file: str, text: str) -> None:
"""Commits text as file on origin's branch, made off origin/main where origin has none."""
sh(self.clone, "fetch", "--quiet", "origin")
known = subprocess.run(["git", "rev-parse", "--quiet", "--verify", f"refs/remotes/origin/{branch}"], cwd=self.clone, capture_output=True).returncode == 0
sh(self.clone, "checkout", "--quiet", "-B", "scratch", *([f"origin/{branch}"] if known else []))
(self.clone / file).write_text(text)
sh(self.clone, "add", file)
sh(self.clone, "commit", "--quiet", "-m", f"{file} on {branch}")
sh(self.clone, "push", "--quiet", "origin", f"HEAD:refs/heads/{branch}")
sh(self.clone, "fetch", "--quiet", "origin")
def test_makes_the_branch_off_the_default_branch_where_origin_has_none(self) -> None:
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Made origin/ABC-1 off origin/main.")
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), sh(self.origin, "rev-parse", "main"))
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"), "fetched, so a worktree can branch off it")
def test_makes_a_fresh_branch_off_the_default_branch_where_origin_deleted_the_one_this_checkout_still_tracks(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
self.commit("main", "b.txt", "epic\n")
sh(self.origin, "branch", "--quiet", "-D", "ABC-1")
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Made origin/ABC-1 off origin/main.")
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), sh(self.origin, "rev-parse", "main"), "not the commits the deleted branch held")
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"))
def test_a_branch_another_chunk_makes_between_its_two_calls_to_origin_is_no_failure(self) -> None:
calls: list[tuple[str, ...]] = []
def raced(*args: str, **options: object) -> str | Failure:
answer = git_repo.git(*args, **options)
calls.append(args)
if len(calls) == 1:
sh(self.origin, "branch", "--quiet", "ABC-1", "main")
return answer
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone), run=raced), "Made origin/ABC-1 off origin/main.")
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "main"))
def test_asks_origin_for_exactly_the_branch(self) -> None:
calls: list[tuple[str, ...]] = []
levelled("ABC-1", "origin/main", run=scripted(calls))
self.assertEqual(calls[0], ("ls-remote", "--heads", "origin", "refs/heads/ABC-1"))
def test_an_origin_that_cannot_say_whether_it_has_the_branch_fails_with_gits_reason(self) -> None:
calls: list[tuple[str, ...]] = []
unreachable = Failure("git ls-remote --heads origin refs/heads/ABC-1: fatal: unable to access origin")
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, ls_remote=unreachable)), unreachable)
self.assertEqual([args[0] for args in calls], ["ls-remote"], "makes no branch on an origin it could not ask")
def test_leaves_a_branch_that_holds_the_default_branch(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
before = sh(self.origin, "rev-parse", "ABC-1")
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "origin/ABC-1 already holds origin/main.")
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
def test_merges_a_moved_default_branch_in_with_a_merge_commit_and_no_checkout(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
epic = sh(self.origin, "rev-parse", "ABC-1")
self.commit("main", "c.txt", "main\n")
checked_out = sh(self.clone, "rev-parse", "HEAD")
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), "Merged origin/main into origin/ABC-1.")
self.assertEqual(sh(self.origin, "rev-list", "--parents", "-n", "1", "ABC-1").split()[1:], [epic, sh(self.origin, "rev-parse", "main")])
self.assertEqual(sh(self.origin, "ls-tree", "--name-only", "ABC-1").split(), ["a.txt", "b.txt", "c.txt"])
self.assertEqual(sh(self.origin, "log", "-1", "--format=%s", "ABC-1"), "Merge remote-tracking branch 'origin/main' into ABC-1")
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(self.origin, "rev-parse", "ABC-1"))
self.assertEqual(sh(self.clone, "rev-parse", "HEAD"), checked_out)
def test_a_conflict_fails_for_a_person_and_leaves_the_branch(self) -> None:
self.commit("ABC-1", "a.txt", "epic\n")
before = sh(self.origin, "rev-parse", "ABC-1")
self.commit("main", "a.txt", "main\n")
done = levelled("ABC-1", "origin/main", cwd=str(self.clone))
assert isinstance(done, Failure), done
self.assertEqual(done.reason, "origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it: check ABC-1 out, run `git merge origin/main`, resolve the conflicts and push")
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
def test_a_conflict_fails_for_a_person_from_a_runner_that_shows_stdout_where_stderr_is_empty(self) -> None:
self.commit("ABC-1", "a.txt", "epic\n")
self.commit("main", "a.txt", "main\n")
run = runner(str(self.clone))
done = levelled("ABC-1", "origin/main", run=lambda *args, **more: run(["git", *args]))
self.assertEqual(done, Failure("origin/main doesn't merge into origin/ABC-1 cleanly, so a person merges it: check ABC-1 out, run `git merge origin/main`, resolve the conflicts and push"))
def test_a_merge_that_fails_other_than_by_a_conflict_fails_with_gits_reason(self) -> None:
sh(self.clone, "checkout", "--quiet", "--orphan", "stray")
sh(self.clone, "commit", "--quiet", "-m", "stray")
sh(self.clone, "push", "--quiet", "origin", "HEAD:refs/heads/ABC-1")
before = sh(self.origin, "rev-parse", "ABC-1")
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone)), Failure("git merge-tree --write-tree origin/ABC-1 origin/main: fatal: refusing to merge unrelated histories"))
self.assertEqual(sh(self.origin, "rev-parse", "ABC-1"), before)
def test_a_git_older_than_2_38_fails_naming_the_git_levelling_needs(self) -> None:
# What git 2.36 prints: it reads --write-tree as a commit.
old = Failure("git merge-tree --write-tree origin/ABC-1 origin/main: fatal: unknown rev --write-tree")
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted([], merge_tree=old)), Failure("levelling origin/ABC-1 with origin/main needs git 2.38 or later: git merge-tree --write-tree origin/ABC-1 origin/main: fatal: unknown rev --write-tree"))
def test_a_merge_another_chunk_pushed_first_is_fetched_and_found_level(self) -> None:
self.commit("ABC-1", "b.txt", "epic\n")
self.commit("main", "c.txt", "main\n")
other = self.clone.parent / "other"
sh(self.clone.parent, "clone", "--quiet", str(self.origin), str(other))
sh(other, "config", "user.name", "Other")
sh(other, "config", "user.email", "other@example.com")
raced: list[str | Failure] = []
def racing(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
"""Runs git, after the other clone levels the branch just before this clone's first push."""
if args[0] == "push" and not raced:
raced.append(levelled("ABC-1", "origin/main", cwd=str(other)))
return git_repo.git(*args, cwd=cwd, timeout=timeout, guarded=guarded, errors=errors)
self.assertEqual(levelled("ABC-1", "origin/main", cwd=str(self.clone), run=racing), "origin/ABC-1 already holds origin/main.")
self.assertEqual(raced, ["Merged origin/main into origin/ABC-1."])
self.assertEqual(sh(self.clone, "rev-parse", "origin/ABC-1"), sh(other, "rev-parse", "origin/ABC-1"))
def test_a_push_that_fails_again_after_a_fresh_fetch_fails_with_gits_reason(self) -> None:
calls: list[tuple[str, ...]] = []
declined = Failure("git push --quiet origin c0mm17:refs/heads/ABC-1: ! [remote rejected] c0mm17 -> ABC-1 (protected branch hook declined)")
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, push=declined)), declined)
self.assertEqual([args[0] for args in calls], ["ls-remote", "fetch", "rev-list", "merge-tree", "commit-tree", "push"] * 2)
def test_a_fetch_that_fails_is_tried_once_more_since_a_chunk_starting_beside_it_may_hold_the_ref(self) -> None:
merge = ["rev-list", "merge-tree", "commit-tree", "push"]
for fetches, names in (([LOCKED, ""], ["ls-remote", "fetch", "fetch", *merge, "fetch"]), (["", LOCKED, ""], ["ls-remote", "fetch", *merge, "fetch", "fetch"])):
with self.subTest(fetches=fetches):
calls: list[tuple[str, ...]] = []
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, fetch=list(fetches))), "Merged origin/main into origin/ABC-1.")
self.assertEqual([args[0] for args in calls], names)
def test_a_fetch_that_fails_twice_fails_with_gits_reason(self) -> None:
calls: list[tuple[str, ...]] = []
self.assertEqual(levelled("ABC-1", "origin/main", run=scripted(calls, fetch=LOCKED)), LOCKED)
self.assertEqual([args[0] for args in calls], ["ls-remote", "fetch", "fetch"])
def test_every_call_to_origin_runs_in_the_checkout_and_stops_after_the_timeout_given(self) -> None:
for answers, origin_calls in (({"ls_remote": ""}, ["ls-remote", "fetch", "push", "fetch"]), ({"push": Failure("git push: rejected")}, ["ls-remote", "fetch", "push", "ls-remote", "fetch", "push"]), ({"fetch": [LOCKED, ""], "ls_remote": ""}, ["ls-remote", "fetch", "fetch", "push", "fetch"]), ({"fetch": ["", LOCKED, ""], "ls_remote": ""}, ["ls-remote", "fetch", "push", "fetch", "fetch"])):
with self.subTest(origin_calls=origin_calls):
timed: list[tuple[str, float | None, str | None]] = []
answering = scripted([], **answers)
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
timed.append((args[0], timeout, cwd))
return answering(*args, cwd=cwd, timeout=timeout, guarded=guarded, errors=errors)
levelled("ABC-1", "origin/main", cwd="/checkout", timeout=5, run=run)
self.assertEqual([call for call in timed if call[0] in ("fetch", "ls-remote", "push")], [(name, 5, "/checkout") for name in origin_calls])
class ChunkBase(unittest.TestCase):
def setUp(self) -> None:
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.clone = pathlib.Path(folder.name)
sh(self.clone, "init", "--quiet", "--initial-branch=main")
sh(self.clone, "remote", "add", "origin", "https://example.com/acme.git")
sh(self.clone, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
def test_a_branch_with_a_recorded_base_measures_against_it_and_any_other_against_the_default_branch(self) -> None:
self.assertIsNone(git_repo.record_chunk_base("ABC-2", "ABC-1", cwd=str(self.clone)))
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main", "main has no recorded base")
sh(self.clone, "checkout", "--quiet", "-b", "ABC-2")
self.assertEqual(git_repo.chunk_base(cwd=str(self.clone)), "ABC-1")
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/ABC-1")
self.assertEqual(git_repo.default_ref(cwd=str(self.clone), guarded=True), "origin/ABC-1")
sh(self.clone, "checkout", "--quiet", "-b", "ABC-3")
self.assertIsNone(git_repo.chunk_base(cwd=str(self.clone)))
self.assertEqual(git_repo.default_ref(cwd=str(self.clone)), "origin/main")
def test_a_guarded_read_of_the_recorded_base_runs_every_git_call_guarded(self) -> None:
calls: list[tuple[tuple[str, ...], bool]] = []
answers = {"remote": "origin\n", "symbolic-ref": "ABC-2\n", "config": "ABC-1\n"}
def run(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
calls.append((args, guarded))
return answers[args[0]]
self.assertEqual(git_repo.default_ref(guarded=True, run=run), "origin/ABC-1")
self.assertEqual(calls, [(("remote",), True), (("symbolic-ref", "--quiet", "--short", "HEAD"), True), (("config", "--get", "branch.ABC-2.chunk-base"), True)])
def test_a_base_git_cannot_record_fails_with_gits_reason(self) -> None:
refused = Failure("git config branch.ABC-2.chunk-base ABC-1: could not lock config file")
self.assertEqual(git_repo.record_chunk_base("ABC-2", "ABC-1", run=lambda *args, **more: refused), refused)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -9,7 +9,7 @@ from agent_cycle.worker_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."""
"""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 task is quotable as the evidence, and 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}")
heading = transcript_heading(LOOP_CLAUDE)
task, found_heading, shown = after_task.partition(heading)
+10 -2
View File
@@ -145,7 +145,7 @@ class Main(unittest.TestCase):
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(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, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, self.home, effects)
@@ -387,7 +387,7 @@ class JudgeArchivedRuns(unittest.TestCase):
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, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=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, LOOP_CLAUDE, effects)), cwds
@@ -403,6 +403,14 @@ class JudgeArchivedRuns(unittest.TestCase):
self.assertIsInstance(self.judged(evidence="Do it.")[0], Unfinished)
self.assertIsInstance(self.judged(evidence="Do it. ... Use Postgres.")[0], Unfinished)
def test_splits_the_prompt_into_the_premises_the_task_and_the_transcript_at_the_first_heading_of_each(self):
heading = transcript_heading(LOOP_CLAUDE)
again = self.PROMPT.replace("Worker chose option B.", f"Worker chose option B. {heading}Again.", 1)
for prompt in (self.PROMPT, again):
grounds = grounds_of(prompt, self.ENTRIES)
self.assertEqual((grounds.quotable, grounds.task), ("HEAD: Ship fast.", "Do it."))
self.assertEqual(grounds_of(self.PROMPT, self.ENTRIES).shown, "Worker chose option B.\n[human] Use Postgres.")
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))
+1 -1
View File
@@ -3,7 +3,7 @@ import typing
from larv_review.agreement import agreement_report
from review_rules.comprehension_history import appended, DIMENSIONS, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from larv_review.plan import checkout_plan, plan_reasons
from larv_review.scoring_due import checkout_plan, plan_reasons
from git_cli.git_repo import commit_exists
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure
+11 -14
View File
@@ -34,7 +34,7 @@ needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
a floor item, one whose tagline opens with `Reach the comprehension floor:`. It is also due when the
chunk leaves a release with no item in the project's todo.md, once the shipped items are set aside, and work has landed
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
towards that release; bin/larv_review/scoring_due.py's `work_landed` and `landed_towards` say when. A release the checkout's
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
A chunk is also due one while no scoring run in the default branch's history is newer than the
commit of its second-newest v* tag, so a release cut unmeasured is caught up by the next chunk. A project whose
@@ -91,8 +91,9 @@ prepare-scoring sets up a scoring run in the chunk's review folder: a detached w
checkout's HEAD, which the seats read, and one prompt file per seat beside it, as
skills/comprehension-panel/seat-prompts.md builds them. It prints the worktree's path and each
prompt's. It takes {{language}}, {{kind}}, {{domain}}, {{domain docs}} and {{3am question}} from the
checkout's AGENTS.md → "Scoring run". claude-config keeps no AGENTS.md, so there it takes them from
seat-prompts.md → "claude-config's values". It fills the other placeholders from the worktree and
project's working-rules file → "Scoring run", which is the checkout's AGENTS.md unless the config
names another. Where that file holds no such section, as in claude-config, it takes them from the
checkout's seat-prompts.md → "claude-config's values". It fills the other placeholders from the worktree and
the panel's SKILL.md. Where any one of the five values is missing, it exits 1 and doesn't write
anything. Where a setup that record-scoring never removed is still there, it removes it first and
says so.
@@ -170,8 +171,9 @@ import sys
import time
import typing
from git_cli.git_repo import branch_titles, default_branch, git, top
from larv_review.reviewer_header import branch_summaries, reviewer_header
from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
from git_cli.git_repo import default_branch, git, top
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from larv_review.history_changes import history_changes
@@ -181,12 +183,10 @@ from larv_review.ruling_base import measured_commit
from larv_review.agreement import MIN_PAIRS
from larv_review.owed import owed_scoring_run
from review_rules.review_passes import PASSES, REVIEWERS
from larv_review.plan import plan_reasons
from larv_review.scoring_due import plan_reasons
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.reviewer_header import reviewer_header
from larv_review.round_title import round_title
from project_config.main import title_templates
class Command(typing.NamedTuple):
@@ -320,13 +320,10 @@ def show_ruling_base(default: str, home: pathlib.Path) -> Failure | None:
def round_count(default: str) -> Failure | None:
titles = branch_titles(default)
if isinstance(titles, Failure):
return titles
templates = title_templates(None, pathlib.Path.home())
if isinstance(templates, Failure):
return templates
for name, count in round_counts([templates.summary(title) for title in titles]).items():
summaries = branch_summaries(default, pathlib.Path.home())
if isinstance(summaries, Failure):
return summaries
for name, count in round_counts(summaries).items():
print(f"{name}: {count}{cap_note(count, cap(name)) if name in PASSES else ', not a pass: check the commit title'}")
return None
+1 -1
View File
@@ -1,7 +1,7 @@
import pathlib
import typing
from larv_review.plan import Emptied, plan_reasons
from larv_review.scoring_due import Emptied, plan_reasons
from review_rules.comprehension_history import entries
from failure import Failure
from git_cli.git_repo import file_at, git
+9 -5
View File
@@ -80,15 +80,19 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure:
return done + 1
def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure:
"""Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun."""
def branch_summaries(default: str, home: pathlib.Path) -> list[str] | Failure:
"""The branch's commit titles since default, each read as its summary in the project's title templates, so round titles count under any template. rule-hook's round-cap reads them its own way: guarded, and counting zero rounds where git fails."""
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_)
return templates if isinstance(templates, Failure) else [templates.summary(title) for title in titles]
def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure:
"""Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun."""
summaries = branch_summaries(default, home)
round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_)
if isinstance(round_, Failure):
return round_
found = [top(), *(git(*args) for args in (["symbolic-ref", "--short", "HEAD"], ["rev-parse", "--short", "HEAD"], ["merge-base", "HEAD", default]))]
+4 -10
View File
@@ -1,23 +1,17 @@
"""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 larv_review.reviewer_header import branch_summaries, unanswered_round
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
from git_cli.git_repo import top
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_)
summaries = branch_summaries(default, home)
round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_)
if isinstance(round_, Failure):
return round_
worktree = top()
@@ -1,3 +1,5 @@
"""When the plan calls a scoring run: a chunk that ships a floor item, one that empties a release that work has already landed towards, or one after a release cut unmeasured; and each reason it gives."""
import pathlib
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown
+9 -4
View File
@@ -61,9 +61,12 @@ def score_bullets(skill: str) -> tuple[list[str], list[str]] | Failure:
return anchors, [line.replace("**", "") for _, line in dimensions]
VALUES_HEADING = r"(\d+\.\s+)?Scoring run|.+'s values"
def project_values(text: str, source: str) -> dict[str, str] | Failure:
"""Each value seat-prompts.md fills from the project, from the section of text, read from source, headed `Scoring run` or `<name>'s values`."""
lines = section(text, r"(\d+\.\s+)?Scoring run|.+'s values")
lines = section(text, VALUES_HEADING)
if lines is None:
return Failure(f"{source} has no \"Scoring run\" section to fill the seats' prompts from; add one with {listed([f'{{{name}}}' for name in VALUE_NAMES], 'and')}")
values = {}
@@ -137,13 +140,15 @@ def prepare_scoring(worktree: str, home: pathlib.Path, run: Git = git) -> str |
config = located(worktree, home, run)
if isinstance(config, Failure):
return config
# Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md.
source = config.paths["working-rules"]
if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file():
source = own
rules = read(source) if source.is_file() else ""
if isinstance(rules, Failure):
return rules
# This repo keeps the values in seat-prompts.md, so its working rules hold none: .claude/rules/this-repo-keeps-no-agents-md.md.
if section(rules, VALUES_HEADING) is None and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file():
source, rules = own, read(own)
if isinstance(rules, Failure):
return rules
skill = read(PANEL / "SKILL.md")
if isinstance(skill, Failure):
return skill
+1 -1
View File
@@ -15,7 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
from larv_review.history_commands import appended_to
from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from larv_review.scoring_due import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from review_rules import comprehension_history
from project_config.doubles import configured
from larv_review.ruling import counted, ruling, split, surplus, votes
+30
View File
@@ -165,6 +165,28 @@ class PrepareScoring(unittest.TestCase):
assert isinstance(ran, str), ran
self.assertIn("every non-test tracked file: `bin/**` and `README.md`. Do NOT open any record of a past panel, nor any review output.", pathlib.Path(ran.splitlines()[2]).read_text())
def test_takes_the_values_from_the_checkouts_seat_prompts_where_the_working_rules_hold_none(self):
own = self.checkout / "skills" / "comprehension-panel" / "seat-prompts.md"
own.parent.mkdir(parents=True)
own.write_text("# Seats\n\n## proj's values\n\n- Language: Go\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
for rules in ("# Working rules, with no values\n", None):
with self.subTest(rules=rules):
(self.checkout / "AGENTS.md").unlink(missing_ok=True)
self.commit(rules)
ran = self.prepare()
assert isinstance(ran, str), ran
self.assertIn("Your background: ~2 years in Go, first codebase of this kind (a CLI)", pathlib.Path(ran.splitlines()[2]).read_text())
self.assertIsNone(removed_setup(str(self.checkout), self.root, functools.partial(git, env=self.env)))
def test_keeps_the_working_rules_values_where_the_checkout_has_seat_prompts_too(self):
own = self.checkout / "skills" / "comprehension-panel" / "seat-prompts.md"
own.parent.mkdir(parents=True)
own.write_text("## proj's values\n\n- Language: Go\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
self.commit("## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
ran = self.prepare()
assert isinstance(ran, str), ran
self.assertIn("Your background: ~2 years in Python,", pathlib.Path(ran.splitlines()[2]).read_text())
def test_refuses_writing_nothing_where_the_project_gives_no_values(self):
self.commit()
ran = self.run_tool("prepare-scoring")
@@ -181,6 +203,14 @@ class PrepareScoring(unittest.TestCase):
assert isinstance(unread, Failure), unread
self.assertTrue(unread.reason.startswith(f"cannot read {self.checkout}/AGENTS.md: "), unread.reason)
self.assertEqual(len(self.git("worktree", "list").splitlines()), 1)
own = self.checkout / "skills" / "comprehension-panel" / "seat-prompts.md"
own.parent.mkdir(parents=True)
own.write_bytes(b"\xff")
(self.checkout / "AGENTS.md").write_text("# Working rules, with no values\n")
unread = self.prepare()
assert isinstance(unread, Failure), unread
self.assertTrue(unread.reason.startswith(f"cannot read {own}: "), unread.reason)
self.assertEqual(len(self.git("worktree", "list").splitlines()), 1)
if __name__ == "__main__":
+1 -1
View File
@@ -49,7 +49,7 @@ def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
if announce and config.tracked("plan") is None:
say(UNSEEN_RELEASES, loop.effects)
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git)
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git, loop.effects.forge(loop.root))
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
+17 -6
View File
@@ -76,6 +76,12 @@ def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: i
return Room(running, stopped, restart, room - len(restart))
@dataclasses.dataclass(frozen=True)
class AwaitedMerges:
"""Why no chunk starts and none runs: every item left awaits a person's merge of the pull requests that why names."""
why: str
def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]:
"""The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone."""
if isinstance(plan, NoItem):
@@ -104,12 +110,12 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | No
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
if isinstance(ref, Failure):
return ref
held = project_plan(config, ref, root, effects.git)
held = project_plan(config, ref, root, effects.git, effects.forge(root))
return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure:
"""Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. A Failure says why no chunk may start, or why one could not; those before it run."""
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | AwaitedMerges | Failure:
"""Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run."""
config = located(loop_run.root, paths.home)
if isinstance(config, Failure):
return config
@@ -122,6 +128,8 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map
if refused := refusal(session, windows, loop_run.root, effects.tmux):
return refused
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects)
if isinstance(chunks, AwaitedMerges):
return chunks
for chunk in chunks:
started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux)
if isinstance(started, Failure):
@@ -139,8 +147,8 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux)
return None
def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str]:
"""The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does."""
def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges:
"""The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge."""
room = room_of(windows, loop_run.chunk, leaving, limit)
if not room.left:
return room.restart
@@ -150,7 +158,10 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
plan = NoItem(plan.reason)
held = held_items(room.running + room.stopped, project_key(loop_run.root, paths.home), paths.claude_code_transcripts)
return room.restart + [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.stopped]
if isinstance(plan, NoItem) and plan.awaits_merge and not room.running + room.restart:
return AwaitedMerges(plan.why)
picked = may_start(plan, room.running + room.restart, held, room.left)
return room.restart + [chunk for chunk in picked if chunk not in room.stopped]
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
+6 -2
View File
@@ -4,11 +4,11 @@ import typing
from chunk_driver.cycle_start import announced_route, cycle_of, project_routing
from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.chunk_windows import AwaitedMerges, chunk_session, item_of, start_chunks
from loop_claude.loop.routing_check import check_routing
from loop_claude.loop.checkout import checkout_root
from chunk_driver.claims import CHUNK_FLAG, loop_session
from loop_claude.chunk import chunk_items, fresh_prompt
from loop_claude.loop.chunk_windows import chunk_session, item_of, start_chunks
from loop_claude.loop.chunk_start import chunk_start, plan_item, scored_plan
from chunk_driver.chunk_run import closed_cycle
from agent_cycle.run import Concluded, Cycle, run_cycle
@@ -30,7 +30,7 @@ from agent_cycle import tmux
# Starts the chunks that may start now, as chunk_windows.start_chunks does.
StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | Failure]
StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | AwaitedMerges | Failure]
@dataclasses.dataclass(frozen=True)
@@ -107,6 +107,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, start: StartChunks) -> Stop:
"""What the loop-claude the human runs does: starts, through start, each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
started = start(loop_run, False, paths, env, launcher, effects)
if isinstance(started, AwaitedMerges):
return Stop(0, started.why)
if isinstance(started, Failure):
return Stop(1, started.reason)
session = loop_session(loop_run.root, paths.home)
@@ -121,6 +123,8 @@ def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Path
def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop:
"""The stop of a loop whose chunk finished, once it has started, through start, each chunk that may start now. Its window closes as it exits."""
started = start(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
if isinstance(started, AwaitedMerges):
return Stop(0, f"the chunk finished; {started.why}")
if isinstance(started, Failure):
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True)
+35 -9
View File
@@ -9,7 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from chunk_driver.doubles import a_loop
from loop_claude.loop import chunk_start
from loop_claude.loop import chunk_start, chunk_windows, reload
from project_config.doubles import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from failure import Failure
@@ -21,6 +21,9 @@ from plan_store.todo_md import plan_of
from claude_code import session
from agent_cycle import tmux
# What git answers as `default_ref` reads the default branch in a checkout on main: the remote, the branch checked out, no chunk base, and origin's default branch.
ON_MAIN = ["origin\n", "main\n", Failure("no chunk base"), "origin/main\n"]
class RouteSources(unittest.TestCase):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
@@ -43,9 +46,9 @@ class RouteSources(unittest.TestCase):
opened = session.session_named("A proj loop-claude", pathlib.Path(root, "projects"))
transcript = pathlib.Path(root, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text("")
transcript.write_text("{}\n")
unread = Failure("no git")
fake = FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread])
fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread])
with contextlib.redirect_stderr(io.StringIO()) as stderr:
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1])))
self.assertEqual((facts, held.plan), ("", plan_of(TODO)))
@@ -70,7 +73,7 @@ class RouteSources(unittest.TestCase):
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
def git(*args, **options):
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "show": f"what {args[-1]} holds\n"}
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "config": Failure("no chunk base"), "show": f"what {args[-1]} holds\n"}
return answers.get(args[0], "1\n")
with tempfile.TemporaryDirectory() as root:
@@ -79,24 +82,47 @@ class RouteSources(unittest.TestCase):
held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1])))
self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n")
def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_as_the_loops_forge_lists_them(self):
head = "a" * 40
finished = TODO.replace("| 3 | 0.2.0 | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n", "")
def git(*args, **options):
if args[:2] == ("remote", "get-url"):
return "https://github.com/o/r\n"
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "merge-base": "base\n", "show": finished if args[-1] == f"{head}:todo.md" else TODO}
return answers.get(args[0], "1\n")
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
(folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n')
fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 3)
held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1])))
self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")])
self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"])
self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk")
window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git))
self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick")
stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git))
self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on")
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self):
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
loop = a_loop(FakeEffects(git=["origin\n", "origin/main\n"] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
config = folder / "config.toml"
tracked = a_loop(FakeEffects(git=["origin\n", "origin/main\n", *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(tracked)
self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release")
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(TODO)
unread = Failure("no git")
standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
held = chunk_start.fetched_plan(standing)
self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently")
quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(quiet, announce=False)
self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts")
@@ -150,7 +176,7 @@ class ChunkFacts(unittest.TestCase):
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True))
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text("")
transcript.write_text("{}\n")
resumed = FakeEffects()
facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER))
self.assertEqual((resumed.made("python"), facts), ([], ""))
+4 -2
View File
@@ -11,10 +11,10 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from chunk_driver.doubles import a_loop
from loop_claude.loop import chunk_windows, main, reload, usage
from loop_effects.doubles import CWD, FakeEffects, ran, STAMP
from failure import Failure
from agent_cycle.verdicts import Finished, Unfinished
from loop_claude.loop import main, reload, usage
from loop_claude.doubles import OPUS_PROJECT
from loop_state import paths
from model_routing.route import Route
@@ -240,6 +240,7 @@ class WindowStarts(unittest.TestCase):
def test_stops_where_no_chunk_could_start(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan"))
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=chunk_windows.AwaitedMerges("#7 awaits a merge."))[0], Stop(0, "#7 awaits a merge."), "nothing failed, so the stop exits 0")
def test_stops_where_tmux_cannot_show_the_session(self):
fake = FakeEffects(git=["/r\n"])
@@ -260,7 +261,8 @@ class WindowStarts(unittest.TestCase):
def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self):
loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7")
for started, said, stop in ((["item-9", "item-12"], "the chunk finished; started item-9, item-12", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")),
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan"))):
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan")),
(chunk_windows.AwaitedMerges("#7 awaits a merge."), "", Stop(0, "the chunk finished; #7 awaits a merge."))):
with self.subTest(started=started), contextlib.redirect_stdout(io.StringIO()) as printed:
loop, asked = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"}), []
self.assertEqual(main.handed_on(loop_run, loop, lambda *args: asked.append(args) or started), stop)
+3 -2
View File
@@ -99,8 +99,9 @@ class JudgeFailures(unittest.TestCase):
("verdict_from", "'the judge interrupted without a question'", unasked),
("verdict_from", "'the judge quoted an answer without a question'", unasked),
("run_judge", "verdict.reason", field),
("run_judge", "checked.reason", "quotes a passage the transcript does not hold"),
("misquoted_evidence", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
("run_judge", "checked.reason", "quotes a passage that neither the task nor the transcript holds"),
("misquoted_evidence", "f'the judge quoted {verdict.evidence!r}, which is not in the task or the transcript", "quotes a passage that neither the task nor the transcript holds"),
("judge_prompt", "f\"the premises, the records, the task and the judge's rules leave", f"leave room for less than the last {judge.TRANSCRIPT_FLOOR:,} characters of the transcript, or all of a shorter one"),
("claude_reply", "f'could not start claude:", started),
("claude_reply", "proc.stderr.strip() or f'{who} exited", exited),
("claude_reply", 'f"{who} printed no json reply', unparsed),

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