Compare commits

..

90 Commits

Author SHA1 Message Date
lilleman 3c85562bb9 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); the entry says what OTLP is and sends, the archive traces each cycle, and both lists keep their order
CI / tests (pull_request) Successful in 3m5s
2026-11-16 21:25:46 +01:00
lilleman 242f87a9b3 Record that the tools send no OTLP traces, logs or metrics, and loop-claude's archive is the trace of each cycle
CI / tests (pull_request) Successful in 3m7s
2026-11-16 21:23:54 +01:00
lilleman 8d24f73971 Record the comprehension check: paired ruling better at 31da587 against 64454f8, both seats voting better overall
CI / tests (pull_request) Successful in 3m8s
2026-11-16 16:57:45 +01:00
lilleman 2fc9f7212c Point Gathered.plan and CarriedOver at where plan_name and the moved items live now, and name next_chunk.py in the README 2026-11-16 16:57:25 +01:00
lilleman 31da587415 Answer stability round 1: 0 🔴, 14 🟡 (0 misread); tests that kill the surviving mutants, with a versioned MemoryStore and appended_to, plan/named_paths.py, TakenIn's docstring and the run-heavy rule naming LAUNCHERS; three places left to item 300
CI / tests (pull_request) Successful in 3m10s
2026-11-16 16:53:36 +01:00
lilleman 79e0f755e2 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the changelog says what the wider run-heavy rule refuses and that loop-claude's prompts say plan, a bad value in a Jira issue's property names the property, and a Jira edit's refusal names the issue 2026-11-16 16:48:05 +01:00
lilleman fde2718a97 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); each 🟡 and 🟢 rewritten as the report asks, items 392 and 393 included, and item 300's quoted places left for its next refresh 2026-11-16 16:48:04 +01:00
lilleman a06a6dec22 Say in project-record's help that a save refuses after a teammate's save since the last save too
CI / tests (pull_request) Successful in 2m45s
2026-11-16 16:24:06 +01:00
lilleman 8deef3b4ac Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the todo-rank-check override on ba21a1ef stands, and those on two empty commits are moot 2026-11-16 16:23:45 +01:00
lilleman ba0356adae Answer principles round 2: 0 🔴, 1 🟡 (0 misread); start_window fails only where it cannot mark a new session as the checkout's, so a started chunk never reads as one that didn't start 2026-11-16 16:23:45 +01:00
lilleman a7a6640ea1 Answer architecture round 3: 0 🔴, 2 🟡 (0 misread); a record write names its version, even None, in every backend, and the unreleased section is read through markdown_text.section by one title pattern 2026-11-16 16:17:12 +01:00
lilleman 50ce373c40 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); both todo-rank-check overrides stand
CI / tests (pull_request) Successful in 2m44s
2026-11-16 16:12:36 +01:00
lilleman fda61ac06e Answer security round 1: 0 🔴, 0 🟡 (0 misread); security-review found nothing, and the full scan could not run in a subagent 2026-11-16 16:12:36 +01:00
lilleman ba21a1efcd Answer principles round 1: 2 🔴, 9 🟡 (0 misread); explicit record versions in place of the Confluence store's hidden state, the routing ruling filed as item 393 for 0.12.0, rule-hook catching heavy runs through uv, poetry, sudo and doas, one unreleased heading, one owner of the no-item message, typed Jira issues, a turn that gives its failure as a value, outcome tests for the Atlassian client, an Emptied reason type, an injected clock and git in touch-predictions, and paired record names 2026-11-16 16:12:36 +01:00
lilleman a60bfdbc1c Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); the answer destinations and the help say the plan, and the notice of releases a plan outside the checkout hides prints once per chunk 2026-11-16 14:54:27 +01:00
lilleman f58250d0ce Answer architecture round 1: 4 🔴, 5 🟡 (0 misread); one-way plan packages with a plan core and an Atlassian client, one parse and print of an item's cells, a pure chunk-start decision, a settings table, one plan read and one standing per pick, one config load in chunk-pr, notifier backends in notifier, and the bin regroup filed as item 392 2026-11-16 14:47:46 +01:00
lilleman 3f7d85c48e Release review of 0.11.0
CI / tests (pull_request) Successful in 2m47s
2026-11-16 13:55:47 +01:00
lilleman 64454f86a8 Merge remote-tracking branch 'origin/main' into adf-lossless
CI / tests (pull_request) Successful in 2m48s
# Conflicts:
#	todo.md
2026-11-16 13:32:34 +01:00
lilleman b62dea42fc Answer stability round 1: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Successful in 1m46s
2026-11-16 13:16:54 +01:00
lilleman d01d0d421e Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the todo-rank-check override on finishing item 375 stands
CI / tests (pull_request) Successful in 2m56s
2026-11-16 13:16:54 +01:00
lilleman f2b7eb7fd2 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); say each pair's use once in the module docstring, name what the changelog entry keeps, and make item 391 stand alone 2026-11-16 13:16:50 +01:00
lilleman a921b08207 Finish item 375
CI / tests (pull_request) Successful in 2m54s
2026-11-16 13:16:19 +01:00
lilleman e2c4e94cb2 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the todo-rank-check override stands
CI / tests (pull_request) Successful in 2m57s
2026-11-16 13:15:32 +01:00
lilleman 251b0e8f02 Record the comprehension check: two scoring runs at 55235a0, overall 6.50 each, and refresh floor item 300
CI / tests (pull_request) Successful in 2m58s
2026-11-16 13:14:42 +01:00
lilleman bac9cf9756 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override stands 2026-11-16 13:08:38 +01:00
lilleman 880d0c6342 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-16 13:08:38 +01:00
lilleman 068ab77ce3 Record reading cost 2026-11-16 13:07:39 +01:00
lilleman 4985e6a2a9 Convert ADF to markdown and back through adf-codec's lossless pair
CI / tests (pull_request) Successful in 1m47s
2026-11-16 13:07:30 +01:00
lilleman 55235a07d8 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); no finding
CI / tests (pull_request) Successful in 2m56s
2026-11-16 13:05:18 +01:00
lilleman 96e1b364f1 Clamp the room for new chunks at 0, and test the held-items wording and the session option's target 2026-11-16 12:55:17 +01:00
lilleman 30b0e9e0a7 Target the tmux session as =<session>: for its @loop-root option, which set-option and show-options read as a pane's target
CI / tests (pull_request) Successful in 2m57s
2026-11-16 12:47:28 +01:00
lilleman 255d5f7bb1 Answer prose round 1: 0 🔴, 12 🟡 (0 misread); name the tmux and claude sessions apart, say parallel-chunks is a most, and put the fakes and keywords in order 2026-11-16 12:46:08 +01:00
lilleman 986697ab52 Answer product-owner round 1: 0 🔴, 4 🟡 (0 misread); leave a stopped chunk to the human, name the task that didn't start, refuse another checkout's session and ask to stop old loops before upgrading 2026-11-16 12:46:07 +01:00
lilleman fa9d487afd Answer stability round 1: 1 🔴, 4 🟡 (0 misread); check a new chunk's Touches against every held item, keep a stopped chunk's items, test the fetch and fold the slot loop back 2026-11-16 12:46:07 +01:00
lilleman fbd1b5e99d Check what start_chunks hands next_plan and tmux, keep other chunks' dead windows, and drop item_of's redundant re.ASCII 2026-11-16 12:20:43 +01:00
lilleman f3eaf19f62 Test the window loop, the window starts, --item and the tmux effects in process; drop the Ctrl-C check every stop's reason already makes 2026-11-16 12:12:18 +01:00
lilleman 4e02971bfe Sort the added imports and type the parallel-chunks value for mypy 2026-11-16 12:02:41 +01:00
lilleman 3fd7e15255 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-16 12:00:57 +01:00
lilleman 2de1e7e74e Cite no open item in the tmux windows decision 2026-11-16 12:00:15 +01:00
lilleman eecb0387ca Run each chunk in its own tmux window, up to parallel-chunks at once, and mark a window that waits
CI / tests (pull_request) Failing after 2m56s
2026-11-16 11:59:45 +01:00
lilleman 7fc64d860a Finish item 384
CI / tests (pull_request) Successful in 2m7s
2026-11-16 03:08:52 +01:00
lilleman 00c1dd2480 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); say who made each call, split the README paragraph and correct the rank's help
CI / tests (pull_request) Successful in 3m10s
2026-11-16 03:07:39 +01:00
lilleman f768ef3272 Answer product-owner round 1: 0 🔴, 2 🟡 (1 misread); rank a question first, as todo.md does, and parse the formula on load 2026-11-16 03:07:39 +01:00
lilleman cf1180734c Answer stability round 1: 0 🔴, 7 🟡 (0 misread); parse the formula on load, require the scoring, share the bar rule and split add 2026-11-16 03:07:39 +01:00
lilleman 727ed70ecb Kill the surviving mutants of the scoring and ranking 2026-11-16 02:50:37 +01:00
lilleman 9d9c5a3352 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-16 02:42:27 +01:00
lilleman 2db4759c2a Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first
CI / tests (pull_request) Successful in 2m8s
2026-11-16 02:41:43 +01:00
lilleman 9d685c52b3 Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the second override of the rank check is accepted
CI / tests (pull_request) Successful in 1m44s
2026-11-16 02:17:16 +01:00
lilleman c56b3166a0 Finish item 382
CI / tests (pull_request) Successful in 1m48s
2026-11-16 02:15:54 +01:00
lilleman b6a53ef98b Answer prose round 1: 0 🔴, 7 🟡 (0 misread); say what an edit of a person's issue writes 2026-11-16 02:15:39 +01:00
lilleman c46a117088 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); set the four scores together, and say the comment tells the team the issue is scored 2026-11-16 02:15:39 +01:00
lilleman 121aba05ea Answer stability round 1: 0 🔴, 2 🟡 (0 misread); keep the comment in the fake plan, and name move among the writes Jira may have taken 2026-11-16 02:15:39 +01:00
lilleman eb5a63edd2 Test an edit of the release with the tagline, and an empty tagline 2026-11-16 02:03:32 +01:00
lilleman 2707cfc04e Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted 2026-11-16 01:57:06 +01:00
lilleman 53a54e50dd Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-16 01:57:06 +01:00
lilleman 2e9d9dd714 Edit a Jira issue the loop filed, and score a teammate's with a comment saying why
CI / tests (pull_request) Successful in 1m48s
2026-11-16 01:55:57 +01:00
lilleman 0681e9be17 Answer prose round 1: 0 🔴, 1 🟡 (0 misread); say the choice in one line
CI / tests (pull_request) Successful in 1m56s
2026-11-16 01:44:30 +01:00
lilleman 2fdc75d035 Record that the loop reads no other mark of a cut release yet
CI / tests (pull_request) Successful in 1m55s
2026-11-16 01:43:26 +01:00
lilleman bad76b07c8 Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); both overrides of the rank check are accepted
CI / tests (pull_request) Successful in 1m57s
2026-11-16 01:33:15 +01:00
lilleman 9dd8441f3b Finish item 359
CI / tests (pull_request) Successful in 1m57s
2026-11-16 01:32:41 +01:00
lilleman 1210f8cd68 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); name no cut release in the move line
CI / tests (pull_request) Successful in 1m56s
2026-11-16 01:26:49 +01:00
lilleman 0f0ba7fa43 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); say what to do in a Jira plan 2026-11-16 01:26:49 +01:00
lilleman 37078cffa9 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); carry into a release named since the cut 2026-11-16 01:26:49 +01:00
lilleman 30129051ad Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-16 01:15:54 +01:00
lilleman 58055f0fac Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted 2026-11-16 01:15:23 +01:00
lilleman 55ad029df2 Test the singular and plural move lines
CI / tests (pull_request) Successful in 2m2s
2026-11-16 01:14:47 +01:00
lilleman b89ac805d3 Route on a cut release's carried item
CI / tests (pull_request) Successful in 1m58s
2026-11-16 01:08:13 +01:00
lilleman 8b649682dc Count a cut release's open items as the next release's 2026-11-16 01:05:47 +01:00
lilleman 4447e89e48 Reword item 359: releases stay semver, and the loop keeps working when someone else cuts one 2026-11-16 00:59:20 +01:00
lilleman 3c522160c9 Re-score item 359 at L 4, S 7 2026-11-15 23:44:52 +01:00
lilleman 39bf6e6d94 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted
CI / tests (pull_request) Successful in 2m22s
2026-11-15 23:38:03 +01:00
lilleman 0339a515fc Finish item 386 2026-11-15 23:37:09 +01:00
lilleman 75c3c581ef Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Successful in 2m8s
2026-11-15 23:36:33 +01:00
lilleman cca16e702a Make the open test tell the injected git from the real one 2026-11-15 23:26:27 +01:00
lilleman 36d9ddb6f5 Test the pruning on open and kill its surviving mutants 2026-11-15 23:17:22 +01:00
lilleman dbc8cfe854 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); the help, the docstrings and the test name reworded in the previous commit 2026-11-15 23:06:50 +01:00
lilleman fffba3d454 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); prune the copies of removed worktrees 2026-11-15 23:06:50 +01:00
lilleman 2695e9b530 Pin the worktree folder's name in a test 2026-11-15 22:54:09 +01:00
lilleman 4873ee9e74 Key project-record's copies per worktree
CI / tests (pull_request) Successful in 2m8s
2026-11-15 22:45:04 +01:00
lilleman 70e3c0b9de Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted
CI / tests (pull_request) Successful in 2m24s
2026-11-15 22:28:08 +01:00
lilleman 93a4da0728 Record the comprehension check: a scoring run at bcb04e3, overall 6.00; refresh floor item 300
CI / tests (pull_request) Successful in 2m23s
2026-11-15 22:27:10 +01:00
lilleman bcb04e32d4 Finish item 374 in the plan, and record lilleman's answer on the paired ruling's base
CI / tests (pull_request) Successful in 2m35s
2026-11-15 22:19:02 +01:00
lilleman 37fcedc5bf Merge remote-tracking branch 'origin/main' into item-374
CI / tests (pull_request) Successful in 2m44s
2026-11-15 22:11:23 +01:00
lilleman e18555be3e Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); the base of a rerun paired ruling is asked of lilleman
CI / tests (pull_request) Successful in 2m25s
2026-11-15 22:11:22 +01:00
lilleman 2136413dd6 Answer stability round 2: 0 🔴, 4 🟡 (0 misread); each survivor it named has a test that kills it 2026-11-15 22:11:22 +01:00
lilleman e37518db29 Answer prose round 1: 0 🔴, 11 🟡 (0 misread); the help lists merge's steps and stops, and the decision says where it differs from the call
CI / tests (pull_request) Successful in 2m45s
2026-11-15 21:56:11 +01:00
lilleman 9e0a6d4d7b Answer product-owner round 1: 1 🔴, 5 🟡 (1 misread); an absent item is named, an approved pull request answers its comments first, and todo-item keeps its own checks 2026-11-15 21:56:11 +01:00
lilleman aff46cd64e Answer stability round 1: 2 🔴, 8 🟡 (1 misread); the scoring-run gate follows the finish, a rerun commits what a finish left, and the queue wait ends after 30 minutes 2026-11-15 21:56:11 +01:00
lilleman 0109f97cd7 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing reported
CI / tests (pull_request) Successful in 2m8s
2026-11-15 21:34:51 +01:00
lilleman 85f3b74d4f Merge a project's chunks one at a time, finishing each one's plan items in its turn
CI / tests (pull_request) Successful in 2m9s
2026-11-15 21:33:36 +01:00
139 changed files with 4793 additions and 1610 deletions
+4 -4
View File
@@ -30,6 +30,8 @@
!bin/adf_codec/node_shim/package-lock.json
!bin/adf_codec/node_shim/package.json
!bin/adf_codec/node_shim/shim.mjs
!bin/atlassian/
!bin/atlassian/*.py
!bin/branch_chunks/
!bin/branch_chunks/*.py
!bin/chunk-pr
@@ -67,8 +69,6 @@
!bin/loop_state/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/mattermost_dm/
!bin/mattermost_dm/*.py
!bin/metric-bench
!bin/metric_bench/
!bin/metric_bench/*.py
@@ -81,6 +81,8 @@
!bin/notifier/
!bin/notifier/*.py
!bin/notify
!bin/plan/
!bin/plan/*.py
!bin/plan_store/
!bin/plan_store/*.py
!bin/project-config
@@ -126,8 +128,6 @@
!bin/score_outcomes/*.py
!bin/settings_filter.py
!bin/setup.cfg
!bin/slack_dm/
!bin/slack_dm/*.py
!bin/statusline.py
!bin/subagent-rung
!bin/subagent_rung/
+9 -2
View File
@@ -2,13 +2,19 @@
## Unreleased
- Two loop-claude runs in one project now work side by side, each on its own chunk. Each loop holds a slot of the project, a locked file under `~/.local/state/loop-claude/<key>/`, and names its session after it: the first loop's session keeps its name, `A <key> loop-claude`, and the second's is `A <key> loop-claude 2`. A rerun resumes a chunk left open first. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`.
- `adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet.
- A config whose `plan` names a Jira epic must now set `jira-score-formula` and `jira-score-bar`, and fails to load without them. `todo-item add` scores the item by them, refuses one under the bar unless it is exempt, and ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep their rank.
- `todo-item edit` and `move` work on a plan kept in a Jira epic. They change only an issue the loop filed, and never a link. Of an issue a person filed, `edit` sets only the scores, and posts the new `--comment` on the issue to tell the team why; a plan in a file takes the flag and keeps no comment.
- A release someone else cut while it still held plan items no longer stops the loop: those items count as the next release's, `chunk-preflight` tells the worker to move them there, and `loop-claude` routes on them. Where the plan names no later release and `todo.md` named none since the cut, the loop still asks which release they belong to.
- `project-record open` now writes the copy of a record kept outside a file under a folder of the worktree that ran it, `~/.local/state/project-record/<key>/<worktree>/`, so two chunks of one project no longer overwrite each other's unsaved edit. It also removes the folders of worktrees git no longer lists.
- `chunk-pr merge` merges the chunks of one project on a machine one at a time, and `--finish <ID>` finishes each plan item in the chunk's turn, so `todo.md` and `CHANGELOG.md` no longer conflict between open chunks. A pull request that waits for an approval leaves the queue while it waits, and merge stops where a reviewer's comment waits for an answer.
- `loop-claude` runs each chunk in its own window of one tmux session per project, `loop-<key>`, and needs tmux 3.2 or later. Up to the config's new optional `parallel-chunks` chunks run at once, 1 by default; a chunk starts beside the others only where its item's `Touches:` prediction overlaps none of theirs. `loop-claude <task>` starts the windows and attaches to the session, and as a chunk finishes, its loop starts the next. A window whose chunk waits for you ends its name in ` ?` and rings the bell, and the question's DM names the window. A stopped chunk keeps its window and its items until you run `loop-claude <task>` again. A chunk's claude session is named after its window, as `A <key> loop-claude item-372`. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`. To upgrade, finish or stop every running loop-claude before `deploy-release` moves `~/.claude` to this release: a loop that reloads into it starts its project's windows afresh, and leaves its chunk's open claude session in the session picker.
- `todo-item finish` finishes an item of a plan kept in a Jira epic: it moves the item's issue by the workflow transition, and to the status, that the config's new optional settings `jira-finish-transition` and `jira-finish-status` name, both as Jira shows them. 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.
- Reviewers and loop-claude's judge read the review standards from the folder a project's config sets as `standards`, in place of `~/.claude/skills/larv-review/standards/`. The setting is required. To upgrade, add `standards = "~/.claude/skills/larv-review/standards"` to every config under `~/.claude-projects/` right after `deploy-release` moves `~/.claude` to this release, and not before.
- A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you.
- `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira.
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- CLAUDE.md, the todo-items rule, and loop-claude's worker and judge prompts and `--help` define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
- A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host.
- A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out.
@@ -24,6 +30,7 @@
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link.
- rule-hook's `run-heavy` rule also refuses a heavy command run through `uv run`, `poetry run`, `sudo` or `doas` outside `run-heavy`, such as `uv run mutmut run` or `sudo docker build`. Run it as `~/.claude/bin/run-heavy uv run mutmut run`.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
+4 -3
View File
@@ -6,9 +6,10 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **Until the goals file has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
- **Keep a plan in `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file, and there it files and finishes an item but doesn't edit or move one yet. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file. There it edits and moves only an issue the loop filed; of an issue a person filed it sets only the scores, with `--comment` telling the team why. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
- **Where someone cut a release that still holds items, those items are the next release's.** Move them there as the chunk's first change and say so in its opening line; where `todo-item` cannot move an item, such as an issue a person filed in a Jira plan, ask the human in the chunk's summary to move it. Where the plan names no later release, ask the human which one they belong to.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
- **Read the goals file's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
@@ -17,7 +18,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in the goals file, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the goals file, and record as a choice only what the goal leaves open.
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the goals file's `## Audience`, picks it.
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding.
- **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item.
- **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5).
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
- **Open each plan item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and doesn't say anything about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
@@ -138,7 +139,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's goals file, with code health ("Shared goal") first among the goals unless the goals file voids it.
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
- **project record** — one of five documents a project keeps beside its plan, each where its config names it: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`.
- **release** — a semver version the human cuts.
- **release** — a semver version the human cuts, or in a client's project someone on its team.
- **release review** — a release's last chunk: the architecture and principles passes over the whole project, before the release is ready to cut; `larv-review` §3 → "Release review".
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
+19 -13
View File
@@ -71,7 +71,7 @@ git config filter.settings.clean bin/settings_filter.py
Then pick a model with `/model`.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. loop-claude runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later.
To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
@@ -105,13 +105,13 @@ A project may also set `notifier` to `"mattermost"` or `"slack"`, the service th
A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer <pass> round <n>:`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault.
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item.
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item. To let more than one chunk run at once, set `parallel-chunks` to the most that may; left out, it is 1. Beside the plan's next item, only items whose `Touches:` predictions overlap none of the running chunks' items start.
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. 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 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.
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.
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets, apart from the rank `todo-item add` gives an issue it files. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
- The ID is the issue's number, so every child must be in the epic's own Jira project.
- The tagline is the summary.
@@ -120,7 +120,11 @@ A client that plans in Jira Cloud names an epic as its project's plan: `plan = "
- A blocker is an "is blocked by" link to another open child.
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
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, and doesn't edit an issue yet. `todo-item edit` and `move` fail, so edit its issues in Jira. 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. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
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.
`todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do every issue's links. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
@@ -164,13 +168,13 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
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`.
- `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; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks; once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
- `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.
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one.
@@ -190,12 +194,13 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
@@ -204,13 +209,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop_state/` holds where loop-claude keeps its 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`, 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`; `mattermost_dm/` and `slack_dm/` are its two backends.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`) and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` a plan in memory.
- `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/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
- `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`.
- `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 `mattermost_dm`, `slack_dm`, `plan_store` and `record_store`.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
+40 -10
View File
@@ -1,6 +1,10 @@
"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back.
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
adf-codec has two pairs of calls, and each function here names the one it runs:
- The lossless pair, `*_lossless`, for a document that already exists in Jira or Confluence and is edited and saved back. It keeps each block's localId and the empty paragraphs Jira uses for spacing, so a document read and saved unedited comes back identical.
- The portable pair, with no suffix, for new text written from scratch, and for markdown shown to a person. It drops the localId and the empty paragraphs, so saving a document that exists changes it.
"""
import contextlib
import dataclasses
@@ -31,7 +35,7 @@ class Ran:
err: str
# Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to run it.
# Runs the shim in the given mode (`to-adf`, `to-markdown`, `to-adf-lossless` or `to-markdown-lossless`) on a text, or fails to run it.
Run = typing.Callable[[str, str], Ran | Failure]
# Runs a docker command line on a text, in at most the given seconds, or fails to run it.
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
@@ -149,9 +153,8 @@ def refusal(out: str) -> Refused | Failure:
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown."""
out = answer("to-adf", markdown, run)
def to_adf(mode: str, markdown: str, run: Run) -> dict[str, typing.Any] | Failure:
out = answer(mode, markdown, run)
if isinstance(out, Refused):
return out.failure
if isinstance(out, Failure):
@@ -163,11 +166,10 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing
return document
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start."""
def to_markdowns(mode: str, documents: list[dict[str, typing.Any]], run: Run) -> list[str] | Refused | Failure:
if not documents:
return []
out = answer("to-markdown", json.dumps(documents), run)
out = answer(mode, json.dumps(documents), run)
if isinstance(out, Refused) and not 0 <= out.index < len(documents):
return Failure(f"the adf-codec shim refused a document at index {out.index}, past the {len(documents)} it was handed")
if isinstance(out, Refused | Failure):
@@ -181,9 +183,37 @@ def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = containe
return texts
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document."""
texts = adfs_to_markdown([document], run)
def one_markdown(texts: list[str] | Refused | Failure) -> str | Failure:
if isinstance(texts, Refused):
return texts.failure
return texts if isinstance(texts, Failure) else texts[0]
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown, by the portable pair."""
return to_adf("to-adf", markdown, run)
def markdown_to_adf_lossless(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown, by the lossless pair."""
return to_adf("to-adf-lossless", markdown, run)
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, by the portable pair, from one container run, so a caller with many documents pays one container start."""
return to_markdowns("to-markdown", documents, run)
def adfs_to_markdown_lossless(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, by the lossless pair, from one container run."""
return to_markdowns("to-markdown-lossless", documents, run)
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document, by the portable pair."""
return one_markdown(adfs_to_markdown([document], run))
def adf_to_markdown_lossless(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document, by the lossless pair."""
return one_markdown(adfs_to_markdown_lossless([document], run))
+12 -9
View File
@@ -1,10 +1,11 @@
// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument:
// Converts between markdown and ADF with @larvit/adf-codec. The mode is the one argument:
// to-adf stdin is markdown, stdout is the ADF document as JSON
// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order
// to-adf-lossless, to-markdown-lossless the same, through adf-codec's lossless pair in place of its portable pair
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}},
// with "index", the refused document's place in the array, beside "error" in to-markdown.
// Exit 1: the shim could not run, and stderr says why.
import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec'
import { adfToLosslessMarkdown, adfToPortableMarkdown, losslessMarkdownToAdf, portableMarkdownToAdf } from '@larvit/adf-codec'
const REFUSED = 2
@@ -19,17 +20,17 @@ function refuse(refusal) {
return REFUSED
}
function toAdf(markdown) {
const result = portableMarkdownToAdf(markdown)
function toAdf(convert, markdown) {
const result = convert(markdown)
if (!result.ok) return refuse({ error: result.error })
process.stdout.write(JSON.stringify(result.value))
return 0
}
function toMarkdown(documents) {
function toMarkdown(convert, documents) {
const texts = []
for (const [index, document] of documents.entries()) {
const result = adfToPortableMarkdown(document)
const result = convert(document)
if (!result.ok) return refuse({ index, error: result.error })
texts.push(result.value)
}
@@ -39,9 +40,11 @@ function toMarkdown(documents) {
async function main(mode) {
const input = await readStdin()
if (mode === 'to-adf') return toAdf(input)
if (mode === 'to-markdown') return toMarkdown(JSON.parse(input))
throw new Error(`mode must be to-adf or to-markdown, not ${mode}`)
if (mode === 'to-adf') return toAdf(portableMarkdownToAdf, input)
if (mode === 'to-adf-lossless') return toAdf(losslessMarkdownToAdf, input)
if (mode === 'to-markdown') return toMarkdown(adfToPortableMarkdown, JSON.parse(input))
if (mode === 'to-markdown-lossless') return toMarkdown(adfToLosslessMarkdown, JSON.parse(input))
throw new Error(`mode must be to-adf, to-adf-lossless, to-markdown or to-markdown-lossless, not ${mode}`)
}
main(process.argv[2]).then(
+55
View File
@@ -66,6 +66,36 @@ def test_adf_to_markdown_returns_the_text_of_its_one_document():
assert run.calls == [("to-markdown", json.dumps([DOC]))]
def test_markdown_to_adf_lossless_runs_the_lossless_mode():
run = fake(0, json.dumps(DOC))
assert convert.markdown_to_adf_lossless("Hi\n", run) == DOC
assert run.calls == [("to-adf-lossless", "Hi\n")]
def test_adfs_to_markdown_lossless_sends_every_document_in_one_lossless_run():
run = fake(0, json.dumps(["a\n", "b\n"]))
assert convert.adfs_to_markdown_lossless([DOC, DOC], run) == ["a\n", "b\n"]
assert run.calls == [("to-markdown-lossless", json.dumps([DOC, DOC]))]
def test_adf_to_markdown_lossless_returns_the_text_of_its_one_document():
run = fake(0, json.dumps(["a\n"]))
assert convert.adf_to_markdown_lossless(DOC, run) == "a\n"
assert run.calls == [("to-markdown-lossless", json.dumps([DOC]))]
def test_adfs_to_markdown_lossless_names_a_refused_documents_index():
refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
refused = convert.adfs_to_markdown_lossless([DOC, DOC], fake(2, json.dumps(refusal)))
assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)"))
def test_adfs_to_markdown_lossless_of_no_documents_runs_no_container():
run = fake(1)
assert convert.adfs_to_markdown_lossless([], run) == []
assert run.calls == []
def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message():
refusal = {"error": {"code": "malformed-pipe-table", "message": "row has too many cells", "path": [], "position": {"line": 3, "offset": 9}}}
failure = convert.markdown_to_adf("| a |\n", fake(2, json.dumps(refusal)))
@@ -279,3 +309,28 @@ def test_round_trip_through_the_real_container():
assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason
crashed = convert.answer("to-markdown", "not json", convert.container_run)
assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ")
# A Jira description as Jira stores it: every block carries a localId, and an empty paragraph spaces two blocks.
JIRA_DESCRIPTION = {
"type": "doc", "version": 1, "content": [
{"type": "heading", "attrs": {"level": 2, "localId": "h-1"}, "content": [{"type": "text", "text": "Goal"}]},
{"type": "paragraph", "attrs": {"localId": "p-1"}, "content": [{"type": "text", "text": "Keep "}, {"type": "text", "text": "this", "marks": [{"type": "strong"}]}]},
{"type": "paragraph", "attrs": {"localId": "p-2"}},
{"type": "bulletList", "attrs": {"localId": "l-1"}, "content": [
{"type": "listItem", "attrs": {"localId": "i-1"}, "content": [{"type": "paragraph", "attrs": {"localId": "p-3"}, "content": [{"type": "text", "text": "one"}]}]},
]},
],
}
@pytest.mark.skipif(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode != 0, reason="needs a docker daemon")
def test_the_lossless_pair_gives_back_a_jira_description_identical_and_the_portable_pair_does_not():
markdown = convert.adf_to_markdown_lossless(JIRA_DESCRIPTION)
assert isinstance(markdown, str)
assert convert.markdown_to_adf_lossless(markdown) == JIRA_DESCRIPTION
assert convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, JIRA_DESCRIPTION]) == [markdown, markdown]
portable = convert.markdown_to_adf(convert.adf_to_markdown(JIRA_DESCRIPTION))
assert portable != JIRA_DESCRIPTION
second = convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, {"type": "nope"}])
assert isinstance(second, convert.Refused) and second.index == 1
+51
View File
@@ -0,0 +1,51 @@
"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request both backends send, and each service's error messages."""
import base64
import pathlib
import typing
from failure import Failure
from rest_client import json_request
from rest_client.env_file import read_env
from adf_codec.convert import Refused
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# Seconds each connect and each read may wait.
TIMEOUT = 30
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def jira_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, jira_errors)
def jira_errors(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
def confluence_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, confluence_errors)
def confluence_errors(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))
+65
View File
@@ -0,0 +1,65 @@
import base64
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from atlassian import client
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client.test_json_request import Served
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
class Credentials(unittest.TestCase):
def test_builds_basic_auth_from_the_env_files_email_and_token(self):
with tempfile.TemporaryDirectory() as temp:
env = pathlib.Path(temp, "acme.env")
env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
env.chmod(0o600)
self.assertEqual(client.basic_auth(env), AUTHORIZATION)
def test_a_missing_env_file_fails(self):
self.assertIsInstance(client.basic_auth(pathlib.Path("/nonexistent/acme.env")), Failure)
class Jira(Served):
def test_an_error_answer_fails_with_jiras_messages_and_its_status(self):
base = self.serve((400, b'{"errorMessages": ["One."], "errors": {"jql": "Two."}}'))
self.assertEqual(client.jira_json("POST", f"{base}/rest/api/3/search/jql", AUTHORIZATION, {"jql": "x"}), ErrorAnswer("POST /rest/api/3/search/jql answered 400: One.; Two.", 400))
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"jql": "x"}))
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(client.jira_errors(answer), message)
class Confluence(Served):
def test_an_error_answer_fails_with_confluences_messages_and_its_status(self):
base = self.serve((409, b'{"errors": [{"status": 409, "title": "Version must be incremented"}]}'))
self.assertEqual(client.confluence_json("PUT", f"{base}/wiki/api/v2/pages/1", AUTHORIZATION, {"version": {"number": 2}}), ErrorAnswer("PUT /wiki/api/v2/pages/1 answered 409: Version must be incremented", 409))
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"version": {"number": 2}}))
def test_reads_confluences_messages_from_an_error_answer(self):
self.assertEqual(client.confluence_errors({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
self.assertEqual(client.confluence_errors({"message": "Not Found"}), "Not Found")
self.assertEqual(client.confluence_errors({"errors": "odd"}), "")
self.assertEqual(client.confluence_errors(["odd"]), "")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -4,7 +4,7 @@ import typing
from failure import Failure
from review_rules.comprehension_history import HISTORY
from release_plan.todo_table import Item, items
from plan.todo_table import Item, items
from reading_cost.figures import RECORD
from project_config import templates
from text_files.utc_stamp import utc
+1 -1
View File
@@ -5,7 +5,7 @@ import re
import typing
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
from release_plan.todo_table import Exempt, Item
from plan.todo_table import Exempt, Item
from review_rules.round_titles import title_counts
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
+1 -1
View File
@@ -17,7 +17,7 @@ from project_config.test_project_config import configured
from failure import Failure
from git_cli.git_repo import git
from test_env import isolated_env
from release_plan.todo_table import Item
from plan.todo_table import Item
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
+53 -27
View File
@@ -8,42 +8,68 @@ from failure import Failure
from chunk_preflight.gathered import Forge
from deploy_release.forge import Run
BIN = pathlib.Path(__file__).resolve().parents[1]
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints.
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
POLL_SECONDS = 60
WAIT_SECONDS = 90 * 60
def awaited(forge: Forge, run: Run) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails too."""
answer = run([str(BIN / "project-config"), "wait-for-approval"])
if isinstance(answer, Failure):
return answer
if answer.strip() not in ("true", "false"):
return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false")
if answer.strip() == "true" and forge != "gh":
def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires."""
if wait_for_approval and forge != "gh":
return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
return answer.strip() == "true"
return wait_for_approval
# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout.
THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
author { login }
reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } }
} } }"""
def approval(number: str, run: Run) -> bool | Failure:
"""Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review."""
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
try:
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
if isinstance(decision, Failure):
return decision
if decision == "CHANGES_REQUESTED":
return Failure(f"a reviewer requested changes on pull request {number}")
if not decision:
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
if decision not in ("APPROVED", "REVIEW_REQUIRED"):
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
return decision == "APPROVED"
def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
"""None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS."""
"""None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS."""
for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS):
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
try:
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
if isinstance(decision, Failure):
return decision
if decision == "APPROVED":
return None
if decision == "CHANGES_REQUESTED":
return Failure(f"a reviewer requested changes on pull request {number}")
if not decision:
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
if decision != "REVIEW_REQUIRED":
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
read = approval(number, run)
if read is True or isinstance(read, Failure):
return None if read is True else read
asked = unanswered(number, run)
if asked is not None:
return asked
if waited < WAIT_SECONDS:
sleep(POLL_SECONDS)
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
def unanswered(number: str, run: Run) -> Failure | None:
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits."""
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
try:
pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"]
if isinstance(pull, Failure):
return pull
author = pull["author"]["login"]
waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
except (ValueError, KeyError, TypeError):
return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}")
if not waiting:
return None
return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again")
+294 -70
View File
@@ -3,7 +3,7 @@
usage: chunk-pr open <title> [<body>]
chunk-pr sync
chunk-pr ready [<title>]
chunk-pr merge
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
chunk-pr clean
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
@@ -25,22 +25,44 @@ 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.
merge waits for the pull request's checks, and those origin's default branch requires, to pass
on the head, then merges the pull request, and only while its head is still the commit
checked out, so a push after the gate is never merged. Where no check reports within a
minute, it takes the pull request as having none. It refuses where a check fails, or, on
Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them
until they end. Run it in the background.
It takes the first merge method the repository allows of: a merge commit, fast-forward
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
merge commit, the rebase and the squash. It also refuses where `larv-review
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
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;
2. finishes each plan item a --finish names with `todo-item finish`, passing on
--changelog or --no-changelog, and commits what that changed in the plan and the
changelog, so both change only at merge time, on top of every chunk merged before;
3. pushes, also where step 2 failed after step 1 brought changes in;
4. waits for the pull request's checks, and those origin's default branch requires, to
pass on the head; where no check reports within a minute, it takes the pull request
as having none;
5. merges the pull request, only while its head is still the commit checked out, so a
push after the gate is never merged. It takes the first merge method the repository
allows of: a merge commit, fast-forward only, a rebase followed by a merge commit, a
rebase, a squash. GitHub offers only the merge commit, the rebase and the squash.
Its last line names each --finish item the plan did not hold when it began: an earlier
run finished that item, or its ID is mistyped.
Where the project's config sets `wait-for-approval = true` (`project-config --help`), it
also waits, once the checks have passed, until GitHub reports the pull request approved
as its branch protection requires. It refuses at once where a reviewer requested changes,
where the protection requires no review, on Gitea, and where it cannot read the config.
After 90 minutes without an approval it refuses too; run it again once the pull request
is approved.
merges only once GitHub reports the pull request approved as its branch protection
requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes
a new turn once approved.
It stops, without merging, and says what to do before running it again:
- on a merge conflict in step 1, naming the conflicted files, with the merge in progress;
- where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a
scoring run it has not recorded;
- where origin's default branch has moved since the branch last recorded a paired
ruling, since that ruling read a head that no longer merges;
- where a check fails, or, on Gitea, where the checks have not all passed within 30
minutes; on GitHub, gh watches them until they end;
- where other pull requests still hold the turn after 30 minutes, naming the last;
- with `wait-for-approval`: where a reviewer requested changes, where the protection
requires no review, on Gitea, where it cannot read the config, and after 90 minutes
without an approval;
- with `wait-for-approval`, approved or not: where a reviewer's comment waits for an
answer, which is a review thread nobody resolved whose last comment is not the pull
request author's. Answer it in its thread and push any fix.
A run that waits for an approval takes two turns, so it can last the 90 minutes and,
twice, the 30 minutes in the queue and the checks. One killed before that left the
branch pushed, so run it again.
clean acts once the forge reports the branch's pull request merged at the commit checked out,
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
default branch, removes the chunk's worktree, then deletes the local branch; origin's
@@ -51,7 +73,10 @@ clean acts once the forge reports the branch's pull request merged at the com
It prints what it did, exit 0, or why it failed, exit 1.
"""
import contextlib
import dataclasses
import fcntl
import functools
import json
import os
import pathlib
@@ -59,17 +84,29 @@ import sys
import time
import typing
from chunk_pr.approval import approved, awaited
from chunk_pr.approval import approval, approved, awaited, unanswered
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
from failure import Failure
from chunk_preflight.gathered import Forge
from chunk_preflight.choices import forge_of
from project_config.main import located
from project_config.settings import ProjectConfig
from plan_store.plans import says_no_item
from project_config import templates
BIN = pathlib.Path(__file__).resolve().parents[1]
# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one.
NO_CHECKS_SECONDS = 60
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean"
# The file, in the git folder that every worktree of the checkout shares, that a merge keeps locked with flock for its turn: so every chunk of the project on this machine queues on it.
QUEUE = "chunk-pr-merge-queue"
# A turn lasts as long as its checks, which chunk-pr waits half an hour for on Gitea, so a queue still held after that is reported, not waited out.
QUEUE_SECONDS = 30 * 60
QUEUE_POLL_SECONDS = 10
# The line record-ruling writes into the comprehension history, as git's -G reads it.
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"
# 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], ...]] = {
@@ -82,7 +119,7 @@ def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
done = step(argv, runner(os.getcwd()))
done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())))
if isinstance(done, Failure):
print(f"chunk-pr: {done.reason}", file=sys.stderr)
return 1
@@ -90,31 +127,34 @@ def main(argv: list[str]) -> int:
return 0
def step(argv: list[str], run: Run) -> str | Failure:
def step(argv: list[str], run: Run, config: Config) -> str | Failure:
"""Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything."""
match argv:
case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"):
return Failure("give a title of one line") if not one_line(title) else misfit(title, run) or opened(title, body[0] if body else "", run)
return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run)
case ["sync"]:
return synced(run)
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) if title else None) or marked_ready(run, title[0] if title else None)
case ["merge"]:
return merged(run)
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)
case ["merge", *given]:
finishes = finishes_of(given)
return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes)
case ["clean"]:
return cleaned(run)
return Failure(USAGE)
def misfit(title: str, run: Run) -> Failure | None:
"""Why title doesn't fit the `pull-request-title` template the project's config names; None where it fits. A branch that doesn't fit the config's `branch` template is no plan item's, so it has no ID for {id}, and any title fits there. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
read = [run([str(BIN / "project-config"), "pull-request-title"]), run([str(BIN / "project-config"), "branch"]), run(["git", "symbolic-ref", "--short", "HEAD"])]
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
return failed
template, branch_template, branch = (answer.strip("\n") for answer in read if isinstance(answer, str))
if not templates.branch_fits(branch_template, branch) or templates.fits(template, title.strip()):
def misfit(title: str, run: Run, config: Config) -> Failure | None:
"""Why title doesn't fit the `pull-request-title` template the project's config names, as templates.misfits rules; None where it fits. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
loaded = config()
if isinstance(loaded, Failure):
return loaded
branch = run(["git", "symbolic-ref", "--short", "HEAD"])
if isinstance(branch, Failure):
return branch
if not templates.misfits(loaded.pull_request_title, loaded.branch, branch.strip("\n"), title):
return None
return Failure(f"title the pull request as the project's config asks, `{template}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
return Failure(f"title the pull request as the project's config asks, `{loaded.pull_request_title}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
def one_line(title: str) -> bool:
@@ -185,7 +225,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
return number if isinstance(number, Failure) else f"Opened draft pull request #{number}."
def synced(run: Run) -> str | Failure:
def synced(run: Run, config: Config) -> str | Failure:
found = checkout(run)
if isinstance(found, Failure):
return found
@@ -195,28 +235,16 @@ def synced(run: Run) -> str | Failure:
return base
if branch == base:
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
fetched = run(["git", "fetch", "--quiet", "origin"])
if isinstance(fetched, Failure):
return fetched
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"])
if isinstance(behind, Failure):
return behind
count, root = behind
if count == "0":
done = f"{branch} already holds origin/{base}."
else:
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
if isinstance(merged, Failure):
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
if isinstance(conflicted, Failure) or not conflicted[0]:
return merged
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit")
done = f"Merged origin/{base} into {branch}."
plan = run([str(BIN / "project-config"), "plan"])
if isinstance(plan, Failure):
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {plan.reason}")
todo = pathlib.Path(plan.strip())
if not todo.is_file():
level = levelled(run, branch, base)
if isinstance(level, Failure):
return level
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
loaded = config()
if isinstance(loaded, Failure):
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}")
todo = loaded.plan_file
# A plan in Jira is no file, and Jira's backlog ranks it.
if todo is None or not todo.is_file():
return done
ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)])
if isinstance(ranked, Failure):
@@ -224,6 +252,25 @@ def synced(run: Run) -> str | Failure:
return f"{done}\nrank_todo.py --check todo.md passed."
def levelled(run: Run, branch: str, base: str, resolve: str = "resolve them and commit") -> bool | Failure:
"""Fetch origin and merge its base into branch, the one checked out: whether that brought anything in. On a conflict the merge stays in progress, and the Failure names the conflicted files and ends with resolve, the caller's words for what to do about them."""
fetched = run(["git", "fetch", "--quiet", "origin"])
if isinstance(fetched, Failure):
return fetched
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"])
if isinstance(behind, Failure):
return behind
if behind[0] == "0":
return False
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
if isinstance(merged, Failure):
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
if isinstance(conflicted, Failure) or not conflicted[0]:
return merged
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: {resolve}")
return True
def marked_ready(run: Run, title: str | None) -> str | Failure:
found = pull(run)
if isinstance(found, Failure):
@@ -241,33 +288,210 @@ 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 merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure:
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
while rest:
match rest:
case ["--finish", item, "--changelog", bullet, *rest] if item.isdigit():
finishes.append([item, "--changelog", bullet])
case ["--finish", item, "--no-changelog", *rest] if item.isdigit():
finishes.append([item, "--no-changelog"])
case ["--finish", item, *rest] if item.isdigit():
finishes.append([item])
case _:
return None
return finishes
def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved."""
found = pull(run)
if isinstance(found, Failure):
return found
forge, number, head = found
waits = awaited(forge, run)
forge, number, _ = found
loaded = config()
if isinstance(loaded, Failure):
return loaded
waits = awaited(forge, loaded.wait_for_approval)
if isinstance(waits, Failure):
return waits
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
method = merge_method(forge, run)
if isinstance(method, Failure):
return method
base = default_branch(run)
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(required, Failure):
return required
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
if isinstance(queue, Failure):
return queue
absent = unplanned(run, finishes)
if isinstance(absent, Failure):
return absent
file = pathlib.Path(queue[0]) / QUEUE
pull_request = Merging(forge, number, method, str(base), required, waits)
while True:
with turn(file, number, sleep) as untaken:
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
if not isinstance(taken, AwaitsApproval):
return taken if isinstance(taken, Failure) else taken + absent
# Out of the queue, so the project's other chunks merge while this one waits.
waited = approved(number, run, sleep)
if isinstance(waited, Failure):
return waited
@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, and whether it waits for an approval."""
forge: Forge
number: str
method: str
base: str
required: set[str]
waits: bool
@dataclasses.dataclass(frozen=True)
class AwaitsApproval:
"""The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one."""
def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | Failure:
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails."""
head = levelled_and_finished(run, pull_request.base, finishes, config)
checked = head if isinstance(head, Failure) else checks_passed(pull_request.forge, pull_request.number, head, pull_request.required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(checked, Failure):
return checked
approval = approved(number, run, sleep) if waits else None
if isinstance(approval, Failure):
return approval
if forge == "gh":
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
ready = approval(pull_request.number, run) if pull_request.waits else True
if isinstance(ready, Failure):
return ready
if not ready:
return AwaitsApproval()
asked = unanswered(pull_request.number, run) if pull_request.waits else None
if asked is not None:
return asked
if pull_request.forge == "gh":
done = run(["gh", "pr", "merge", pull_request.number, pull_request.method, "--match-head-commit", str(head)])
else:
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')})."
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull_request.number}/merge", f"Do={pull_request.method}", f"head_commit_id={head}")
return done if isinstance(done, Failure) else f"Merged pull request #{pull_request.number} ({pull_request.method.removeprefix('--')})."
def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure:
"""A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all."""
absent = []
for finish in finishes:
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]):
return shown
absent += [finish[0]] if isinstance(shown, Failure) else []
return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else ""
@contextlib.contextmanager
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[Failure | None]:
"""Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Gives None while it holds the queue; a Failure, without the queue, where another merge still holds it after QUEUE_SECONDS or the file cannot be opened or locked."""
try:
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
except OSError as failure:
yield Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
return
try:
yield held_turn(fd, queue, number, sleep)
finally:
os.close(fd)
def held_turn(fd: int, queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> Failure | None:
"""Lock the open queue file fd for pull request number and write its number there, for a merge that waits to name; None once held, else why it isn't."""
try:
for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS):
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if waited == QUEUE_SECONDS:
holder = os.pread(fd, 20, 0).decode(errors="replace").strip()
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{holder or '?'}, so this one took no turn; run chunk-pr merge again")
sleep(QUEUE_POLL_SECONDS)
os.ftruncate(fd, 0)
os.pwrite(fd, number.encode(), 0)
except OSError as failure:
return Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
return None
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]], config: ProjectConfig) -> str | Failure:
"""What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out."""
found = checkout(run)
if isinstance(found, Failure):
return found
_, branch, before = found
moved = levelled(run, branch, base, "resolve them, commit, push, and run chunk-pr merge again")
if isinstance(moved, Failure):
return moved
failed = next((failure for finish in finishes if (failure := finished(run, branch, finish, config))), None)
head = answers(run, ["rev-parse", "HEAD"])
if isinstance(head, Failure):
return head
pushed = run(["git", "push", "--quiet", "origin", branch]) if head[0] != before else ""
if isinstance(pushed, Failure):
return pushed
# The scoring run is asked for only now: scoring-run-owed counts as shipped the items the committed plan no longer holds.
owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
return remeasure(run, base, config) or head[0]
def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> Failure | None:
"""Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way."""
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]):
return shown
finishing = "" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish])
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")
# 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)
def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None:
"""Commit what changed in files under title, each in the git repository that holds it, and only those files: a record the config keeps in its own folder is committed there, where another chunk may commit at the same time."""
held: dict[str, list[str]] = {}
for file in files:
top = run(["git", "-C", str(file.parent), "rev-parse", "--show-toplevel"])
if isinstance(top, Failure):
return top
held.setdefault(top.strip(), []).append(str(file))
for top, paths in held.items():
changed = run(["git", "-C", top, "status", "--porcelain", "--", *paths])
steps = [changed] if isinstance(changed, Failure) or not changed.strip() else [run(["git", "-C", top, "add", "--", *paths]), run(["git", "-C", top, "commit", "--quiet", "-m", title, "--", *paths])]
if failed := next((step for step in steps if isinstance(step, Failure)), None):
return failed
return None
def remeasure(run: Run, base: str, config: ProjectConfig) -> Failure | None:
"""A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout."""
history = config.paths.get("comprehension-history")
# A history on a Confluence page is outside the checkout.
if history is None:
return None
top = answers(run, ["rev-parse", "--show-toplevel"])
if isinstance(top, Failure) or not history.resolve().is_relative_to(top[0]):
return top if isinstance(top, Failure) else None
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", str(history)])
if isinstance(ruled, Failure) or not ruled[0].strip():
return ruled if isinstance(ruled, Failure) else None
since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"])
if isinstance(since, Failure) or since[0].strip() == "0":
return since if isinstance(since, Failure) else None
return Failure(f"origin/{base} moved after the branch recorded its paired ruling, and its changes are merged in and pushed; run the paired ruling again at the new head, record it, push, and run chunk-pr merge again")
def merge_method(forge: Forge, run: Run) -> str | Failure:
+395 -88
View File
@@ -1,5 +1,9 @@
import contextlib
import fcntl
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
@@ -7,10 +11,12 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from chunk_pr.main import cleaned, merged, step, USAGE
from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
from failure import Failure
from test_env import isolated_env
from project_config.settings import ProjectConfig
from deploy_release.forge import Run
from chunk_pr.approval import THREADS
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
GITHUB = "git@github.com:me/project.git"
@@ -28,7 +34,14 @@ OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scori
TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "pull-request-title"]
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
# 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_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"]
# The folder the fake checkouts name as their shared git folder, where merge keeps its queue's file.
GIT_FOLDER = tempfile.TemporaryDirectory()
class Checkout:
@@ -45,6 +58,8 @@ class Checkout:
self.decisions = ["APPROVED"]
# Set, what GitHub prints instead of a decision's JSON.
self.unreadable: str | Failure | None = None
# The pull request's review threads, as GitHub's GraphQL API prints them; its author is `worker`.
self.threads: list[dict[str, object]] = []
self.ran: list[list[str]] = []
self.answers: dict[tuple[str, ...], str | Failure] = {
("git", "remote", "get-url", "origin"): f"{origin}\n",
@@ -54,8 +69,20 @@ class Checkout:
tuple(WAITS): "false\n",
tuple(TITLE): "{summary}\n",
tuple(BRANCH): "item-{id}\n",
tuple(BEHIND): "0\n",
tuple(COMMON): f"{GIT_FOLDER.name}\n",
("git", "rev-parse", "--show-toplevel"): "/checkout\n",
}
def config(self) -> ProjectConfig | Failure:
"""The project's config, from the settings the answers hold under PROJECT_CONFIG; a Failure where one of them is, as where no config names the checkout."""
named = {key[1]: answer for key, answer in self.answers.items() if key[0] == PROJECT_CONFIG}
if failed := next((answer for answer in named.values() if isinstance(answer, Failure)), None):
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", commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
def __call__(self, command: list[str]) -> str | Failure:
self.ran.append(command)
if command[0] == ("tea" if self.github else "gh"):
@@ -74,6 +101,8 @@ class Checkout:
return self.unreadable
if command == GH_DECISION:
return json.dumps({"reviewDecision": self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]})
if command == GH_THREADS:
return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": self.threads}}}}})
if command == TEA_BRANCH:
return json.dumps({"enable_status_check": False})
if command in (GH_SETTINGS, TEA_SETTINGS):
@@ -82,7 +111,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]
reads = [GH_LIST, GH_DECISION, TEA_LIST, 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]
@@ -93,32 +122,32 @@ class Open(unittest.TestCase):
checkout = Checkout(GITHUB, open=argv[0] == "ready")
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
self.assertNotIsInstance(step(argv, checkout), Failure)
self.assertNotIsInstance(step(argv, checkout, checkout.config), Failure)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "feature/PAY-7\n"
refused = step(argv, checkout)
refused = step(argv, checkout, checkout.config)
assert isinstance(refused, Failure), refused
self.assertIn("'Release review of 0.3.0' doesn't fit", refused.reason)
def test_github_pushes_and_opens_a_draft_into_the_default_branch(self):
checkout = Checkout(GITHUB, open=False)
opened = step(["open", "ABC-1 - Do it", "The body."], checkout)
opened = step(["open", "ABC-1 - Do it", "The body."], checkout, checkout.config)
self.assertEqual(checkout.acted(), [PUSH, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."]])
self.assertEqual(opened, "Opened draft pull request #12.")
def test_gitea_opens_a_draft_with_tea(self):
checkout = Checkout(GITEA, open=False)
self.assertEqual(step(["open", "Do it"], checkout), "Opened draft pull request #12.")
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.")
self.assertEqual(checkout.acted(), [PUSH, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""]])
def test_an_open_pull_request_is_kept(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["open", "Do it"], checkout), "Pull request #12 is open already.")
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Pull request #12 is open already.")
self.assertEqual(checkout.acted(), [PUSH])
def test_on_the_default_branch_it_refuses_and_pushes_nothing(self):
checkout = Checkout(GITEA, open=False)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
self.assertIsInstance(step(["open", "Do it"], checkout), Failure)
self.assertIsInstance(step(["open", "Do it"], checkout, checkout.config), Failure)
self.assertEqual(checkout.acted(), [])
def test_a_title_that_does_not_fit_the_configs_template_is_refused_before_anything_runs(self):
@@ -126,75 +155,75 @@ class Open(unittest.TestCase):
with self.subTest(argv=argv):
checkout = Checkout(GITHUB, open=argv[0] == "ready")
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
refused = step(argv, checkout)
refused = step(argv, checkout, checkout.config)
assert isinstance(refused, Failure), refused
self.assertIn("`PAY-{id} - {summary}`", refused.reason)
self.assertEqual(checkout.acted(), [])
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout), Failure)
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout, checkout.config), Failure)
checkout.answers[tuple(TITLE)] = Failure("no config names the checkout")
self.assertEqual(step(argv, checkout), Failure("no config names the checkout"))
self.assertEqual(step(argv, checkout, checkout.config), Failure("no config names the checkout"))
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
checkout.answers[tuple(BRANCH)] = Failure("`branch` is 'x', which holds no {id}")
self.assertEqual(step(argv, checkout), Failure("`branch` is 'x', which holds no {id}"))
self.assertEqual(step(argv, checkout, checkout.config), Failure("`branch` is 'x', which holds no {id}"))
untitled = Checkout(GITHUB, open=True)
untitled.answers[tuple(TITLE)] = Failure("no config names the checkout")
self.assertNotIsInstance(step(["ready"], untitled), Failure)
self.assertNotIsInstance(step(["ready"], untitled, untitled.config), Failure)
def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self):
for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)):
with self.subTest(argv):
checkout = Checkout(GITHUB, open=False)
self.assertEqual(step(argv, checkout), Failure(refusal))
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
self.assertEqual(checkout.ran, [])
def test_a_failed_listing_after_the_create_is_returned(self):
checkout = Checkout(GITHUB, open=False)
checkout.answers[("gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--body", "")] = Failure("gh pr create: done")
self.assertEqual(step(["open", "Do it"], checkout), Failure("gh pr create: done"))
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), Failure("gh pr create: done"))
checkout = Checkout(GITHUB, open=False)
listings = iter(["", Failure("gh pr list: offline")])
original = checkout.__call__
checkout_call = lambda command: next(listings) if command == GH_LIST else original(command)
self.assertEqual(step(["open", "Do it"], checkout_call), Failure("gh pr list: offline"))
self.assertEqual(step(["open", "Do it"], checkout_call, checkout.config), Failure("gh pr list: offline"))
class Ready(unittest.TestCase):
def test_github_marks_it_ready(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
self.assertEqual(checkout.acted(), [["gh", "pr", "ready", "12"]])
def test_gitea_marks_it_ready_with_tea(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]])
def test_github_sets_a_given_title_then_marks_it_ready(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]])
def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]])
def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self):
for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)):
with self.subTest(argv=argv):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(argv, checkout), Failure(refusal))
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
self.assertEqual(checkout.ran, [])
def test_a_failed_title_edit_on_github_leaves_it_a_draft(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied")
self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied"))
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), Failure("gh pr edit: denied"))
self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran)
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
checkout = Checkout(GITHUB, open=False)
ready = step(["ready"], checkout)
ready = step(["ready"], checkout, checkout.config)
self.assertIsInstance(ready, Failure)
self.assertIn("item-7", ready.reason)
self.assertEqual(checkout.acted(), [])
@@ -202,10 +231,10 @@ class Ready(unittest.TestCase):
def test_a_failed_ready_or_git_call_is_returned(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[("tea", "pulls", "edit", "12", "--ready")] = Failure("tea pulls edit: denied")
self.assertEqual(step(["ready"], checkout), Failure("tea pulls edit: denied"))
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("tea pulls edit: denied"))
checkout = Checkout(GITEA, open=True)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = Failure("git symbolic-ref: HEAD is detached")
self.assertEqual(step(["ready"], checkout), Failure("git symbolic-ref: HEAD is detached"))
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("git symbolic-ref: HEAD is detached"))
self.assertEqual(checkout.acted(), [])
@@ -232,34 +261,34 @@ class Sync(unittest.TestCase):
def test_a_branch_behind_the_default_branch_merges_it(self):
checkout = self.checkout(behind=3)
self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.")
self.assertEqual(step(["sync"], checkout, checkout.config), "Merged origin/main into item-7.")
self.assertEqual(checkout.acted(), [FETCH, MERGE])
def test_a_branch_that_holds_the_default_branch_merges_nothing(self):
checkout = self.checkout(behind=0)
self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.")
self.assertEqual(step(["sync"], checkout, checkout.config), "item-7 already holds origin/main.")
self.assertEqual(checkout.acted(), [FETCH])
def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self):
checkout = self.checkout(behind=1, todo=True)
self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
self.assertEqual(step(["sync"], checkout, checkout.config), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]])
def test_a_checkout_no_config_names_fails_naming_what_it_did(self):
checkout = self.checkout(behind=0, todo=True)
checkout.answers[PLAN] = Failure("no config names the checkout")
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
def test_a_failing_rank_check_fails_naming_what_it_did(self):
checkout = self.checkout(behind=0, todo=True)
checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order")
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self):
checkout = self.checkout(behind=2, todo=True)
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n"
self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
self.assertNotIn([RANK, "--check", self.todo], checkout.ran)
self.assertNotIn(["git", "merge", "--abort"], checkout.ran)
@@ -267,48 +296,53 @@ class Sync(unittest.TestCase):
checkout = self.checkout(behind=2)
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten")
checkout.answers[CONFLICTED] = ""
self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git merge --quiet: untracked files would be overwritten"))
def test_on_the_default_branch_it_refuses_and_fetches_nothing(self):
checkout = self.checkout(behind=0)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("main is origin's default branch; sync the chunk's branch"))
self.assertNotIn(FETCH, checkout.ran)
def test_a_failed_fetch_is_returned(self):
checkout = self.checkout(behind=0)
checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote")
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git fetch --quiet: could not read from remote"))
def changes(checkout: Checkout) -> list[list[str]]:
"""What a merge ran, leaving out what it read, the project's config included, and the fetch each turn opens with."""
return [command for command in checkout.acted() if command != FETCH and not command[0].endswith("/project-config")]
class Merge(unittest.TestCase):
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
checkout = Checkout(GITHUB, open=True)
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
self.assertIsInstance(step(["merge", "--gate-passed"], checkout, checkout.config), Failure)
self.assertEqual(checkout.ran, [])
def test_an_option_given_as_a_title_runs_nothing(self):
for argv in (["ready", "--help"], ["open", "-h"]):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(argv, checkout), Failure(USAGE))
self.assertEqual(step(argv, checkout, checkout.config), Failure(USAGE))
self.assertEqual(checkout.ran, [])
def test_github_waits_for_the_checks_before_merging(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
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]])
def test_a_failed_check_on_github_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(changes(checkout), [])
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 60)
self.assertEqual(checkout.ran.count(GH_CHECKS), 7)
@@ -316,7 +350,7 @@ class Merge(unittest.TestCase):
checkout = Checkout(GITEA, open=True)
checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 60)
def requiring_approval(self, origin: str = GITHUB, *decisions: str) -> Checkout:
@@ -329,33 +363,33 @@ class Merge(unittest.TestCase):
def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self):
checkout = Checkout(GITHUB, open=True)
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertNotIn(GH_DECISION, checkout.ran)
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
checkout = self.requiring_approval()
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_DECISION, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
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]])
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")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(slept, [60, 60])
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(slept, [60])
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
slept: list[float] = []
failed = merged(checkout, slept.append)
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("90 minutes", failed.reason)
self.assertEqual(sum(slept), 90 * 60)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 90, "APPROVED")
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 90 * 60)
def test_a_review_decision_it_cannot_read_or_does_not_know_leaves_it_unmerged(self):
@@ -363,40 +397,38 @@ class Merge(unittest.TestCase):
with self.subTest(answer):
checkout = self.requiring_approval()
checkout.unreadable = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
self.assertEqual(changes(checkout), [])
def test_requested_changes_leave_it_unmerged_without_waiting(self):
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
slept: list[float] = []
failed = merged(checkout, slept.append)
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("requested changes", failed.reason)
self.assertEqual((slept, checkout.acted()), ([], []))
self.assertEqual((slept, changes(checkout)), ([], []))
def test_a_branch_protection_that_asks_for_no_review_leaves_it_unmerged_naming_the_setting(self):
for decision in ("", None):
with self.subTest(decision):
checkout = self.requiring_approval(GITHUB, decision)
failed = step(["merge"], checkout)
failed = step(["merge"], checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("requires no review", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
checkout = self.requiring_approval(GITEA)
failed = step(["merge"], checkout)
failed = step(["merge"], checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("GitHub", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
with self.subTest(answer):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
def test_a_config_it_cannot_read_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = Failure("no config names the checkout")
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("no config names the checkout"))
self.assertEqual(changes(checkout), [])
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
@@ -412,79 +444,354 @@ class Merge(unittest.TestCase):
def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self):
checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")])
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(len(slept), 2)
self.assertEqual(checkout.ran.count(TEA_STATUS), 3)
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
self.assertEqual(checkout.acted(), [])
self.assertIsInstance(merged(checkout, checkout.config, lambda _: None), Failure)
self.assertEqual(changes(checkout), [])
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("tea api: 500"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
failed = merged(checkout, lambda _: None)
failed = merged(checkout, checkout.config, lambda _: None)
self.assertIsInstance(failed, Failure)
self.assertIn("gave up on pull request 12", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
for origin in (GITHUB, GITEA):
with self.subTest(origin=origin):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(changes(checkout), [])
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_github_without_merge_commits_rebases(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
step(["merge"], checkout)
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
step(["merge"], checkout, checkout.config)
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (fast-forward-only).")
self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
self.assertEqual(changes(checkout), [])
def test_a_forge_failure_is_returned(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved"))
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr merge: head moved"))
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_SETTINGS)] = "not json"
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
def test_a_failed_settings_read_is_returned_unmerged(self):
for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)):
with self.subTest(origin):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(settings)] = Failure("settings: denied")
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("settings: denied"))
self.assertEqual(changes(checkout), [])
def queue_is_free() -> bool:
"""Whether another merge could take its turn now."""
fd = os.open(pathlib.Path(GIT_FOLDER.name) / QUEUE, os.O_RDWR | os.O_CREAT)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return False
finally:
os.close(fd)
return True
class MergeQueue(unittest.TestCase):
PUSHED = ["git", "push", "--quiet", "origin", "item-7"]
TODO_ITEM = str(pathlib.Path(__file__).resolve().parents[1] / "todo-item")
CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
def moved(self, checkout: Checkout) -> Checkout:
"""checkout with origin's main two commits ahead of the branch, whose head is `decaf` once main is merged in."""
checkout.answers[tuple(BEHIND)] = "2\n"
run = checkout.__call__
def merging(command: list[str]) -> str | Failure:
answer = run(command)
if command == MERGE and not isinstance(answer, Failure):
checkout.answers[("git", "rev-parse", "HEAD")] = "decaf\n"
return answer
checkout.__call__ = merging # type: ignore[method-assign]
return checkout
def with_plan(self, checkout: Checkout, held: bool = True) -> tuple[Checkout, str]:
"""checkout in a project whose config names a todo.md and a CHANGELOG.md in one folder, which is returned, and titles commits `[{id}] {summary}`. The plan holds item 7 where held. A commit moves the head to `f00d`."""
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder)
for name in ("todo.md", "CHANGELOG.md"):
(pathlib.Path(folder) / name).write_text("")
checkout.answers.update({
(self.TODO_ITEM, "show", "7"): "From todo.md:\n" if held else Failure("todo-item show 7: todo.md holds no item 7"),
(self.CONFIG, "plan"): f"{folder}/todo.md\n",
(self.CONFIG, "changelog"): f"{folder}/CHANGELOG.md\n",
(self.CONFIG, "commit-title"): "[{id}] {summary}\n",
("git", "-C", folder, "rev-parse", "--show-toplevel"): f"{folder}\n",
("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md"): " M todo.md\n",
})
run = checkout.__call__
def committing(command: list[str]) -> str | Failure:
if command[3:4] == ["commit"]:
checkout.answers[("git", "rev-parse", "HEAD")] = "f00d\n"
return run(command)
checkout.__call__ = committing # type: ignore[method-assign]
return checkout, folder
@staticmethod
def thread(path: str, last: str, resolved: bool = False) -> dict[str, object]:
return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}}
def test_malformed_finish_flags_dont_run_anything(self):
for flags in (["--finish"], ["--finish", "abc"], ["--changelog", "Bullet."], ["12"], ["--finish", "--no-changelog"], ["--finish", "7", "--changelog"], ["--finish", "7", "--no-changelog", "--changelog", "Bullet."]):
with self.subTest(flags):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["merge", *flags], checkout, checkout.config), Failure(USAGE))
self.assertEqual(checkout.ran, [])
def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self):
checkout = self.moved(Checkout(GITHUB, open=True))
self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]])
self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS))
def test_a_conflict_with_the_default_branch_leaves_it_unmerged_naming_the_files_and_frees_the_queue(self):
checkout = self.moved(Checkout(GITHUB, open=True))
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n"
failed = merged(checkout.__call__, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason)
self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True))
self.assertTrue(queue_is_free())
def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"]
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]])
self.assertEqual(changes(checkout)[-4:], [
["git", "-C", folder, "add", "--", *files],
["git", "-C", folder, "commit", "--quiet", "-m", "[7] Finish item 7 in the plan", "--", *files],
self.PUSHED,
["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"],
])
def test_the_flags_reach_todo_item_as_given(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers.update({(self.TODO_ITEM, "show", "8"): "From todo.md:\n", (self.TODO_ITEM, "show", "9"): "From todo.md:\n"})
self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]])
def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False)
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.")
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"])
self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"])
def test_each_item_the_plan_no_longer_holds_is_named(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False)
checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8")
self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, checkout.config, finishes=[["7"], ["8"]])))
def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
run, shows = checkout.__call__, []
def run_whose_second_show_fails(command: list[str]) -> str | Failure:
shows.extend([command] if command[1:2] == ["show"] else [])
return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command)
self.assertEqual(merged(run_whose_second_show_fails, checkout.config, finishes=[["7"]]), Failure("todo-item show 7: unreadable"))
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self):
for clean in ("status", "records"):
with self.subTest(clean):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
if clean == "status":
checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n"
else:
checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"})
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
merged(checkout.__call__, checkout.config, finishes=[["7"]])
self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]])
def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self):
for failing in ("show", "finish"):
with self.subTest(failing):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout")
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout"))
self.assertNotIn(self.PUSHED, checkout.ran)
def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self):
_, folder = self.with_plan(Checkout(GITHUB, open=True))
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"]):
with self.subTest(failing):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
run = checkout.__call__
def failing_run(command: list[str]) -> str | Failure:
asked = ["<plan>" if part == folder else part for part in command]
return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command)
self.assertEqual(merged(failing_run, checkout.config, finishes=[["7"]]), Failure("that step failed"))
self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"])
def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self):
checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True)))
checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7")
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
self.assertEqual(changes(checkout), [MERGE, self.PUSHED])
def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"])
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge).")
self.assertLess(commit(), checkout.ran.index(OWED))
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run")
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
self.assertEqual(changes(checkout)[-1], self.PUSHED)
def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
free: dict[str, bool] = {}
def run(command: list[str]) -> str | Failure:
if command == GH_CHECKS:
free.setdefault("during the checks", queue_is_free())
return checkout(command)
self.assertEqual(merged(run, checkout.config, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).")
self.assertEqual(free, {"during the checks": False, "waiting for the approval": True})
self.assertEqual(checkout.ran.count(FETCH), 2)
def test_a_reviewers_comment_ends_the_wait_naming_its_file_until_the_author_answers_or_it_is_resolved(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED"]
checkout.threads = [self.thread("bin/asked.py", "reviewer"), self.thread("bin/answered.py", "worker"), self.thread("bin/resolved.py", "reviewer", resolved=True)]
slept: list[float] = []
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual((slept, changes(checkout)), ([], []))
checkout.threads = checkout.threads[1:]
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.threads = [self.thread("bin/asked.py", "reviewer")]
failed = merged(checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual(changes(checkout), [])
def test_review_threads_it_cannot_read_leave_it_unmerged(self):
for answer, reason in ((Failure("gh api graphql failed"), "gh api graphql failed"), ("not json", "gh api graphql printed no review threads: not json"), ("{}", "gh api graphql printed no review threads: {}")):
with self.subTest(answer):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({tuple(WAITS): "true\n", tuple(GH_THREADS): answer})
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertEqual(merged(checkout, checkout.config, lambda seconds: None), Failure(reason))
self.assertEqual(changes(checkout), [])
def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self):
history = "/checkout/docs/comprehension-history.md"
ruled = ["git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", history]
since = ["git", "rev-list", "--count", "bead..origin/main"]
for name, answers, stops in (
("moved since the ruling", {tuple(ruled): "bead\n", tuple(since): "2\n"}, True),
("ruled at this head", {tuple(ruled): "bead\n", tuple(since): "0\n"}, False),
("no ruling", {tuple(ruled): "\n"}, False),
):
with self.subTest(name):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers})
done = merged(checkout.__call__, checkout.config)
self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done)
self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_history_outside_the_checkout_or_one_git_cannot_read_never_stops_or_fails_the_merge_wrongly(self):
ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md")
checkout = Checkout(GITHUB, open=True)
checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n"
self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertNotIn("log", [command[1] for command in checkout.ran])
for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")):
with self.subTest(failing):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"})
checkout.answers[failing] = Failure("git failed")
self.assertEqual(merged(checkout.__call__, checkout.config), Failure("git failed"))
def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self):
with self.assertRaises(ValueError):
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "12", lambda seconds: None):
self.assertFalse(queue_is_free())
raise ValueError
self.assertTrue(queue_is_free())
def test_a_queue_another_pull_request_holds_for_half_an_hour_leaves_it_unmerged_naming_the_holder(self):
checkout = Checkout(GITHUB, open=True)
slept: list[float] = []
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "1234", lambda seconds: None):
pass
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None):
failed = merged(checkout, checkout.config, slept.append)
self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again"))
self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, []))
def test_a_queue_freed_while_it_waits_gives_it_the_turn(self):
checkout = Checkout(GITHUB, open=True)
holder = contextlib.ExitStack()
holder.enter_context(turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None))
self.assertEqual(merged(checkout, checkout.config, lambda seconds: holder.close()), "Merged pull request #12 (merge).")
def test_a_queue_it_cannot_open_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n"
self.assertEqual(merged(checkout, checkout.config), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
self.assertEqual(checkout.acted(), [])
class Clean(unittest.TestCase):
+1 -49
View File
@@ -1,60 +1,12 @@
"""The pure choices the preflight's steps act on."""
import pathlib
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
from failure import Failure
from chunk_preflight.gathered import Forge, NoItem, Plan
from release_plan.todo_table import NoItemsTable
from plan_store import stores as plan_stores
from release_plan.release import version
from chunk_preflight.gathered import Forge
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
def cut_name(cut: LastCut) -> str | None:
"""How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut."""
if cut.tag is not None:
return None if isinstance(cut.tag, Failure) else cut.tag
headed = dated_cut(cut.tag, cut.changelog)
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
def plan_name(default: str, outside: str | None) -> str:
"""How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout."""
return outside if outside else f"{default}'s todo.md"
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None) -> Plan | NoItem:
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none. branch is the project's `branch` template."""
where = plan_name(default, outside)
if isinstance(todo, NoItemsTable):
return NoItem(f"{where} holds no items table.")
if isinstance(todo, Failure):
return NoItem(f"{where} cannot be read: {todo.reason}.")
found = todo.items
if isinstance(cut.tag, Failure):
return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.")
named = cut_name(cut)
last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet"
pick = chunk_item(found, cut)
if isinstance(pick, Cut):
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.")
if isinstance(pick, Unknown):
return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
if isinstance(pick, ReviewDue):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
if isinstance(pick, ReadyToCut):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
first = pick.item
if first is None:
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
return Plan(found, first, f"{first.tagline}\n\n{first.detail}".strip(), branch)
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"):
+19 -8
View File
@@ -1,12 +1,13 @@
"""The lines the preflight prints, stated from what it gathered."""
from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
from plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
from touch_predictions.beside import chunks_beside
from chunk_preflight.choices import cut_name, PULLS_LIST
from release_plan.next_chunk import cut_name, NextChunk, NoItem
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran
from text_files.markdown_text import listed, quoted
from release_plan.release import version
from chunk_preflight.choices import PULLS_LIST
from plan.release import version
# CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt.
@@ -45,7 +46,8 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
first = item.plan.first
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
return [
f"- The earliest release in {plan}: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
f"- The {'next release, after the last cut, that ' + plan + ' names' if item.plan.carried else 'earliest release in ' + plan}: {version(first.release)}. {'The item this chunk starts from, named with --item' if item.plan.named else 'Its first item that does not wait'}: item {first.id}, {levels(first)}.",
*carried_lines(item.plan),
f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
*bundled(item.plan),
@@ -57,7 +59,16 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
]
def joining_details(plan: Plan) -> list[str]:
def carried_lines(plan: NextChunk) -> list[str]:
"""What the worker does about the items of a release someone cut while it held them."""
over = plan.carried
if over is None:
return []
items, count, them = (f"Items {listed([str(id_) for id_ in over.ids], 'and')} are", "they count", "them") if len(over.ids) > 1 else (f"Item {over.ids[0]} is", "it counts", "it")
return [f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."]
def joining_details(plan: NextChunk) -> list[str]:
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
joining = bundle_candidates(plan.items, plan.first)
if not joining:
@@ -90,7 +101,7 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch]
def bundled(plan: Plan) -> list[str]:
def bundled(plan: NextChunk) -> list[str]:
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
if ships_alone(first):
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
@@ -100,7 +111,7 @@ def bundled(plan: Plan) -> list[str]:
return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
def beside(plan: Plan) -> list[str]:
def beside(plan: NextChunk) -> list[str]:
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
first = plan.first
found = chunks_beside(plan.items, first)
+3 -25
View File
@@ -4,9 +4,8 @@ import pathlib
import typing
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release_standing import LastCut
from project_config import templates
from release_plan.next_chunk import NextChunk, NoItem
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
Forge = typing.Literal["gh", "tea"]
@@ -20,27 +19,6 @@ class Ran:
stderr: str
@dataclasses.dataclass(frozen=True)
class Plan:
"""The default branch's plan items, each with its detail, and `first`: the item the next chunk takes first."""
items: list[Item]
first: Item
# first's tagline and detail.
text: str
branch_template: str
@property
def branch(self) -> str:
"""The branch first's worktree is on."""
return templates.branch_of(self.branch_template, self.first.id)
@dataclasses.dataclass(frozen=True)
class NoItem:
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
why: str
@dataclasses.dataclass(frozen=True)
class Worktree:
path: pathlib.Path
@@ -60,7 +38,7 @@ class NamedPath:
@dataclasses.dataclass(frozen=True)
class ItemFacts:
"""What the preflight found or made for the plan's first item."""
plan: Plan
plan: NextChunk
worktree: Worktree | Failure
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
pulls: tuple[Forge, Ran | Failure] | None
@@ -79,7 +57,7 @@ class Gathered:
cut: LastCut
# What was found or made for the plan's first item; else why the plan names none.
item: ItemFacts | NoItem
# The plan that was read, as choices.plan_name names it.
# The plan that was read, as release_plan.next_chunk.plan_name names it.
plan: str
# Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout.
places: dict[str, str]
+27 -20
View File
@@ -1,6 +1,6 @@
"""Find the mechanical facts a chunk starts from, so its worker starts from them; with --worktree, also make its worktree.
usage: chunk-preflight [--worktree]
usage: chunk-preflight [--worktree] [--item <ID>]
Run it inside a project checkout. It fetches origin, when the checkout has that remote, and takes
origin's default branch, or else the local main or master. Without --worktree, it still fetches,
@@ -16,18 +16,21 @@ 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;
- the next release and its first item that does not wait, the item loop-claude routes on, with
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
- 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
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.
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.
Where the next release holds no item, it says so, naming it where todo.md named it since the cut:
its release review due where changes are unreleased (the ## Unreleased entries, or else the
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
such a commit counts only where its <release> is after the version under the dated heading.
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
Where todo.md files items under x.y.z or earlier, someone cut a release that still held them:
they count as the next release, the earliest after x.y.z that todo.md names or has named
since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release
already cut;
- with --worktree, the item's worktree: a sibling of the checkout named <checkout>-<branch>,
each / of the branch a dash, on the branch the config's `branch` template names, which is
@@ -63,7 +66,7 @@ running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT se
stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of
those four tools, --worktree or not.
Exit 1, saying why, on any argument other than --worktree, -h or --help, on a
Exit 1, saying why, on any argument other than --worktree, --item with an ID, -h or --help, on a
CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, when git cannot start or finds no
checkout or no default branch, or when no config names the checkout or its config cannot be read.
"""
@@ -75,11 +78,12 @@ import typing
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command, worktree_add, worktree_on
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran, Worktree
from chunk_preflight.choices import forge_of, pulls_command, worktree_add, worktree_on
from chunk_preflight.facts import JOINING_DETAILS, render
from project_config.main import located
from release_plan.named_code import named_paths
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
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -90,16 +94,19 @@ TIMEOUT = 60
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
# The flag that makes the item's worktree and runs TOOLS in it. Three readers seated as the README's audience picked it 2-1 over --start.
WORKTREE = "--worktree"
# The flag that names the chunk's item. Three readers seated as the README's audience picked it 3-0 over --for, --start and a bare ID.
ITEM = "--item"
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip().format(timeout=TIMEOUT, JOINING_DETAILS=JOINING_DETAILS))
return 0
if argv not in ([], [WORKTREE]):
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}]", file=sys.stderr)
rest = [arg for arg in argv if arg != WORKTREE]
if len(argv) - len(rest) > 1 or not (rest == [] or (len(rest) == 2 and rest[0] == ITEM and re.fullmatch(r"[0-9]+", rest[1], re.ASCII))):
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}] [{ITEM} <ID>]", file=sys.stderr)
return 1
printed = run(env.get(TIMEOUT_SETTING), argv == [WORKTREE])
printed = run(env.get(TIMEOUT_SETTING), WORKTREE in argv, int(rest[1]) if rest else None)
if isinstance(printed, Failure):
print(printed.reason, file=sys.stderr)
return 1
@@ -107,13 +114,13 @@ def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
return 0
def run(setting: str | None, make: bool) -> list[str] | Failure:
"""The preflight's lines, given the setting TIMEOUT_SETTING holds and whether to make the item's worktree; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
def run(setting: str | None, make: bool, item_id: int | None = None) -> list[str] | Failure:
"""The preflight's lines, given the setting TIMEOUT_SETTING holds, whether to make the item's worktree, and the ID --item names; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
timeout = seconds(setting)
if isinstance(timeout, Failure):
return timeout
root = top()
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make)
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make, item_id)
def seconds(setting: str | None) -> float | Failure:
@@ -125,7 +132,7 @@ def seconds(setting: str | None) -> float | Failure:
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Failure:
def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | None) -> list[str] | Failure:
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
default = default_branch(stale_ok=True, timeout=timeout)
if isinstance(default, Failure):
@@ -136,14 +143,14 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
return config
outside = None if config.tracked("plan") else config.plan_label
held = project_plan(config, ref, str(root))
plan = planned(held.todo, held.cut, ref, config.branch, outside)
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)
# 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))
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
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}.")
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 [])
+65 -5
View File
@@ -10,15 +10,17 @@ import unittest
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 chunk_preflight import choices
from failure import Failure
from chunk_preflight.choices import forge_of, worktree_add
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
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 import next_chunk
from chunk_preflight.facts import open_pulls, render
from plan_store.stores import plan_of
from plan_store.todo_md import plan_of
from project_config.test_project_config import write_config
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -54,6 +56,10 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# Item 9's row, the only one under release 0.3.0.
NINTH = "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# A plan whose release 0.2.0 holds item 3 alone, before release 0.3.0's item 9.
SHIPPED_BUT_3 = TODO[:TODO.index("| 5 |")] + "| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n" + NINTH
# An items table that holds no row.
EMPTY = TODO[:TODO.index("| 5 |")]
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
@@ -315,6 +321,29 @@ class ChunkPreflightTool(unittest.TestCase):
self.assertFalse((repo.temp / "proj-item-3").exists())
self.assertNotIn("item-3", repo.git(repo.root, "branch", "--list"))
def test_item_names_the_item_the_chunk_starts_from_in_place_of_the_plans_next(self):
repo = Repo(self)
for args in (["--item", "7"], ["--worktree", "--item", "7"], ["--item", "7", "--worktree"]):
with self.subTest(args):
done = repo.preflight(*args)
self.assertEqual((done.returncode, done.stderr), (0, ""))
self.assertIn("0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", done.stdout)
self.assertNotIn("Its first item that does not wait", done.stdout)
self.assertTrue((repo.temp / "proj-item-7").is_dir())
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_item_names_no_item_where_the_plan_no_longer_holds_it(self):
done = Repo(self).preflight("--worktree", "--item", "4")
self.assertEqual((done.returncode, done.stderr), (0, ""))
self.assertIn("- No plan item: origin/main's todo.md holds no item 4, the one --item names; it may have shipped. No worktree was made.", done.stdout)
def test_exits_1_on_an_item_that_is_no_id(self):
for args in (["--item"], ["--item", "x"], ["--item", "7", "8"]):
with self.subTest(args):
done = Repo(self).preflight(*args)
self.assertEqual((done.returncode, done.stdout), (1, ""))
self.assertIn(f"unknown arguments {' '.join(args)}; usage: chunk-preflight [--worktree] [--item <ID>]", done.stderr)
def test_exits_1_on_an_argument_other_than_worktree(self):
done = Repo(self).preflight("--start")
self.assertEqual(done.returncode, 1)
@@ -361,8 +390,8 @@ class ChunkPreflightTool(unittest.TestCase):
def planned(todo, *rest):
"""choices.planned for the plan a todo.md's text holds, or for the Failure given."""
return choices.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
"""next_chunk.planned for the plan a todo.md's text holds, or for the Failure given."""
return next_chunk.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
def item_facts(todo=TODO, **fields):
@@ -387,6 +416,10 @@ class Render(unittest.TestCase):
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
self.assertNotIn("item 8,", said)
def test_says_the_item_was_named_with_item(self):
said = rendered(item_facts(plan=planned(TODO, CUT, "origin/main", BRANCH, None, 7)))
self.assertIn("origin/main's todo.md: 0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", said)
def test_states_each_fact_once_with_the_paths_between_the_worktree_and_the_open_pull_requests(self):
lines = render(gathered(item_facts()))
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files and plan at", "- The project's config sets", "- Open pull requests from item-3"])
@@ -527,6 +560,14 @@ class Plans(unittest.TestCase):
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main", BRANCH).why)
self.assertIn("## Details holds a fenced code block", planned(TODO + "```\n", CUT, "origin/main", BRANCH).why)
def test_takes_the_item_item_names_even_one_that_waits_or_says_it_left_the_plan(self):
# Item 7 waits for item 3, which another chunk runs.
named = planned(TODO, CUT, "origin/main", BRANCH, None, 7)
self.assertEqual((named.first.id, named.first.tagline, named.named), (7, "**Do the thing after.**", True))
self.assertTrue(named.text.startswith("**Do the thing after.**"), named.text)
self.assertFalse(planned(TODO, CUT, "origin/main", BRANCH).named)
self.assertEqual(planned(TODO, CUT, "origin/main", BRANCH, None, 4), NoItem("origin/main's todo.md holds no item 4, the one --item names; it may have shipped."))
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
without = planned("", CUT, "origin/main", BRANCH).why
self.assertIn("origin/main", without)
@@ -576,8 +617,27 @@ class Plans(unittest.TestCase):
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main", BRANCH).first.id, 9)
def test_counts_the_items_of_a_release_already_cut_as_the_next_releases_and_says_to_move_them(self):
plan = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH)
self.assertEqual((plan.first.id, plan.first.release), (3, (0, 3, 0)))
self.assertEqual({item.release for item in plan.items}, {(0, 3, 0)})
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), (5, 3, 7, 8)))
said = rendered(dataclasses.replace(item_facts(), plan=plan), LastCut("v0.2.0", "", 4, []))
self.assertIn("- Items 5, 3, 7 and 8 are filed under a release already cut, so they count as release 0.3.0's, the next.", said)
self.assertIn("`~/.claude/bin/todo-item move`", said)
self.assertIn("- The next release, after the last cut, that origin/main's todo.md names: 0.3.0. Its first item that does not wait: item 3,", said)
self.assertNotIn("already cut", rendered(item_facts()))
def test_says_to_move_one_or_two_items_of_a_release_already_cut_in_the_singular_or_the_plural(self):
cut = LastCut("v0.2.0", "", 4, [])
for todo, ids, said in ((SHIPPED_BUT_3, (3,), "- Item 3 is filed under a release already cut, so it counts as release 0.3.0's, the next. Move it there"), (SHIPPED_BUT_3 + NINTH.replace("| 9 | 0.3.0 |", "| 4 | 0.1.0 |"), (3, 4), "- Items 3 and 4 are filed under a release already cut, so they count as release 0.3.0's, the next. Move them there")):
with self.subTest(ids=ids):
plan = planned(todo, cut, "origin/main", BRANCH)
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), ids))
self.assertIn(said, rendered(dataclasses.replace(item_facts(), plan=plan), cut))
def test_says_the_plan_files_items_under_a_release_already_cut(self):
why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
why = planned(TODO.replace(NINTH, ""), LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
self.assertIn("release 0.2.0", why)
self.assertIn("v0.2.0", why)
self.assertIn("not after", why)
+2 -2
View File
@@ -5,8 +5,8 @@ import re
import shlex
import typing
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "timeout", "uvx", "yarn"})
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run, uv run mutmut run or sudo docker build.
LAUNCHERS = frozenset({"bunx", "doas", "env", "nice", "npx", "pipx", "pnpm", "poetry", "run-heavy", "sudo", "time", "timeout", "uv", "uvx", "yarn"})
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
+6 -7
View File
@@ -3,7 +3,6 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import pathlib
import re
import shutil
import sys
import tempfile
@@ -13,11 +12,11 @@ from project_config.settings import DEFAULT_FLOOR
from git_cli.git_repo import default_ref, git
from deploy_release.deploy import deploy
from failure import Failure
from plan_store.stores import FilePlan
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from deploy_release import forge
from chunk_preflight.choices import forge_of
from release_plan.release import newest_tag, Release, version
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
from project_config import templates
@@ -119,9 +118,9 @@ 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."""
# 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.todo, Failure):
return Failure(f"todo.md on {ref} cannot be read: {plan.todo.reason}")
match chunk_item(plan.todo.items, plan.cut):
if isinstance(plan.plan, Failure):
return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}")
match chunk_item(plan.plan.items, plan.cut):
case ReadyToCut(release=release) if release is not None:
return release
case ReadyToCut():
@@ -211,7 +210,7 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
return added
changelog = worktree / "CHANGELOG.md"
renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE)
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
changelog.write_text(renamed)
+1 -1
View File
@@ -1,7 +1,7 @@
"""Move a checkout to this repo's newest release, as a bare `deploy-release` does."""
from failure import Failure
from git_cli.git_repo import git
from release_plan.release import newest_tag, parsed, tagged
from plan.release import newest_tag, parsed, tagged
from text_files.markdown_text import sections
+1 -1
View File
@@ -126,7 +126,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=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=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)
+22 -14
View File
@@ -7,11 +7,11 @@ from larv_review.plan 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
from plan_store.stores import file_plan, store as plan_store
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
from larv_review.scoring import floor_step, means, under_floor
from record_store.held import Held
from project_config.main import located
from release_plan import plan_file
from plan_store.stores import store as plan_store
from record_store.stores import RecordStore, store
from larv_review.scoring_setup import removed_setup
@@ -84,10 +84,11 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None:
if todo is None:
# A plan in Jira is ranked by Jira's backlog, which no score moves.
return None
ranked = plan_file.rank_file(todo, config)
plan = file_plan(config, todo)
ranked = plan.rank()
if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
for line in plan_file.report_lines(todo, ranked):
for line in plan.reported(ranked):
warn(line)
if ranked.under_bar:
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
@@ -145,22 +146,29 @@ def read_agreement(home: pathlib.Path) -> str | Failure:
def history_file(home: pathlib.Path) -> tuple[RecordStore, str] | Failure:
"""The store the project's config names for its comprehension history, and the history's text, empty where there is none yet."""
held = held_history(home)
return held if isinstance(held, Failure) else (held[0], held[1].text)
def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure:
"""The store the project's config names for its comprehension history, and the history as it stands, with the version a write over it names."""
config = located(None, home)
if isinstance(config, Failure):
return config
history = store(config, "comprehension-history")
text = history.read()
return text if isinstance(text, Failure) else (history, text)
held = history.held()
return held if isinstance(held, Failure) else (history, held)
def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
"""Appends entry and returns the line the tool prints; a Failure where the history already holds an entry on what the seats read."""
read_history = history_file(home)
if isinstance(read_history, Failure):
return read_history
history, text = read_history
if recorded(text, read):
read_history = held_history(home)
return read_history if isinstance(read_history, Failure) else appended_to(*read_history, read, entry)
def appended_to(history: RecordStore, held: Held, read: str, entry: str) -> str | Failure:
"""Writes entry onto held, the history as history's store read it, over held's version; the line the tool prints, or why the entry isn't written."""
if recorded(held.text, read):
return Failure(f"{history.label} already holds an entry on {read}; record each ruling or run once")
if unwritten := history.write(appended(text, entry)):
return unwritten
return f"Appended to {history.label}."
written = history.write(appended(held.text, entry), held.version)
return written if isinstance(written, Failure) else f"Appended to {history.label}."
+5 -4
View File
@@ -1,13 +1,14 @@
import pathlib
import typing
from larv_review.plan import EMPTIED_WORDS, plan_reasons
from larv_review.plan import Emptied, plan_reasons
from review_rules.comprehension_history import entries
from failure import Failure
from git_cli.git_repo import file_at, git
from project_config.main import located
from release_plan.todo_table import NoItemsTable
from plan_store.stores import store as plan_store, PlanStore
from plan.todo_table import NoItemsTable
from plan_store.stores import store as plan_store
from plan_store.plans import PlanStore
from record_store.stores import store
@@ -48,7 +49,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st
def shortfall(reasons: list[str], recorded: int) -> Failure | None:
"""Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all."""
needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1
needed = 2 if any(isinstance(reason, Emptied) for reason in reasons) else 1
if recorded >= needed:
return None
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
+13 -10
View File
@@ -1,23 +1,27 @@
import pathlib
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, Unknown
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown
from failure import Failure
from larv_review.scoring import is_floor_item
from release_plan.todo_table import Item, NoItemsTable
from plan.todo_table import Item, NoItemsTable
from project_config.main import located
from release_plan.goals_file import OPTED_OUT
from plan_store.stores import Plan, PlanStore
from plan.goals_file import OPTED_OUT
from plan_store.plans import Plan, PlanStore
from plan_store import stores as plan_stores
from project_config.settings import ProjectConfig
from release_plan.release import Release, version
from plan.release import Release, version
from record_store import stores
from larv_review.unmeasured import unmeasured_cut
# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one.
# The words that end the reason a chunk empties a release; SKILL.md → "Second run" quotes them.
EMPTIED_WORDS = "with no plan item"
class Emptied(str):
"""The reason a chunk empties a release, which makes it due two scoring runs; a chunk with only other reasons is due one."""
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: frozenset[Release], unmeasured: str | None = None) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not.
@@ -34,8 +38,7 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
reasons.append(f"follows {unmeasured}")
for release in emptied(before, after, shipped, renamed):
if work_landed(release, shipped, landed_release):
# SKILL.md → "Second run" keys on this wording.
reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}")
reasons.append(Emptied(f"leaves release {version(release)} {EMPTIED_WORDS}"))
return reasons
@@ -49,7 +52,7 @@ def landed_towards(found: list[Item], cut: LastCut) -> Release | None | Failure:
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `release_standing.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
if isinstance(cut.tag, Failure):
return Failure(f"could not tell the next release: the default branch's tags cannot be read: {cut.tag.reason}")
upcoming = next_release(found, cut)
upcoming = next_release(standing_of(found, cut), cut)
if isinstance(upcoming, Unknown):
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
# Cut's release is the last cut's version or earlier, so no work lands towards it.
@@ -86,7 +89,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
if OPTED_OUT.search(decisions):
return []
held = project_plan(config, ref, checkout)
before = held.todo
before = held.plan
read = checkout_plan(plan_stores.store(config))
if isinstance(read, Failure):
return read
+3 -3
View File
@@ -1,8 +1,8 @@
"""The plan as a listing a reviewer reads with the Read tool, whatever store holds the plan."""
from failure import Failure
from release_plan.todo_table import Item
from plan_store.stores import PlanStore
from release_plan.release import version
from plan.todo_table import Item
from plan_store.plans import PlanStore
from plan.release import version
def plan_listing(plan: PlanStore) -> str:
+1 -1
View File
@@ -1,7 +1,7 @@
import decimal
from review_rules.comprehension_history import DIMENSIONS
from release_plan.todo_table import Item
from plan.todo_table import Item
# A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run.
FLOOR_ITEM = "Reach the comprehension floor:"
+18 -6
View File
@@ -15,18 +15,20 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
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 review_rules import comprehension_history
from project_config.test_project_config import configured
from larv_review.ruling import counted, ruling, split, surplus, votes
from larv_review.history_commands import decided, rerank
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from plan_store.stores import FilePlan
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from larv_review.scoring import floor_step, means, under_floor
from record_store.held import Held
from test_env import isolated_env
from release_plan.todo_table import Item, items, NoItemsTable
from plan.todo_table import Item, items, NoItemsTable
from release_plan.release_standing import LastCut
from larv_review.ruling_base import measured_commit
from record_store.fakes import MemoryStore
@@ -459,13 +461,23 @@ class LandedTowards(unittest.TestCase):
self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object"))
class AppendedTo(unittest.TestCase):
def test_writes_the_entry_over_the_version_the_history_was_read_at(self):
history = MemoryStore(label="history.md", version=5)
self.assertEqual(appended_to(history, Held("", "5"), "PR #2 at abcdef1\n", "## an entry\n"), "Appended to history.md.")
self.assertEqual(history.overs, ["5"])
class Shortfall(unittest.TestCase):
def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self):
self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8"))
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
emptied = ["leaves release 0.1.0 with no plan item"]
emptied = [Emptied("leaves release 0.1.0 with no plan item")]
floor = ["ships item 2, a floor item"]
# The type, not the words, makes a reason call two runs.
self.assertIn("owes 1 scoring run and", shortfall(["leaves release 0.1.0 with no plan item"], 0).reason)
self.assertIsInstance(scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())[0], Emptied)
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
self.assertIn("records 0:", shortfall(floor, -1).reason)
@@ -983,7 +995,7 @@ class LarvReviewTool(unittest.TestCase):
checkout = pathlib.Path(temp, "acme")
checkout.mkdir()
config = configured(self, checkout) / "config.toml"
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
(checkout / "todo.md").write_text("the owners' own notes\n")
self.enterContext(contextlib.chdir(checkout))
said: list[str] = []
@@ -1250,7 +1262,7 @@ class LarvReviewTool(unittest.TestCase):
credentials = self.config.parents[2] / "acme.env"
credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
credentials.chmod(0o600)
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\n')
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("cannot read the epic ABC-12", ran.stderr)
+1 -1
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from plan_store.stores import BLOCKED_BY
from plan.todo_table import BLOCKED_BY
from plan_store.contract import FIRST, SECOND
from plan_store.fakes import MemoryPlan
from larv_review.plan_listing import plan_listing
+2 -2
View File
@@ -1,10 +1,10 @@
"""The todo.md items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as todo.md scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
import re
from claude_code.entries import AssistantTurn, Entry, Text
from failure import Failure
from loop_claude.quotes import plain
from plan_store.stores import Plan
from plan_store.plans import Plan
from loop_claude.verdicts import TakenIn
# The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it.
+16 -6
View File
@@ -10,6 +10,7 @@ from claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
from model_routing.ladder import Rung
from loop_claude.direct_message import tell
from loop_claude import tmux
ANSWER_QUESTION = "answer the question above"
# TALK, what the human types at loop-claude's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
@@ -36,17 +37,26 @@ class Talked:
"""The human typed in the worker's claude session."""
def interrupt(question: str, answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
say(f"\n{question}", effects)
def interrupt(question: str, answer_here: bool, session: WorkerSession, window: tmux.Window, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human, in window, and returns their answer. While it waits, the window's name ends in tmux.WAITS, and the bell it rings shows in tmux's status bar. The answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
# The bell ends the question's line, so it rings once the question can be read.
say(f"\n{question}{tmux.BELL}", effects)
on_terminal = effects.on_terminal()
if on_terminal:
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
tmux.mark(window, True, effects.tmux)
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
return stop
tell(f"loop-claude in {session.root} asks, in the tmux window {window.target}:\n\n{question}", effects)
answer = needs_terminal(ANSWER_QUESTION, on_terminal) or answered(answer_here, session, effects)
# A loop that stops unanswered leaves the mark on its window.
if not isinstance(answer, Stop):
tmux.mark(window, False, effects.tmux)
return answer
def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
"""The human's answer, as interrupt returns it."""
answer = typed_answer(effects) if answer_here else TALK
if answer != TALK:
return answer
+1 -1
View File
@@ -31,7 +31,7 @@ INTERRUPT_RULES = (
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals need changing\n"
"- it flags that the plan in todo.md or the task itself is unclear or missing, and recommends no way on\n\n"
"- it flags that the plan or the task itself is unclear or missing, and recommends no way on\n\n"
"interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, "
"so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and "
"recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even "
+11 -6
View File
@@ -12,7 +12,7 @@ from claude_code.transcript import Typed
# Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises.
QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the plan or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
# How review_launches names the reviews: "each reviewer" covers every pass with an agent.
EACH_REVIEWER = "each reviewer"
@@ -23,7 +23,7 @@ THE_SECURITY_PASS = "the security pass's subagent"
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).
NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it'
@@ -33,7 +33,7 @@ def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
@@ -45,7 +45,7 @@ def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
def recount(route: Route) -> str:
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
def preflight_facts(printed: str) -> str:
@@ -53,6 +53,11 @@ def preflight_facts(printed: str) -> str:
return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}"
def held_by_others(items: list[int]) -> str:
"""Keeps a fresh worker off the plan items the project's other chunks hold, running or stopped."""
return f"\n\nOther chunks of this project, running or stopped, hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those items out of this chunk, even where the facts above list them as items that may join it."
def preflight_failed(reason: str) -> str:
"""Has the worker find the facts chunk-preflight would have, its worktree among them."""
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
@@ -72,8 +77,8 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]:
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
def markdown_launch(choice: ReviewChoice) -> list[str]:
+8 -5
View File
@@ -17,13 +17,14 @@ from loop_claude.routing import judge_rung, next_route, step_up, StepUp
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import last_spent
from transcript_archive import outcomes
from plan_store.stores import Plan
from plan_store.plans import Plan
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from loop_claude.cycle import spend
from loop_claude.stop import Stop
from loop_claude.tmux import Window
from model_routing import worker_rungs
@@ -50,10 +51,12 @@ class Cycle:
route: Route
session: Session
task: str
# todo.md on the default branch as the cycle starts, which scores the items the worker names.
todo: Plan | Failure
# The plan on the default branch as the cycle starts, which scores the items the worker names.
plan: Plan | Failure
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
# The tmux window the loop runs in, which an interrupt marks.
window: Window
@dataclasses.dataclass(frozen=True)
@@ -157,7 +160,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
if isinstance(verdict, Stop):
return verdict
if not isinstance(verdict, Finished):
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.plan))
if not isinstance(verdict, Interrupt | QuotedAnswer):
return Ruled(verdict)
annotation = annotation_of(cycle, transcript_path, entries, verdict.judged)
@@ -198,7 +201,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.effects)
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.window, cycle.effects)
match answer:
case Stop():
return answer
-46
View File
@@ -1,46 +0,0 @@
"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
import dataclasses
import os
import pathlib
from failure import Failure
from machine_load.slots import first_free_slot
from loop_claude.loop.reload import LoopRun
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from claude_code.session import Session, session_named, session_open
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
SLOTS = ".local/state/loop-claude"
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
MOST = 64
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
folder = home / SLOTS / key
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
try:
folder.mkdir(parents=True, exist_ok=True)
taken = first_free_slot(folder, order)
except OSError as failure:
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
if taken is None:
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
slot, fd = taken
os.set_inheritable(fd, True)
return slot
def session_name(key: str, slot: int) -> str:
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
key = project_key(loop_run.root, paths.home)
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
if isinstance(slot, Failure):
return slot
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)
+26 -28
View File
@@ -7,12 +7,14 @@ from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELE
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.routing import first_route, kept, routed_item
from plan_store.stores import held_at, Plan, store as plan_store
from release_plan.todo_table import Item
from loop_claude.loop.chunk_windows import held_beside, item_of
from chunk_preflight.main import ITEM
from plan.todo_table import Item
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import latest_worker
from project_config.main import located
from loop_claude.loop.this_loop import Loop
from plan_store.plans import Plan
from loop_claude.cycle import prompts
from model_routing.route import Route, route_from
from claude_code.session import session_open, transcript_file
@@ -21,17 +23,12 @@ from claude_code.session import session_open, transcript_file
ORIGIN_TIMEOUT = 60
def fetched_todo(loop: Loop) -> Plan | Failure:
"""The plan, which scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which scoring the items doesn't need. Where it can't be read or scored, it says why."""
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
todo: Plan | Failure = config
else:
todo = ref if isinstance(ref, Failure) else held_at(ref, plan_store(config), loop.root, loop.effects.git)
if isinstance(todo, Failure):
say(f"the items the worker names lift no rung: {todo.reason}", loop.effects)
return todo
def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Failure:
"""The plan, which scores the items a chunk takes, from what the default branch holds; where it can't be read or scored, it says why."""
plan = default.plan if isinstance(default, DefaultPlan) else default
if isinstance(plan, Failure):
say(f"the items the worker names lift no rung: {plan.reason}", effects)
return plan
def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
@@ -58,38 +55,39 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
return route
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
facts = "" if session_open(loop.session) else chunk_facts(loop)
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]:
"""The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
fresh = not session_open(loop.session)
return chunk_facts(loop) if fresh else "", fetched_plan(loop, fresh)
def chunk_facts(loop: Loop) -> str:
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
if done.returncode:
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
return prompts.preflight_facts(done.stdout.strip())
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold."""
item = item_of(loop.window.name)
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root)
facts = prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else prompts.preflight_facts(done.stdout.strip())
held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects)
return facts + (prompts.held_by_others(held) if held else "")
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. It says UNSEEN_RELEASES for such a plan."""
def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle."""
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
return config
if config.tracked("plan") is None:
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)
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
"""The item that routes a chunk, release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
if isinstance(plan, Failure):
item: Item | Failure | None = plan
else:
item = routed_item(plan.todo, plan.cut)
item = routed_item(plan.plan, plan.cut, window_item)
if isinstance(item, Failure):
say(f"routing on the project's rung: {item.reason}", effects)
return None
+178
View File
@@ -0,0 +1,178 @@
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
import contextlib
import dataclasses
import fcntl
import pathlib
import re
import typing
from touch_predictions.beside import Beside, chunks_beside
from loop_claude.cycle import chunk_items
from git_cli.git_repo import default_ref
from loop_effects.effects import Effects, say
from failure import Failure
from project_config.main import located
from loop_claude.loop.reload import LoopRun
from release_plan.next_chunk import NextChunk, NoItem, planned
from touch_predictions.prediction import overlaps, predicted, Touches
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from release_plan.release_standing import project_plan
from claude_code.transcript import read_transcript
from claude_code.session import Session, session_named, transcript_file
from loop_claude import tmux
# Under the home folder, a folder per project key holds LOCK.
STATE = ".local/state/loop-claude"
# The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together don't start a chunk twice.
LOCK = "starting"
# The flag that tells the loop in a window its chunk, as `--chunk item-372`. Nobody types it, so no panel picked it.
CHUNK_FLAG = "--chunk"
# The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan.
NO_ITEM = "no-item"
# Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched.
FETCH_TIMEOUT = 60
# The prefix of the variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name.
HANDED = "LOOP_CLAUDE_"
def window_name(item_id: int) -> str:
return f"item-{item_id}"
def item_of(chunk: str) -> int | None:
"""The ID of the plan item a chunk starts from; None for NO_ITEM."""
named = re.fullmatch(r"item-([0-9]+)", chunk)
return int(named[1]) if named else None
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts)
@contextlib.contextmanager
def starting(home: pathlib.Path, key: str) -> typing.Iterator[None]:
"""Holds the project's LOCK. Raises OSError where the file cannot be opened or locked."""
folder = home / STATE / key
folder.mkdir(parents=True, exist_ok=True)
with open(folder / LOCK, "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
"""The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from."""
held: set[int] = set()
for chunk in chunks:
held.update(filter(None, [item_of(chunk)]))
transcript = transcript_file(chunk_session(key, chunk, claude_code_transcripts))
entries = read_transcript(transcript) if transcript else []
held.update([] if isinstance(entries, Failure) else chunk_items.named(entries))
return held
@dataclasses.dataclass(frozen=True)
class Room:
"""What a project's windows leave room for, under its limit of chunks at once."""
# The chunks whose windows run.
running: list[str]
# The chunks whose windows are dead: their loop stopped or failed, and the window keeps its last lines and its items.
stopped: list[str]
# The stopped chunks to start again, before any chunk from the plan.
restart: list[str]
# How many chunks from the plan may start beside them.
left: int
def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room:
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's loop-claude <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's loop-claude <task>, restarts one."""
running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)]
# Below 0 where the config lowered parallel-chunks while more chunks ran.
room = max(limit - len(running), 0)
stopped = [window.name for window in windows if window.dead]
restart = [] if leaving else stopped[:room]
return Room(running, stopped, restart, room - len(restart))
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):
return [] if running or room < 1 else [NO_ITEM]
beside = chunks_beside(plan.items, plan.first)
picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])]
details = {item.id: item.detail for item in plan.items}
# chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing.
theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details]
free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)]
return [window_name(item_id) for item_id in free][: max(room, 0)]
def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool:
"""Whether a prediction overlaps none of theirs; not where one of them is missing or unreadable, unless theirs is empty."""
return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs))
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure:
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
config = located(root, home)
if isinstance(config, Failure):
return config
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT)
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
if isinstance(ref, Failure):
return ref
held = project_plan(config, ref, root, effects.git)
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 plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure says why a chunk could not start; those before it run."""
config = located(loop_run.root, paths.home)
if isinstance(config, Failure):
return config
key = project_key(loop_run.root, paths.home)
session = tmux.session_name(key)
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
try:
with starting(paths.home, key):
windows = tmux.listed(session, effects.tmux)
if windows and (owned := tmux.owner(session, effects.tmux)) != loop_run.root:
return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders")
room = room_of(windows, loop_run.chunk, leaving, config.parallel_chunks)
chunks = list(room.restart)
if room.left:
plan = next_plan(loop_run.root, paths.home, effects)
if isinstance(plan, Failure):
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
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, key, paths.claude_code_transcripts)
chunks += [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.stopped]
for chunk in chunks:
stale = [window for window in windows if window.name == chunk and window.dead]
for window in stale:
tmux.close(window, effects.tmux)
windows = [window for window in windows if window not in stale]
command = [str(launcher), CHUNK_FLAG, chunk, loop_run.task]
if failed := tmux.start_window(tmux.Window(session, chunk, ""), loop_run.root, handed, command, not windows, effects.tmux):
return failed
windows.append(tmux.Listed(chunk, "", False))
return chunks
except OSError as failure:
return Failure(f"cannot lock {paths.home / STATE / key / LOCK}: {failure.strerror}")
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
"""The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it."""
key = project_key(root, paths.home)
wait_for_starts(paths.home, key)
others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk]
return sorted(held_items(others, key, paths.claude_code_transcripts))
def wait_for_starts(home: pathlib.Path, key: str) -> None:
"""Returns once no loop of the project is starting windows: start_chunks holds LOCK while it starts them. Where the lock cannot be taken, it returns at once."""
with contextlib.suppress(OSError), starting(home, key):
pass
+48 -15
View File
@@ -3,14 +3,16 @@ import pathlib
import typing
from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed
from loop_claude.loop.chunk_start import archived_route, chunk_start, plan_item, routed, scored_plan
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, item_of, start_chunks
from loop_claude.loop.close import closed_cycle
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.verdicts import Finished
from loop_claude.project.model_choice import get_or_ask_models
from git_cli.git_repo import Git
from loop_claude.loop.usage import HELP
@@ -20,9 +22,9 @@ from transcript_archive.project_key import project_key
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from loop_claude.loop.chunk_slot import slotted
from loop_claude.stop import Stop
from loop_claude.direct_message import tell
from loop_claude import tmux
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -35,8 +37,8 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
raise
if stop.reason:
say(stop.reason, effects, stdout=not stop.code)
# Every stop but the human's own Ctrl-C and the help is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help.
if stop.code != 130 and stop.reason != HELP:
# Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on.
if stop.reason not in ("", HELP):
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
return stop.code
@@ -45,12 +47,18 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
loop_run = loop_run_from(argv, cwd, effects)
if isinstance(loop_run, Stop):
return loop_run
# Before anything starts: a worktree, a claude session or a tmux window.
if reason := tmux.unusable(effects.tmux):
return Stop(1, reason)
if loop_run.chunk is None:
return windows_opened(loop_run, env, paths, launcher, effects)
pane = env.get("TMUX_PANE")
if not pane:
return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude <task>")
baseline = fingerprint(launcher)
held = slotted(loop_run, paths)
if isinstance(held, Failure):
return Stop(1, held.reason)
loop_run, session = held
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
key = project_key(loop_run.root, paths.home)
window = tmux.Window(tmux.session_name(key), loop_run.chunk, pane)
loop = Loop(root=loop_run.root, session=chunk_session(key, loop_run.chunk, paths.claude_code_transcripts), window=window, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := exec_if_edited(loop, baseline, loop_run):
return stop
@@ -68,6 +76,31 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
# Off the ladder the worker runs on the project's model itself, which its route names.
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
return stop
if isinstance(concluded.verdict, Finished):
return handed_on(loop_run, loop)
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects) -> Stop:
"""What the loop-claude the human runs does: starts 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_chunks(loop_run, False, paths, env, launcher, effects)
if isinstance(started, Failure):
return Stop(1, started.reason)
session = tmux.session_name(project_key(loop_run.root, paths.home))
say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now, so `{loop_run.task}` started in no new window", effects, stdout=True)
if not effects.on_terminal():
say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True)
return Stop(0, "")
shown = tmux.show(session, "TMUX" in env)
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "")
def handed_on(loop_run: LoopRun, loop: Loop) -> Stop:
"""The stop of a loop whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits."""
started = start_chunks(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
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)
return Stop(0, "")
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
@@ -89,14 +122,13 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
return Stop(1, ladder.reason)
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(loop)
facts, default = chunk_start(loop)
project = ladder.project_rung(models.worker)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), item)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects))
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
if ladder_file != SHIPPED:
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
todo = fetched_todo(loop)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
@@ -107,11 +139,12 @@ def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv)
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == CHUNK_FLAG else (None, argv)
task = " ".join(words)
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, HELP)
root = checkout_root(cwd, effects)
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
return root if isinstance(root, Stop) else LoopRun(0, root, task, "", chunk=chunk)
loop_run = decode_handed(argv[1]) if len(argv) == 2 else None
if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
+5 -3
View File
@@ -25,8 +25,8 @@ class LoopRun:
route: Route | None = None
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
# The project's slot this loop holds (chunk_slot.py); None until it takes one. A loop started before slots reloads with None, and so takes a slot then.
slot: int | None = None
# The chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the loop-claude the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so starts the project's windows; its open claude session, named for its slot, is left in the session picker (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window, …`).
chunk: str | None = None
class Unreadable(Exception):
@@ -40,8 +40,10 @@ def decode_handed(handed: str) -> LoopRun | None:
except ValueError:
return None
# A loop started before 0.11.0 hands the items loop-inbox listed; dropping them keeps it running across its reload.
# One started before chunks ran in tmux windows hands the slot it held.
if isinstance(fields, dict):
fields.pop("items_taken_in", None)
fields.pop("slot", None)
try:
return LoopRun(**decoded_fields(fields, LOOP_RUN_FIELDS, "cycle_number", "root", "task", "unfinished_evidence"))
except Unreadable:
@@ -77,7 +79,7 @@ def decoded_route(value: object) -> Route | None:
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "slot": lambda value: None if value is None else exactly(int)(value)}
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "chunk": lambda value: None if value is None else exactly(str)(value)}
def fingerprint(launcher: pathlib.Path) -> str:
+3
View File
@@ -5,6 +5,7 @@ import typing
from loop_effects.effects import Effects
from loop_state.paths import Paths
from claude_code.session import Session
from loop_claude.tmux import Window
@dataclasses.dataclass(frozen=True)
@@ -14,6 +15,8 @@ class Loop:
root: str
# The worker's session.
session: Session
# The tmux window the loop runs in.
window: Window
paths: Paths
env: typing.Mapping[str, str]
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
+55 -27
View File
@@ -8,13 +8,13 @@ as goals-and-audience: a file, or a Jira epic's description. `project-config goa
prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's
first worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md →
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's
chunk's plan items, or else the task, and never widen them. A judge then reads the transcript's
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md and ~/.claude/rules/*.md, then the .md files in the folder of review standards
the project's config sets, where they exist. It rules whether the chunk, the work of one PR, is
finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could
need is recorded: the premises or the records hold it, or the transcript shows the worker writing it
into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the worker made
into the premises, AGENTS.md, docs/decisions.md, the plan or a comment. A choice the worker made
that the premises or the records settle is not asked about. When the worker asks a question they
answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote
they do not hold word for word is dropped, and the question goes to the human. So does a question
@@ -22,35 +22,58 @@ asked again after its answer. A question the human answered earlier in the chunk
worker with that answer, unless the question quotes the words of the answer that leave it open. The
fourth question they answer in one cycle goes to the human too, with the quote. An unfinished chunk
resumes its session next cycle, and the worker is shown the passage the judge quoted as the work
remaining. The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C.
remaining. The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C,
either of which stops that one chunk.
Words: ~/.claude/CLAUDE.md → "Vocabulary".
loop-claude needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in its
own window of one tmux session per project, named loop-<key>, such as loop-claude-config. <key> is
the checkout's path relative to ~/code, or to / outside it, with a dash for each character other
than a letter, a digit, _ or -. The tmux session's @loop-root option names its checkout, and a
checkout whose key maps to a tmux session another checkout runs is refused. loop-claude <task>
starts the chunks that may start now, then attaches to the tmux session, or switches to it inside
tmux; detaching leaves the chunks running. Off a terminal it prints the command that attaches. Where
no chunk may start, it says so, and the task starts in no new window. At most parallel-chunks chunks
run at once, a whole number the project's config sets, 1 by default. The first starts from the
plan's next item, and each other from an item whose `Touches:` prediction overlaps neither one
before it nor an item another chunk holds (touch-predictions --help). A window is named for the item
its chunk starts from, as item-372; a chunk without a plan item, such as planning a release or its
release review, runs alone in the window no-item.
Each window runs a loop-claude for that one chunk, started with --chunk <window>, which nobody
types. As a chunk finishes, its loop starts each chunk that may start then, with the task it ran
itself, and exits, which closes its window. A loop that stops, by Ctrl-C, an exit below or a
failure, keeps its window, with its last lines, and its chunk keeps its items; the next loop-claude
<task> starts it again before any other. To stop every chunk, press Ctrl-C in each window. A chunk's
claude session is named "A <key> loop-claude <window>", so a rerun resumes a chunk left open, and is
deleted when the chunk finishes. A fresh worker is told the items the project's other chunks hold,
running or stopped: each one's own and those on its latest `Chunk items:` line, and leaves them out.
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question on its terminal, where the human answers it:
loop-claude prints the question in the chunk's window and rings its bell. Until it is answered the
window's name ends in " ?", as in "item-372 ?", which tmux's status bar shows. The human answers it
there:
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
chunk stays unfinished until the answer is recorded.
- /talk: opens the worker's session with `claude --resume` on the terminal, to read the diff or
discuss first. Once that claude exits, the judge rules on what was typed there.
- /talk: opens the worker's claude session with `claude --resume` on the terminal, to read the diff
or discuss first. Once that claude exits, the judge rules on what was typed there.
- Enter alone: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it.
While claude is open, Ctrl-C reaches it alone, and the loop goes on.
Where the project's config sets notifier, loop-claude also sends the human each question, each
release ready to cut and each stop as a DM, as bin/notify sends it. Two stops are
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
A release ready to cut opens that claude session on the terminal at once, since only the human may
cut it. While claude is open, Ctrl-C reaches it alone, and the loop goes on. Where the project's
config sets notifier, loop-claude also sends the human each question, naming its tmux window as
<session>:<window>, each release ready to cut and each stop as a DM, as bin/notify sends it. Four
stops are left out: Ctrl-C, printing this help, the loop-claude that started the windows once it
attaches or prints how to, and a loop whose chunk finished once it started the next chunks. A DM
that fails is said on stderr, and the loop goes on.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
after 600 s and is stopped, leaves the worker to find the facts itself.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree, adding
--item <ID> in a window named for an item, and quotes what it prints in the first prompt
(prompts.preflight_facts in bin/loop_claude/cycle/prompts.py); chunk-preflight --help says what it
finds and makes. A preflight that fails, or is still running after 600 s and is stopped, leaves the
worker to find the facts itself.
Loops of one project run side by side, each on one chunk at a time. Each holds a slot of the
project, the file slot-<n> under ~/.local/state/loop-claude/<key>/, locked while the loop runs.
<key> is the checkout's path relative to ~/code, or to / outside it. A loop takes the lowest free
slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot.
slot-0's session is named "A <key> loop-claude", and slot-<n>'s "A <key> loop-claude <n+1>".
The session is deleted when its chunk finishes. At every
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the claude session's
transcript is copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
@@ -71,7 +94,7 @@ both set, nothing is asked.
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
project's model is on it, the worker and the session /talk opens run on
the rung that the chunk's todo.md item picks, and the judge of some
the rung that the chunk's plan item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the
worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds
@@ -81,7 +104,7 @@ each review's rung in bin/model_routing/review_choice.py, and the prompts' wordi
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
plan or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
without it.
The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh
@@ -116,7 +139,11 @@ loop-claude --help succeeds: the loop reloads into the edited script.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- its slot in the project cannot be taken
- tmux is missing or older than 3.2
- --chunk is given outside a tmux window
- a chunk's window cannot be started, as when the project's config cannot be read, or the tmux
session runs another checkout's chunks
- the tmux session cannot be put on the terminal
- the goals file, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
the project's review standards where they exist, cannot be read or is not UTF-8
- no config names the checkout, its config cannot be read, or the goals file holds no premises
@@ -146,4 +173,5 @@ Exit 2, when the human is needed to go on:
- the claude opened for /talk, or for a release ready to cut, ends without
anything typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning resumes an open session that no running loop holds, the lowest one first."""
Rerunning loop-claude <task> starts the chunks that may start, a stopped one first, and each
resumes its claude session where it is open."""
+1 -1
View File
@@ -3,7 +3,7 @@ import pathlib
from failure import Failure
from record_store.stores import goals_store
from project_config.main import located
from release_plan.goals_file import section
from plan.goals_file import section
def read_premises(root: str, home: pathlib.Path) -> str | Failure:
+6 -6
View File
@@ -5,10 +5,10 @@ from project_config.main import located
from loop_claude.project.text_file import read_utf8
from record_store.stores import store
# The records the judge reads beside the premises: these project files, then the human's rules below.
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
# The setting in the project's config that places each of RECORD_FILES.
RECORD_SETTINGS = ("working-rules", "decisions")
# The records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below.
WORKING_RULES = ("AGENTS.md", "working-rules")
DECISIONS = ("docs/decisions.md", "decisions")
RECORD_FILES = (WORKING_RULES[0], DECISIONS[0])
# The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/,
# then each .md file in the review standards folder the project's config sets.
HUMAN_RULES_FILE = "CLAUDE.md"
@@ -27,8 +27,8 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str
if isinstance(config, Failure):
return Failure(f"{config.reason} - {CONSEQUENCE}.")
rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md")), *sorted(config.paths["standards"].glob("*.md"))]
decisions = store(config, RECORD_SETTINGS[1]).read()
texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
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 = []
for heading, text in texts:
+9 -6
View File
@@ -33,9 +33,9 @@ from release_plan.release_standing import chunk_item, LastCut, Next
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from release_plan.todo_table import Item, NoItemsTable
from plan.todo_table import Item, NoItemsTable
from model_routing.ladder import Ladder, Rung
from plan_store.stores import Plan
from plan_store.plans import Plan
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
@@ -45,14 +45,17 @@ ESCALATION_CAP = 2
JUDGE_REPLAYED = ("claude-opus-5-5",)
def routed_item(plan: Plan | Failure, cut: LastCut) -> Item | Failure | None:
"""The item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
def routed_item(plan: Plan | Failure, cut: LastCut, item_id: int | None = None) -> Item | Failure | None:
"""The plan's item item_id, or without one the item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
if isinstance(plan, NoItemsTable):
return None
if isinstance(plan, Failure):
return plan
pick = chunk_item(plan.items, cut)
takes = pick.item if isinstance(pick, Next) else None
if item_id is None:
pick = chunk_item(plan.items, cut)
takes = pick.item if isinstance(pick, Next) else None
else:
takes = next((item for item in plan.items if item.id == item_id), None)
return takes if takes and takes.likelihood and takes.escape_and_impact else None
+171 -22
View File
@@ -29,6 +29,26 @@ OFF_LADDER = '{"model": "worker-model"}'
OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0}
# A tmux that logs each command. It prints $FAKE_TMUX_VERSION for -V, $FAKE_TMUX_OWNER for show-options, and the file $FAKE_TMUX_WINDOWS for list-windows, where it finds no session without the file, and for any other command the ID of a new window.
FAKE_TMUX = """#!{python}
import json, os, pathlib, sys
argv = sys.argv[1:]
with open(os.environ["FAKE_TMUX_LOG"], "a") as log:
log.write(json.dumps(argv) + "\\n")
windows = pathlib.Path(os.environ["FAKE_TMUX_WINDOWS"])
if argv[0] == "-V":
print(os.environ.get("FAKE_TMUX_VERSION", "tmux 3.2"))
elif argv[0] == "show-options":
print(os.environ["FAKE_TMUX_OWNER"])
elif argv[0] == "list-windows":
if not windows.exists():
sys.exit("no server running")
print(windows.read_text(), end="")
else:
print("@7")
"""
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
FAKE_CLAUDE = """#!{python}
@@ -166,9 +186,11 @@ class Run:
code: int
sleeps: list
starts: list
# stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it.
# stderr and stdout are without the local time that opens each message loop-claude prints, and stderr without the bell an interrupt rings; raw_stderr and raw_stdout keep them.
stderr: str
stdout: str
# Each tmux command run, as its arguments.
tmux: list
raw_stderr: str
raw_stdout: str
@@ -195,6 +217,8 @@ class Checkout:
fake.mkdir()
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
(fake / "claude").chmod(0o755)
(fake / "tmux").write_text(FAKE_TMUX.format(python=sys.executable))
(fake / "tmux").chmod(0o755)
(fake / "git").symlink_to(shutil.which("git"))
site = self.temp / "site"
site.mkdir()
@@ -203,6 +227,11 @@ class Checkout:
self.env.update({
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
"FAKE_MEMINFO": str(self.temp / "meminfo"),
"FAKE_TMUX_LOG": str(self.temp / "tmux.jsonl"),
"FAKE_TMUX_WINDOWS": str(self.temp / "tmux-windows"),
"FAKE_TMUX_OWNER": str(self.root),
# The pane of the window the loop under test runs in.
"TMUX_PANE": "%3",
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
@@ -224,15 +253,20 @@ class Checkout:
self.git("add", "todo.md")
self.git("commit", "--quiet", "-m", "plan")
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""):
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
def run(self, steps, argv=None, cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early="", chunk="no-item"):
"""Runs loop-claude with argv, or without one as the loop of the window `chunk`, on TASK. Off a terminal, a window's loop whose chunk finished is run again while steps remain, as the window it starts for the next chunk would."""
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG", "FAKE_TMUX_LOG"):
pathlib.Path(self.env[name]).unlink(missing_ok=True)
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
command = [sys.executable, str(self.script), *argv]
command = [sys.executable, str(self.script), *(("--chunk", chunk, TASK) if argv is None else argv)]
cwd = cwd or self.root
if terminal_input is None:
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
code, stdout, stderr = done.returncode, done.stdout, done.stderr
code, stdout, stderr = 0, "", ""
runs = 0
while code == 0 and (runs == 0 or (argv is None and json.loads(pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).read_text()))):
runs += 1
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
code, stdout, stderr = done.returncode, stdout + done.stdout, stderr + done.stderr
else:
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early)
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
@@ -241,8 +275,9 @@ class Checkout:
code=code,
sleeps=[event["sleep"] for event in started if "sleep" in event],
starts=[event["argv"] for event in started if "argv" in event],
stderr=unstamped(stderr),
stderr=unstamped(stderr).replace("\a", ""),
stdout=unstamped(stdout),
tmux=lines(pathlib.Path(self.env["FAKE_TMUX_LOG"])),
raw_stderr=stderr,
raw_stdout=stdout,
)
@@ -394,7 +429,7 @@ class Premises(unittest.TestCase):
write_config(checkout.home, root)
checkout.git("init", "--quiet", str(root))
run = checkout.run([worker()], cwd=root)
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude")
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude no-item")
class Cycles(unittest.TestCase):
@@ -414,13 +449,13 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
workers = [call for call in run.calls if call["role"] == "worker"]
session = argument(workers[0], "--session-id")
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude")
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude no-item")
self.assertEqual(argument(workers[1], "--resume"), session)
self.assertIsNone(argument(workers[1], "--session-id"))
self.assertIsNone(argument(workers[1], "--name"))
self.assertEqual(argument(workers[2], "--session-id"), session)
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's plan items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertIn("main or master", argument(workers[0], "-p"))
self.assertNotIn(TASK, argument(workers[1], "-p"))
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
@@ -433,8 +468,10 @@ class Cycles(unittest.TestCase):
self.assertIn("landed-it", run.calls[3]["stdin"])
self.assertNotIn("landed-it", run.calls[5]["stdin"])
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
self.assertIn("=== cycle 2, worker on worker-model ===", run.stdout)
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 2, worker on worker-model ===$", run.raw_stdout)), 1)
# The finished chunk's loop started the next chunk's window and ended; the checkout has no default branch to read a plan from.
self.assertIn("landed-it\nthe chunk finished; started no-item\n\n=== cycle 1, worker on worker-model ===\nnext chunk\n", run.stdout)
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
@@ -608,19 +645,15 @@ class Cycles(unittest.TestCase):
self.assertIsNotNone(argument(run.calls[0], "--resume"))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
def test_a_second_loop_in_the_project_runs_its_own_session_and_leaves_the_first_loops_open_chunk_alone(self):
def test_a_second_window_of_the_project_runs_its_own_session_and_leaves_the_first_ones_open_chunk_alone(self):
checkout = Checkout(self)
first = checkout.run([worker(say="first chunk"), judge(evidence="first chunk")])
session = argument(first.calls[0], "--session-id")
transcript = checkout.transcripts()[0]
kept, archived = transcript.read_bytes(), checkout.archived()
slot = checkout.home / ".local" / "state" / "loop-claude" / "proj" / "slot-0"
slot.parent.mkdir(parents=True, exist_ok=True)
# The test holds the first loop's slot, as the first loop does while it runs.
with open(slot, "a") as running:
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")])
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude 2")
self.assertEqual(argument(first.calls[0], "--name"), "A proj loop-claude no-item")
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")], chunk="item-2")
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude item-2")
self.assertNotIn(session, [argument(call, "--session-id") or argument(call, "--resume") for call in second.calls if call["role"] == "worker"])
self.assertNotIn("first chunk", second.calls[1]["stdin"])
self.assertEqual(transcript.read_bytes(), kept)
@@ -771,6 +804,111 @@ class Cycles(unittest.TestCase):
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
# Items 4 and 9 with predictions that do not overlap, so both may run at once, and item 12, which overlaps item 4.
BESIDE = TAKEN_IN_AT_L_4 + "| 12 | 0.1.0 | | **Do most.** | 2 | 1 | 2 | 3 | 2 | 1 by 9 | 10 |\n\n## Details\n\n### 4. Do it.\n\nTouches:\n\n- `a.py`\n\n### 9. Do more.\n\nTouches:\n\n- `b.py`\n\n### 12. Do most.\n\nTouches:\n\n- `a.py`\n"
class Windows(unittest.TestCase):
def checkout(self, parallel=None):
"""A checkout whose plan is BESIDE, with parallel-chunks set where given."""
checkout = Checkout(self)
checkout.commit_plan(BESIDE)
if parallel:
config = checkout.home / ".claude-projects" / "proj" / "config.toml"
config.write_text(f"parallel-chunks = {parallel}\n" + config.read_text())
return checkout
def started(self, run):
"""The window each new-session or new-window made, with the command it runs."""
return [(command[0], command[command.index("-n") + 1], command[command.index("--") + 1:]) for command in run.tmux if command[0] in ("new-session", "new-window")]
def test_starts_one_chunk_in_a_window_of_the_projects_session_by_default(self):
checkout = self.checkout()
run = checkout.run([], argv=["ship", "it"])
self.assertEqual((run.code, run.calls, run.stderr), (0, [], ""))
self.assertEqual(run.tmux, [
["-V"],
["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"],
["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "LOOP_CLAUDE_JUDGE_MODEL=judge-model", "-e", "LOOP_CLAUDE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"],
["set-option", "-t", "=loop-proj:", "@loop-root", str(checkout.root)],
["set-option", "-w", "-t", "@7", "remain-on-exit", "failed"],
])
self.assertEqual(run.stdout, "started item-4 in the tmux session loop-proj\nnot on a terminal; see the chunks with `tmux attach -t =loop-proj`\n")
def test_starts_up_to_the_configured_number_of_chunks_whose_predictions_do_not_overlap(self):
run = self.checkout(parallel=3).run([], argv=[TASK])
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-session", "item-4"), ("new-window", "item-9")])
self.assertIn("started item-4, item-9 in the tmux session loop-proj\n", run.stdout)
def test_starts_only_what_the_running_windows_leave_room_for(self):
checkout = self.checkout(parallel=2)
# Item 4's chunk runs and waits for the human; item 9's loop failed, so its window stays, dead.
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4 ?\t0\t@1\nitem-9\t1\t@2\n")
run = checkout.run([], argv=[TASK])
self.assertEqual([command for command in run.tmux if command[0] == "kill-window"], [["kill-window", "-t", "@2"]])
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-window", "item-9")])
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
run = checkout.run([], argv=[TASK])
self.assertEqual((self.started(run), run.code), ([], 0))
self.assertIn(f"the tmux session loop-proj runs every chunk that may run now, so `{TASK}` started in no new window\n", run.stdout)
def test_a_finished_chunk_starts_the_next_one_its_window_leaves_room_for(self):
checkout = self.checkout(parallel=2)
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-9")
self.assertEqual((run.code, run.roles()), (0, ["worker", "judge"]))
# Item 9 is still in the checkout's plan, since nothing merged here; the window that leaves holds it no longer, and item 4's chunk still runs.
self.assertEqual(self.started(run), [("new-window", "item-9", [str(checkout.script), "--chunk", "item-9", TASK])])
self.assertIn("the chunk finished; started item-9\n", run.stdout)
def test_a_finished_chunk_starts_the_next_item_from_the_plan_its_merge_left_on_origin(self):
checkout = Checkout(self)
origin = checkout.temp / "origin.git"
checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin))
checkout.git("symbolic-ref", "HEAD", "refs/heads/main")
checkout.commit_plan(TODO)
checkout.git("remote", "add", "origin", str(origin))
checkout.git("push", "--quiet", "--set-upstream", "origin", "main")
# Item 4's chunk runs a cycle and stays open, so the rerun below resumes it and runs no chunk-preflight, which would fetch.
self.assertEqual(checkout.run([worker(), judge()], chunk="item-4").code, 130)
# Item 4's chunk merges, which leaves item 6 next on origin; the checkout fetched before it.
elsewhere = checkout.temp / "elsewhere"
checkout.git("clone", "--quiet", str(origin), str(elsewhere))
(elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |"))
checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "Finish item 4")
checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main")
run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-4")
self.assertEqual(self.started(run), [("new-session", "item-6", [str(checkout.script), "--chunk", "item-6", TASK])])
def test_tells_a_fresh_worker_the_items_the_other_running_chunks_hold_and_starts_from_its_windows_item(self):
checkout = self.checkout(parallel=2)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
run = checkout.run([worker()], chunk="item-9")
prompt = argument(run.calls[0], "-p")
self.assertIn("The item this chunk starts from, named with --item: item 9, L 4, E + I 3.", prompt)
self.assertIn("Other chunks of this project, running or stopped, hold item 4. Leave those items out of this chunk, even where the facts above list them as items that may join it.", prompt)
self.assertIn("routed by item 9's L of 4", prompt)
def test_refuses_to_start_on_a_tmux_older_than_needed_or_without_one(self):
checkout = self.checkout()
checkout.env["FAKE_TMUX_VERSION"] = "tmux 3.1c"
run = checkout.run([], argv=[TASK])
self.assertEqual((run.code, run.stderr, run.tmux), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\n", [["-V"]]))
(pathlib.Path(checkout.env["PATH"]) / "tmux").unlink()
run = checkout.run([], argv=[TASK])
self.assertEqual((run.code, run.stderr), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
def test_marks_the_window_while_an_interrupt_waits_and_rings_its_bell(self):
checkout = self.checkout()
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?")], chunk="item-4")
self.assertEqual(run.code, 2)
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"]])
self.assertEqual(run.raw_stderr.count("\a"), 1)
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?"), worker()], chunk="item-4", terminal_input="B\n", before_typing=ANSWERING)
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"], ["rename-window", "-t", "%3", "item-4"]])
class Interrupt(unittest.TestCase):
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
checkout = Checkout(self)
@@ -971,17 +1109,28 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "slot": 0} for cycle in (2, 3, 4)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "chunk": "no-item"} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
outside.mkdir()
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None}
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "chunk": "no-item"}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
self.assertIn("=== cycle 4,", run.stdout)
def test_a_loop_started_before_chunks_ran_in_windows_reloads_into_starting_the_projects_windows(self):
checkout = Checkout(self)
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "slot": 0}
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)])
self.assertEqual((run.code, run.calls), (0, []))
self.assertEqual([command[0] for command in run.tmux], ["-V", "list-windows", "new-session", "set-option", "set-option"])
self.assertIn("started no-item in the tmux session loop-proj\n", run.stdout)
def test_stops_where_a_reload_hands_no_state(self):
checkout = Checkout(self)
run = checkout.run([], argv=["--reloaded", "{}"])
self.assertEqual((run.code, run.calls), (1, []))
self.assertIn("rerun loop-claude <task>", run.stderr)
+500 -77
View File
@@ -21,7 +21,7 @@ from routing_figures import archive, state
from routing_figures.calls import Call
from loop_claude.project import checkout, model_choice, records
from loop_claude.cycle import chunk_items
from loop_claude.loop import chunk_slot, chunk_start, close
from loop_claude.loop import chunk_start, chunk_windows, close
from project_config.test_project_config import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from loop_effects.effects import Effects, PYTHON_TIMEOUT
@@ -33,16 +33,19 @@ from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, stat
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from machine_load import memory
from release_plan import next_chunk
from transcript_archive import outcomes, write
from loop_state import paths
from plan_store.stores import plan_of
from plan_store.todo_md import plan_of
from transcript_archive.location import project_archive
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from model_routing.ladder import Rung
from loop_claude.stop import Stop
from loop_claude import tmux
from claude_code.tokens import Tokens, tokens_of
from touch_predictions.test_touch_predictions import plan as touch_plan
from text_files.utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
@@ -76,18 +79,28 @@ def human(content):
return {"type": "user", "message": {"content": content}}
# The window the loops under test run in.
WINDOW = tmux.Window("loop-proj", "item-7", "%4")
def a_loop(effects, **fields):
"""A loop in /r on effects, with fields in place of its defaults."""
home = pathlib.Path("/h")
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude"), "window": WINDOW}
return this_loop.Loop(**{**defaults, **fields}, effects=effects)
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"):
self.calls = []
# Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session.
self.tmux_calls = []
self.tmux_version = tmux_version
self.windows = windows
# The checkout the session's @loop-root option names.
self.owner = owner
# Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent.
self.dms = []
self.dm_failures = list(dm_failures)
@@ -115,8 +128,16 @@ class FakeEffects:
python=lambda args, cwd: self.answer("python", (args, cwd)),
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
stream_claude=self.stream,
tmux=self.tmux,
tmux_on_terminal=lambda args: self.tmux(args).returncode,
)
def tmux(self, args):
self.tmux_calls.append(args)
if args[0] == "list-windows":
return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server")
return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "")
def dm(self, text):
self.dms.append(text)
return self.dm_failures.pop(0) if self.dm_failures else None
@@ -265,7 +286,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -560,7 +581,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6))
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
self.assertEqual(fake.made("claude_on_terminal"), [])
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
@@ -627,7 +648,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
self.assertEqual(len(fake.made("stream_claude")), 1)
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
self.assertNotIn("Use ... A.", said.getvalue())
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
@@ -733,10 +754,11 @@ class Interrupts(unittest.TestCase):
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
"""interrupt's answer and what it said."""
"""interrupt's answer and what it said, without the bell it rang, which self.bells counts."""
with contextlib.redirect_stderr(io.StringIO()) as said:
answer = interrupt.interrupt(question, answer_here, self.session, effects or fake.effects())
return answer, said.getvalue()
answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, effects or fake.effects())
self.bells = said.getvalue().count(tmux.BELL)
return answer, said.getvalue().replace(tmux.BELL, "")
def typed_there(self, args):
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
@@ -754,7 +776,19 @@ class Interrupts(unittest.TestCase):
with self.subTest(on_terminal=on_terminal):
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
self.put(fake)
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"])
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"])
def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self):
fake = FakeEffects(inputs=["Use B."])
answer, said = self.put(fake)
self.assertEqual(answer, "Use B.")
self.assertEqual(self.bells, 1)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]])
def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self):
fake = FakeEffects(on_terminal=False)
self.put(fake)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]])
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
fake = FakeEffects(inputs=["Use B."])
@@ -984,7 +1018,9 @@ class Routing(unittest.TestCase):
def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self):
self.assertEqual(routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3)
self.assertIsNone(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])))
# Someone cut 0.2.0 while it held items: they count as 0.3.0's, the next release, and where no later release is known, no item routes.
self.assertEqual(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])).id, 3)
self.assertIsNone(routed_item(re.sub(r"(?m)^\| \d+ \| 0\.3\.0 \|.*\n", "", TODO), LastCut("v0.2.0", "", 3, [])))
later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):]
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO])))
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO])))
@@ -1123,24 +1159,37 @@ class Routing(unittest.TestCase):
class RouteSources(unittest.TestCase):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.2.0", "", 3, [TODO])), FakeEffects().effects()))
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects()))
def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self):
plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO]))
later = next(item.id for item in plan.plan.items if item.id != 3)
self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later)
# An item that left the plan, as once it shipped.
self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects()))
# A chunk start reads the default branch once, for routing and for scoring the items the worker names.
with unittest.mock.patch.object(chunk_start, "session_open", return_value=True), unittest.mock.patch.object(chunk_start, "fetched_plan", return_value=plan) as fetched:
loop = a_loop(FakeEffects().effects())
self.assertEqual(chunk_start.chunk_start(loop), ("", plan))
# An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show.
fetched.assert_called_once_with(loop, False)
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(chunk_start.plan_item(plan, FakeEffects().effects()))
self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects()))
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
fetched = ["origin\n", "origin/main\n", "", "todo.md\n"]
for git, said in ((fetched + [TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")], "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), ([Failure("no git")], "the items the worker names lift no rung: no git\n"), (fetched + [TODO], "")):
with self.subTest(said=said), tempfile.TemporaryDirectory() as root:
home = configured(self, pathlib.Path(root)).parents[1]
unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"))
for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_todo(a_loop(FakeEffects(git=git).effects(), root=root, paths=paths.paths_from(home)))
scored = chunk_start.scored_plan(default, FakeEffects().effects())
self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "")
self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default)
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
def git(*args, **options):
@@ -1164,16 +1213,19 @@ class RouteSources(unittest.TestCase):
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)
self.assertEqual(chunk_start.fetched_todo(loop), plan_of(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]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
held = chunk_start.fetched_plan(standing)
self.assertEqual((held.todo, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
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]))
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")
config.unlink()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIn("no config names the checkout", chunk_start.fetched_todo(loop).reason)
self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason)
self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue())
self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason)
@@ -1208,61 +1260,301 @@ class RouteSources(unittest.TestCase):
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
class ChunkSlots(unittest.TestCase):
class TmuxCommands(unittest.TestCase):
def test_refuses_a_tmux_older_than_needed_naming_both_versions(self):
for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None),
("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"),
("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"),
("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")):
with self.subTest(found=found):
fake = FakeEffects(tmux_version=found)
self.assertEqual(tmux.unusable(fake.tmux), reason)
self.assertEqual(fake.tmux_calls, [["-V"]])
def test_names_the_session_for_the_project(self):
self.assertEqual(tmux.session_name("claude-config"), "loop-claude-config")
# tmux reads `.` and `:` in a target as separators.
self.assertEqual(tmux.session_name("my.site:2 x"), "loop-my-site-2-x")
self.assertEqual(tmux.session_name("Acme/Billing"), "loop-Acme-Billing")
def test_lists_the_windows_without_the_waiting_mark(self):
fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n")
self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)])
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), [])
failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server")
self.assertEqual(tmux.listed("loop-proj", failed), [])
def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self):
fake = FakeEffects()
window = tmux.Window("loop-proj", "item-7", "")
self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, fake.tmux))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, fake.tmux))
self.assertEqual(fake.tmux_calls, [
["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"],
["set-option", "-t", "=loop-proj:", "@loop-root", "/r"],
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"],
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
])
def test_says_why_tmux_started_no_window(self):
failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n")
silent = lambda args: subprocess.CompletedProcess(args, 2, "", "")
window = tmux.Window("loop-proj", "item-7", "")
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj"))
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2"))
def test_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self):
def answering(failing: str):
def run(args):
fails = args[:1] == ["set-option"] and failing in args
return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "")
return run
window = tmux.Window("loop-proj", "item-7", "")
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session"))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, answering("remain-on-exit")))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, answering(tmux.OWNER)))
def test_reads_the_checkout_the_session_names(self):
fake = FakeEffects(owner="/c/proj")
self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj")
self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj:", "@loop-root"]])
def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self):
fake = FakeEffects()
tmux.mark(WINDOW, True, fake.tmux)
tmux.mark(WINDOW, False, fake.tmux)
tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]])
self.assertEqual(WINDOW.target, "loop-proj:item-7")
def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self):
self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"])
self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"])
class ChunkWindows(unittest.TestCase):
def plan(self, *touched):
"""A plan of items 1, 2 and on, each predicted to touch the path given for it."""
items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
return next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="")
def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self):
# Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it.
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"])
def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(self):
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), [])
def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2))
def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2))
def test_leaves_no_room_where_more_chunks_run_than_the_limit(self):
windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0)
def test_starts_no_item_that_overlaps_a_running_chunks_items(self):
# Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py.
items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`"))
plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="")
self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["item-4"])
# A running chunk's item without a prediction leaves no other item free to start beside it.
unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None))
self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), [])
# A held item that left the plan, as once it merged, overlaps nothing.
self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["item-2", "item-4"])
def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self):
none = next_chunk.NoItem("release 1.0.0 has no items")
self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"])
self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), [])
def test_names_a_window_for_its_item_and_reads_the_item_back(self):
self.assertEqual(chunk_windows.window_name(372), "item-372")
self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None])
# Only ASCII digits name an item, as window_name writes them.
self.assertIsNone(chunk_windows.item_of("item-\u0663"))
def test_starts_only_the_next_item_where_the_touch_predictions_cannot_be_read(self):
with unittest.mock.patch.object(chunk_windows, "chunks_beside", return_value="item 1's Touches: list cannot be read"):
self.assertEqual(chunk_windows.may_start(self.plan("a.py", "c.py"), [], set(), 3), ["item-1"])
def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self):
with tempfile.TemporaryDirectory() as temp:
transcripts = pathlib.Path(temp)
folder = transcripts / "-r"
folder.mkdir()
# A folder in place of the transcript file, so reading it fails.
(folder / f"{chunk_windows.chunk_session('proj', 'item-7', transcripts).id}.jsonl").mkdir()
self.assertEqual(chunk_windows.held_items(["item-7"], "proj", transcripts), {7})
def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self):
with tempfile.TemporaryDirectory() as temp:
home = pathlib.Path(temp)
held = paths.paths_from(home)
folder = held.claude_code_transcripts / "-r"
folder.mkdir(parents=True)
lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})]
(folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
# Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item.
fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n")
self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11])
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
class StartChunks(unittest.TestCase):
"""start_chunks: the windows a loop opens for the chunks that may start now."""
LAUNCHER = pathlib.Path("/b/loop-claude")
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.paths = paths.paths_from(self.home)
self.addCleanup(self.release)
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.root = pathlib.Path(made.name, "r")
self.home = configured(self, self.root).parents[1]
self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-")
# Items 1 and 2 overlap, so 2 waits; 3 runs beside 1.
self.plan = ChunkWindows.plan(self, "a.py", "a.py", "c.py")
def held(self):
"""This process's open files on a slot, each with whether an exec keeps it."""
folder = self.home / chunk_slot.SLOTS
found = {}
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if pathlib.Path(os.readlink(f"/proc/self/fd/{fd}")).is_relative_to(folder):
found[os.readlink(f"/proc/self/fd/{fd}")] = os.get_inheritable(int(fd))
return found
def limit(self, chunks):
config = self.home / ".claude-projects" / self.root.name / "config.toml"
config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n")
def release(self):
folder = str(self.home / chunk_slot.SLOTS)
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if os.readlink(f"/proc/self/fd/{fd}").startswith(folder):
os.close(int(fd))
def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None):
"""start_chunks' answer, for a session whose @loop-root names owner, by default this checkout."""
fake.owner = str(self.root) if owner is None else owner
run = main.LoopRun(0, str(self.root), "ship it", "", chunk=chunk)
with unittest.mock.patch.object(chunk_windows, "next_plan", return_value=plan or self.plan) as planned, contextlib.redirect_stderr(io.StringIO()) as said:
effects = fake.effects()
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects)
self.said = said.getvalue()
self.planned = planned.call_count
if planned.call_count:
planned.assert_called_once_with(str(self.root), self.home, effects)
return started
def test_each_loop_takes_the_lowest_free_slot_and_names_its_session_after_it(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
first, second = chunk_slot.slotted(loop_run, self.paths), chunk_slot.slotted(loop_run, self.paths)
self.assertEqual((first[0], first[1].name), (dataclasses.replace(loop_run, slot=0), "A proj loop-claude"))
self.assertEqual((second[0].slot, second[1].name), (1, "A proj loop-claude 2"))
self.assertEqual(second[1], session.session_named("A proj loop-claude 2", self.paths.claude_code_transcripts))
folder = self.home / ".local" / "state" / "loop-claude" / "proj"
self.assertEqual(self.held(), {str(folder / "slot-0"): True, str(folder / "slot-1"): True})
def starts(self, fake):
"""The window starts of fake's tmux calls, each as (command, window name, what it runs)."""
return [(call[0], call[call.index("-n") + 1], call[call.index("--") + 1:]) for call in fake.tmux_calls if call[0] in ("new-session", "new-window")]
def test_a_rerun_takes_the_lowest_free_slot_whose_session_is_open_before_a_lower_closed_one(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
for name in ("A proj loop-claude 3", "A proj loop-claude 4"):
transcript = self.paths.claude_code_transcripts / "-home-proj" / f"{session.session_named(name, self.paths.claude_code_transcripts).id}.jsonl"
transcript.parent.mkdir(parents=True, exist_ok=True)
transcript.write_text("")
self.assertEqual([chunk_slot.slotted(loop_run, self.paths)[0].slot for _ in range(4)], [2, 3, 0, 1])
def test_opens_a_window_for_each_chunk_that_may_start_the_first_making_the_session(self):
self.limit(2)
fake = FakeEffects()
self.assertEqual(self.start(fake, env={"LOOP_CLAUDE_WORKER_MODEL": "m", "PATH": "/bin"}), ["item-1", "item-3"])
self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])])
first = next(call for call in fake.tmux_calls if call[0] == "new-session")
self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root)))
# Only loop-claude's own variables are handed on, since a window gets the tmux server's environment.
self.assertEqual([word for word in first if "=" in word], ["LOOP_CLAUDE_WORKER_MODEL=m"])
self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
# The session names the checkout whose chunks it runs.
self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls)
def test_a_reload_keeps_the_slot_it_is_handed_and_takes_no_other(self):
loop_run = main.LoopRun(cycle_number=3, root="/srv/proj", task="do it", unfinished_evidence="", slot=2)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), (loop_run, session.session_named("A srv/proj loop-claude 3", self.paths.claude_code_transcripts)))
self.assertEqual(self.held(), {})
def test_refuses_a_session_that_runs_another_checkouts_chunks(self):
for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")):
with self.subTest(owner=owner):
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders"))
self.assertEqual(self.starts(fake), [])
self.assertIn(["show-options", "-qv", "-t", f"={self.session}:", "@loop-root"], fake.tmux_calls)
def test_says_why_it_takes_no_slot(self):
loop_run = main.LoopRun(cycle_number=0, root="/srv/proj", task="do it", unfinished_evidence="")
with unittest.mock.patch.object(chunk_slot, "MOST", 1):
chunk_slot.slotted(loop_run, self.paths)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), Failure(f"1 loops of this project are running already; `fuser {self.home}/.local/state/loop-claude/srv/proj/slot-*` names them"))
(self.home / ".local" / "state" / "loop-claude").mkdir(parents=True, exist_ok=True)
(self.home / ".local" / "state" / "loop-claude" / "other").write_text("")
self.assertEqual(chunk_slot.slotted(dataclasses.replace(loop_run, root="/other"), self.paths), Failure(f"cannot take a slot in {self.home}/.local/state/loop-claude/other: File exists"))
def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
self.assertEqual(self.start(FakeEffects(windows="item-5\t0\t@1\n")), ["item-3"])
def test_starts_one_chunk_without_parallel_chunks(self):
fake = FakeEffects()
self.assertEqual(self.start(fake), ["item-1"])
def test_starts_none_and_reads_no_plan_while_the_running_chunks_fill_the_limit(self):
self.limit(2)
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6 ?\t0\t@2\n")
self.assertEqual((self.start(fake), self.planned, self.starts(fake)), ([], 0, []))
# More chunks run than the limit allows, as after it was lowered; a stopped chunk still waits.
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6\t0\t@2\nitem-7\t0\t@3\nitem-8\t1\t@4\nitem-9\t1\t@5\n")
self.assertEqual((self.start(fake), self.planned), ([], 0))
def test_a_finishing_chunks_own_window_counts_as_no_longer_running(self):
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, chunk="item-5"), [])
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, chunk="item-5", leaving=True), ["item-1"])
# The session exists, since the finishing loop's window is still in it.
self.assertEqual(self.starts(fake)[0][0], "new-window")
def test_the_humans_loop_claude_starts_a_stopped_chunk_again_first_closing_its_dead_window(self):
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual((self.start(fake), self.planned), (["item-5"], 0))
self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls)
# Its dead window was the session's last, so the session is made again.
self.assertEqual(self.starts(fake)[0][0], "new-session")
self.limit(2)
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake), ["item-5", "item-1"])
def test_a_plan_with_no_item_starts_nothing_beside_a_restarted_chunk(self):
self.limit(2)
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake, plan=next_chunk.NoItem("release 1.0.0 has no items")), ["item-5"])
def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n")
# Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks.
self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"])
self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], [])
fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n")
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=next_chunk.NoItem("release 1.0.0 has no items")), [])
def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self):
fake = FakeEffects()
self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"])
self.assertIn("starting a chunk without a plan item, since the plan cannot be read: no origin/main", self.said)
def test_says_why_a_window_could_not_start(self):
with unittest.mock.patch.object(tmux, "start_window", return_value=Failure("tmux could not start the window")):
self.assertEqual(self.start(FakeEffects()), Failure("tmux could not start the window"))
def test_says_why_it_cannot_take_the_lock_on_starting_windows(self):
(self.home / ".local" / "state").mkdir(parents=True)
(self.home / ".local" / "state" / "loop-claude").write_text("")
started = self.start(FakeEffects())
self.assertIsInstance(started, Failure)
self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason)
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
with tempfile.TemporaryDirectory() as temp:
transcripts = pathlib.Path(temp)
opened = chunk_windows.chunk_session("proj", "item-7", transcripts)
self.assertEqual(opened.name, "A proj loop-claude item-7")
folder = transcripts / "-r"
folder.mkdir()
lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})]
(folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9})
class Steps(unittest.TestCase):
@@ -1335,10 +1627,27 @@ class ChunkFacts(unittest.TestCase):
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
self.assertIn("\n\n- A fact.", said)
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")])
self.assertTrue(said.endswith("\n\n- A fact."), said)
self.assertNotIn("yourself", said)
def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4")))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self):
# The loop's own window, a stopped one and two that run, one of them waiting for the human.
fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n")
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
self.assertEqual(prompts.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.")
self.assertTrue(prompts.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9."))
# A worker whose preflight failed is told them too.
fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n")
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self):
for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")):
with self.subTest(why=why):
@@ -1351,7 +1660,7 @@ class ChunkFacts(unittest.TestCase):
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
fresh = FakeEffects(python=[ran("- A fact.\n")])
facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER))
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree"], "/r")], True))
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("")
@@ -1414,7 +1723,7 @@ class WorkerArgs(unittest.TestCase):
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
@@ -1922,6 +2231,10 @@ class LoopRuns(unittest.TestCase):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state)
def test_drops_the_slot_that_a_loop_started_before_chunks_ran_in_windows_hands_on(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(reload.decode_handed(json.dumps({key: value for key, value in dataclasses.asdict(state).items() if key != "chunk"} | {"slot": 1})), state)
def test_stops_when_the_reload_cannot_start_python(self):
with tempfile.TemporaryDirectory() as root:
launcher = pathlib.Path(root, "loop-claude")
@@ -1930,6 +2243,106 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class WindowStarts(unittest.TestCase):
"""The loop-claude the human runs, which starts the windows, and the stop of a window's loop whose chunk finished."""
HOME = pathlib.Path("/h")
def run_loop(self, argv, fake, env=None, started=("item-3", "item-4")):
"""run_loop's stop and what it said on stdout, with start_chunks answering `started`; self.asked holds what start_chunks was asked."""
with unittest.mock.patch.object(main, "start_chunks", return_value=list(started) if isinstance(started, tuple) else started) as start, contextlib.redirect_stdout(io.StringIO()) as said:
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, fake.effects())
self.asked = [call.args[:2] for call in start.call_args_list]
return stop, said.getvalue()
def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self):
fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c")
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), ""))
self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], []))
def test_prints_the_help_without_tmux(self):
fake = FakeEffects(tmux_version="")
self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP))
self.assertEqual(fake.tmux_calls, [])
def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self):
for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])):
with self.subTest(shown=shown):
fake = FakeEffects(git=["/r\n"])
stop, said = self.run_loop(["do", "it"], fake, env)
self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n"))
self.assertEqual(fake.tmux_calls, [["-V"], shown])
self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)])
def test_hands_the_window_starts_its_paths_environment_launcher_and_effects(self):
fake = FakeEffects(git=["/r\n"], on_terminal=False)
effects, env, launcher = fake.effects(), {"LOOP_CLAUDE_X": "1"}, pathlib.Path("/b/loop-claude")
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]) as start, contextlib.redirect_stdout(io.StringIO()):
main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
self.assertEqual(start.call_args.args, (main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects))
def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self):
fake = FakeEffects(git=["/r\n"])
effects, env = fake.effects(), {"TMUX_PANE": "%4"}
launcher = pathlib.Path("/b/loop-claude")
cycle = unittest.mock.Mock(project="claude-opus-5-5")
unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished))
closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")]
with unittest.mock.patch.object(main, "fingerprint", return_value=""), unittest.mock.patch.object(main, "exec_if_edited", return_value=None), unittest.mock.patch.object(main, "next_cycle", return_value=cycle) as next_cycle, \
unittest.mock.patch.object(main, "run_cycle", side_effect=[unfinished, finished]), unittest.mock.patch.object(main, "closed_cycle", side_effect=closed), \
unittest.mock.patch.object(main, "check_routing", return_value=None), unittest.mock.patch.object(main, "handed_on", return_value=Stop(0, "")) as handed_on:
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
loop = this_loop.Loop(root="/r", session=session.session_named("A r loop-claude item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME), env=env, launcher=launcher, effects=effects)
self.assertEqual(stop, Stop(0, ""))
self.assertEqual([call.args for call in next_cycle.call_args_list], [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
handed_on.assert_called_once_with(closed[1], loop)
def test_a_window_loop_given_no_task_prints_the_help(self):
self.assertEqual(main.loop_run_from(["--chunk", "item-3"], CWD, FakeEffects(git=["/r\n"]).effects()), Stop(1, usage.HELP))
def test_a_window_loop_outside_a_checkout_stops(self):
self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop)
def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now, so `do it` started in no new window\n")
def test_off_a_terminal_it_prints_how_to_attach(self):
fake = FakeEffects(git=["/r\n"], on_terminal=False)
stop, said = self.run_loop(["do it"], fake)
self.assertEqual(stop, Stop(0, ""))
self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said)
self.assertEqual(fake.tmux_calls, [["-V"]])
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"))
def test_stops_where_tmux_cannot_show_the_session(self):
fake = FakeEffects(git=["/r\n"])
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]), contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, effects)
self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session"))
def test_a_window_loop_outside_tmux_stops(self):
fake = FakeEffects(git=["/r\n"])
self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how loop-claude starts itself in a tmux window; run loop-claude <task>"))
self.assertEqual(self.asked, [])
def test_reads_the_chunk_a_window_loop_is_started_with(self):
self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3"))
self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", ""))
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"))):
with self.subTest(started=started), unittest.mock.patch.object(main, "start_chunks", return_value=started) as start, contextlib.redirect_stdout(io.StringIO()) as printed:
loop = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"})
self.assertEqual(main.handed_on(loop_run, loop), stop)
self.assertEqual(printed.getvalue(), f"{STAMP} {said}\n" if said else "")
self.assertEqual(start.call_args.args, (loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects))
class StopDms(unittest.TestCase):
def run_main(self, argv, fake):
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
@@ -1942,6 +2355,12 @@ class StopDms(unittest.TestCase):
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
def test_skips_the_dm_of_a_stop_without_a_reason_as_once_the_windows_started(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(0, "")):
self.assertEqual(self.run_main(["do it"], fake), (0, ""))
self.assertEqual(fake.dms, [])
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
@@ -2019,7 +2438,11 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
("loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
("loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
("loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
+103
View File
@@ -0,0 +1,103 @@
"""The tmux commands loop-claude runs: each chunk's loop runs in its own window of one tmux session named for the project (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
import dataclasses
import re
import subprocess
import typing
from failure import Failure
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
NEEDED = (3, 2)
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
WAITS = " ?"
BELL = "\a"
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
OWNER = "@loop-root"
@dataclasses.dataclass(frozen=True)
class Window:
"""The tmux window a chunk's loop runs in."""
session: str
# Without WAITS.
name: str
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
pane: str
@property
def target(self) -> str:
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
return f"{self.session}:{self.name}"
@dataclasses.dataclass(frozen=True)
class Listed:
"""A window of the project's session, as tmux lists it."""
# Without WAITS.
name: str
# tmux's ID of the window, such as `@3`.
id: str
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
dead: bool
def unusable(run: Tmux) -> str | None:
"""Why loop-claude cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
found = run(["-V"]).stdout.strip()
version = re.search(r"([0-9]+)\.([0-9]+)", found)
if version and (int(version[1]), int(version[2])) >= NEEDED:
return None
return f"loop-claude runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
def session_name(key: str) -> str:
"""The tmux session of the project with this key, such as `loop-claude-config`. tmux reads `.` and `:` in a target as separators, so every character but a letter, a digit, `_` and `-` becomes a dash."""
return "loop-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
def listed(session: str, run: Tmux) -> list[Listed]:
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3]
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None:
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none, or why it could not mark a session it made as this checkout's."""
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
words = [re.sub(r";$", r"\\;", word) for word in command]
done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words])
if done.returncode:
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
owned = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first else None
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM.
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
# Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it.
if owned is not None and owned.returncode:
return Failure(f"tmux started the session {window.session} but could not mark it as this checkout's: {owned.stderr.strip() or f'it exited {owned.returncode}'}")
return None
def owner(session: str, run: Tmux) -> str:
"""The checkout whose chunks session runs, as OWNER names it; empty where it names none."""
return run(["show-options", "-qv", "-t", f"={session}:", OWNER]).stdout.strip()
def close(window: Listed, run: Tmux) -> None:
run(["kill-window", "-t", window.id])
def mark(window: Window, waits: bool, run: Tmux) -> None:
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
def show(session: str, inside: bool) -> list[str]:
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]
+1 -1
View File
@@ -6,7 +6,7 @@ from claude_code.tokens import Tokens
@dataclasses.dataclass(frozen=True)
class TakenIn:
"""The levels of the todo.md items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
highest_likelihood: int = 0
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
+15
View File
@@ -51,6 +51,10 @@ class Effects:
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
sleep: typing.Callable[[float], None]
stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming]
# Runs tmux with these arguments, as run_tmux does.
tmux: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
# Runs tmux on the terminal, as to attach a session, and returns its exit code once the human detaches.
tmux_on_terminal: typing.Callable[[list[str]], int]
class StreamingClaude:
@@ -82,6 +86,8 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
sleep=time.sleep,
stream_claude=StreamingClaude,
tmux=run_tmux,
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode,
)
@@ -106,6 +112,15 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]:
"""Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
command = ["tmux", *args]
try:
return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
except OSError as failure:
return subprocess.CompletedProcess(command, 127, "", f"could not start: {failure}")
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
body = text.lstrip("\n")
+30
View File
@@ -84,6 +84,36 @@ class ClaudeOnTerminal(unittest.TestCase):
class TmuxEffect(unittest.TestCase):
"""Each test runs a fake tmux off its own PATH, without $TMUX, so the human's tmux server is never reached."""
def fake_tmux(self, folder):
tmux = pathlib.Path(folder, "tmux")
tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n")
tmux.chmod(0o755)
return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
def test_runs_tmux_and_returns_what_it_printed(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
done = system_effects().tmux(["list-windows", "-t", "=loop-proj"])
self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n"))
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n")
self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd")
def test_reads_a_tmux_that_cannot_start_as_exit_127(self):
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}):
done = system_effects().tmux(["-V"])
self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, ""))
self.assertIn("could not start", done.stderr)
def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self):
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
class PythonEffect(unittest.TestCase):
def test_runs_a_script_in_the_given_directory(self):
with tempfile.TemporaryDirectory() as cwd:
+1 -6
View File
@@ -28,12 +28,7 @@ def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Pa
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
"""The number and open file of the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
return first_free_slot(folder, range(slots))
def first_free_slot(folder: pathlib.Path, order: typing.Iterable[int]) -> tuple[int, int] | None:
"""The number and open file of the first slot in order that this call locked; None while every slot in order is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in order:
for slot in range(slots):
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+1 -1
View File
@@ -3,7 +3,7 @@ import dataclasses
import json
import typing
from release_plan.todo_table import LEVELS
from plan.todo_table import LEVELS
from model_routing.ladder import REVIEW_STEPS, Rung
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
+1 -1
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.todo_table import LEVELS
from plan.todo_table import LEVELS
from model_routing.ladder_file import read_ladder, SHIPPED
from review_rules.review_passes import REVIEWERS
from model_routing.ladder import Rung, WORKER_STEPS
+6 -7
View File
@@ -3,12 +3,11 @@ import dataclasses
import pathlib
import typing
from project_config.settings import CONFIG, Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
from failure import Failure
from rest_client.json_request import Http
from project_config.main import located
import mattermost_dm.dm
from project_config.settings import Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
import slack_dm.dm
from notifier import mattermost, slack
# Sends one message, with the credentials already read.
Sender = typing.Callable[[str], Failure | None]
@@ -25,8 +24,8 @@ class Backend[C]:
# The one place each notifier is wired to the network: a caller that tests a send passes a table with its own `http`.
BACKENDS: dict[Notifier, Backend[typing.Any]] = {
"mattermost": Backend(mattermost_dm.dm.read_config, mattermost_dm.dm.send, mattermost_dm.dm.http_json, mattermost_dm.dm.KEYS),
"slack": Backend(slack_dm.dm.read_config, slack_dm.dm.send, slack_dm.dm.http_json, slack_dm.dm.KEYS),
"mattermost": Backend(mattermost.read_config, mattermost.send, mattermost.http_json, mattermost.KEYS),
"slack": Backend(slack.read_config, slack.send, slack.http_json, slack.KEYS),
}
assert tuple(BACKENDS) == NOTIFIERS
@@ -34,9 +33,9 @@ assert tuple(BACKENDS) == NOTIFIERS
def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure:
"""A sender through the project's notifier in backends, with the credentials in its env file read. A Failure where the project names no notifier or its env file cannot be used."""
if project.notifier is None:
return Failure(f"{project.folder / 'config.toml'} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
return Failure(f"{project.folder / CONFIG} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
if project.env_file is None:
return Failure(f"{project.folder / 'config.toml'} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
return Failure(f"{project.folder / CONFIG} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
backend = backends[project.notifier]
config = backend.read_config(project.env_file)
if isinstance(config, Failure):
@@ -6,7 +6,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mattermost_dm import dm
from notifier import mattermost as dm
from failure import Failure
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
+2 -2
View File
@@ -16,9 +16,9 @@ from rest_client.json_request import Http
from test_env import isolated_env
from project_config.main import located
from notifier import main, notify
from mattermost_dm.test_mattermost_dm import mattermost
from notifier.test_mattermost import mattermost
from project_config.settings import Notifier
from slack_dm.test_slack_dm import Slack
from notifier.test_slack import Slack
from loop_effects.effects import system_effects
TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify"
@@ -6,7 +6,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from slack_dm import dm
from notifier import slack as dm
from failure import Failure
CONFIG = dm.Config("xoxb-secret", "U0123ABCD")
@@ -3,8 +3,8 @@ import dataclasses
import graphlib
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release import version
from plan.todo_table import Item
from plan.release import version
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
@@ -1,7 +1,7 @@
import re
from failure import Failure
from release_plan.todo_table import Item
from plan.todo_table import Item
def check_citations(items: list[Item], decisions: str) -> Failure | None:
@@ -4,7 +4,7 @@ import decimal
import re
import typing
from release_plan.todo_table import CODE_HEALTH
from plan.todo_table import CODE_HEALTH
from failure import Failure
from text_files.markdown_text import sections
@@ -7,15 +7,15 @@ import math
import re
import typing
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
from release_plan.blockers import blocked_through, blockers_first
from release_plan.citations import check_citations
from release_plan.formula import evaluate, parse_formula
from plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, detail_heading, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, row_cells, Shape, SHAPE, shape_of, Table, table_rows, tagline_text
from plan.blockers import blocked_through, blockers_first
from plan.citations import check_citations
from plan.formula import evaluate, parse_formula
from failure import Failure
from release_plan.goals_file import goal_weights, Mark, ranked_goals
from plan.goals_file import goal_weights, Mark, ranked_goals
from review_rules.comprehension_history import latest_overall
from text_files.markdown_text import listed
from release_plan.release import version
from plan.release import version
# What a point of an item's move on a maintain goal is worth. A defect that restores the goal weighs it at least this much per point. docs/decisions.md records the choice and its data.
MAINTAIN_WEIGHT = 0.5
@@ -70,7 +70,7 @@ def rank(text: str, goals_text: str, decisions: str, history: str, floor: decima
ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored])
if isinstance(ranked, Failure):
return ranked
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if falls_under(item, value, scoring.bar)]
return Ranked(ranked, under_bar, notes(items, scoring))
@@ -115,22 +115,30 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
formula = parse_formula(stated(text, "Score"), variables(shape))
if isinstance(formula, Failure):
return formula
bar = number(stated(text, "Bar"), "the bar")
if isinstance(bar, Failure):
return bar
next_id = stated(text, "Next ID")
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
return scoring_of(stated(text, "Score"), number(stated(text, "Bar"), "the bar"), goals_text, decisions, history, floor, shape=shape, lines=lines, next_id=int(next_id))
def config_scoring(formula: str, bar: float, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Scoring | Failure:
"""The scoring of a plan in Jira, whose formula and bar the project's config states. Jira numbers the issues, so no Next ID applies."""
return scoring_of(formula, bar, goals_text, decisions, history, floor, shape=SHAPE, lines=[], next_id=0)
def scoring_of(formula_text: str | Failure, bar: float | Failure, goals_text: str, decisions: str, history: str, floor: decimal.Decimal, *, shape: Shape, lines: list[str], next_id: int) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
formula = parse_formula(formula_text, variables(shape))
if isinstance(formula, Failure):
return formula
if isinstance(bar, Failure):
return bar
weights = weigh(lines, history, goals, shape, floor)
if isinstance(weights, Failure):
return weights
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
return Scoring(shape, formula, bar, next_id, dict(goals), weights)
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
@@ -287,25 +295,43 @@ def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
if scoring.shape is OLD_SHAPE:
return item
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
return with_risk(item)
def with_risk(item: Item) -> Item:
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
def falls_under(item: Item, value: float, bar: float) -> bool:
"""Whether the item, which scores value, may not be planned: it scores under the bar, rounded as todo.md shows a Score, and isn't exempt."""
return not item.exempt and round(value, 1) < bar
def item_score(item: Item, scoring: Scoring, name: str) -> float | Failure:
"""The score of an item that holds no R, such as an issue in Jira; refused where it names a goal it may not. name is what a message calls the item."""
if broken := cited_goals_failure(item, scoring, name):
return broken
value = score(scoring.formula, with_risk(item), scoring)
return Failure(f"the formula gives {name} no finite score") if isinstance(value, Failure) else value
def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure | None:
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. name is what a message calls the item, `item <ID>` where empty. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
name = name or f"item {item.id}"
if scoring.shape is OLD_SHAPE:
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
return Failure(f"{name} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
for goal, _ in item.moves:
if goal == CODE_HEALTH and goal not in scoring.goals:
return Failure(f"item {item.id} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
return Failure(f"{name} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
if goal not in scoring.goals:
return Failure(f"item {item.id} cites goal {goal}, which the goals file's ## Goals does not number")
return Failure(f"{name} cites goal {goal}, which the goals file's ## Goals does not number")
return None
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
"""The item's row, each cell under its column."""
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
written = row_cells(item, shape) | {"Score": f"{value:.1f}"}
return "| " + " | ".join(written[column] for column in columns) + " |"
@@ -316,7 +342,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure:
return details if isinstance(details, Failure) else text
if unknown := sorted(set(details) - {item.id for item in items}):
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
headed = [f"{detail_heading(item.id, tagline_text(item.tagline))}\n\n{details[item.id]}\n" for item in items if item.id in details]
ranked = "\n" + "\n".join(headed) if headed else "\n"
tail = "\n" if section.end() < len(text) else ""
return text[:section.start(1)] + ranked + tail + text[section.end():]
@@ -10,6 +10,9 @@ VERSION = r"[0-9]+\.[0-9]+\.[0-9]+"
DATE_DIGITS = (4, 2, 2)
DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits in DATE_DIGITS))
TAG = re.compile(rf"v({VERSION})")
# The title of CHANGELOG.md's section for news not yet released: Unreleased, or a title that says unreleased, such as `0.6.0 (unreleased)`, as a project's own changelog may head it; and its ## heading.
UNRELEASED_TITLE = r"(?i:.*unreleased.*)"
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
def release_of(version: str) -> Release:
@@ -5,10 +5,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking, todo_table
from plan import ranking, todo_table
class Blockers(unittest.TestCase):
@@ -4,10 +4,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking
from plan import ranking
class Formula(unittest.TestCase):
@@ -1,7 +1,7 @@
import unittest
from failure import Failure
from release_plan.goals_file import section
from plan.goals_file import section
GOALS_FILE = "# P\n## Goals\n1. g\n## Audience\nme\n"
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.named_code import named_files, named_paths
from plan.named_paths import named_files, named_paths
class NamedPaths(unittest.TestCase):
@@ -12,10 +12,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import goals_file, plan_file, ranking
from plan_store.stores import file_plan
from plan import goals_file, ranking
from project_config.main import located
from repo_checks import ROOT
from release_plan import todo_table
from plan import todo_table
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
VOID = "**Void:** code health, since a test project has no code to read.\n\n"
@@ -271,6 +272,19 @@ class CodeHealth(unittest.TestCase):
"""A scoring run's entry, without the history's title."""
return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read)
def test_a_plan_in_jira_weighs_the_goals_as_todo_md_does(self):
# As the two tests below: code health weighs 1 / 1.97 at or over the floor and four times that under it, goal 1 0.97 / 1.97.
for floor, code_health in ((DEFAULT_FLOOR, 4 / 1.97), (decimal.Decimal("6.0"), 1 / 1.97)):
with self.subTest(floor=floor):
stated = ranking.config_scoring("V", 1, self.readme, "", SCORED.format(overall="6.99"), floor)
assert not isinstance(stated, Failure), stated
self.assertEqual(set(stated.weights), {"code health", "1"})
self.assertAlmostEqual(stated.weights["code health"], code_health)
self.assertAlmostEqual(stated.weights["1"], 0.97 / 1.97)
opted_out = ranking.config_scoring("V", 1, self.readme, "## review opt-out: the comprehension check\n\nCosts rounds.\n", "", DEFAULT_FLOOR)
assert isinstance(opted_out, Failure), opted_out
self.assertTrue(opted_out.reason.startswith("docs/decisions.md opts out of the comprehension check"), opted_out.reason)
def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self):
# Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight.
self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"})
@@ -365,7 +379,7 @@ class CodeHealth(unittest.TestCase):
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
self.assertIsInstance(ranked, ranking.Ranked)
self.assertEqual(ranked.under_bar, [])
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
@@ -382,10 +396,10 @@ class CodeHealth(unittest.TestCase):
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
self.assertIsInstance(ranked, ranking.Ranked)
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
self.assertEqual(plan_file.check_failures(todo, located(temp, pathlib.Path.home())), [])
self.assertEqual(file_plan(located(temp, pathlib.Path.home()), todo).check(), [])
class Risk(unittest.TestCase):
@@ -461,6 +475,16 @@ class OldShape(unittest.TestCase):
def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self):
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list"))
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 9, 8 | 0 |")), Failure("item 3 cites goal 9, 8, which the goal weights do not list"))
def test_refuses_a_bar_or_next_id_that_is_no_number_naming_the_line(self):
for todo, reason in (
(TODO.replace("`Bar = 2`", "`Bar = x`"), "the bar 'x' is not a finite number"),
(TODO.replace("`Next ID = 6`\n", ""), "todo.md states `Next ID = ...` 0 times; state it once, on a line of its own under ## Scoring"),
(TODO.replace("`Next ID = 6`", "`Next ID = x`"), "Next ID 'x' is not a whole number"),
):
with self.subTest(reason=reason):
self.assertEqual(self.ranked(todo), Failure(reason))
def test_refuses_a_formula_over_v(self):
self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses"))
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
from release_plan.release import newest_tag, tagged
from plan.release import newest_tag, tagged
class NewestTag(unittest.TestCase):
@@ -4,7 +4,7 @@ import typing
from failure import Failure
from text_files.markdown_text import FENCE, sections
from release_plan.release import parsed, Release, release_of, VERSION
from plan.release import parsed, Release, release_of, version, VERSION
# Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level.
TOP_SCORE = 10
@@ -43,7 +43,7 @@ class Shape:
risk_columns: tuple[str, ...]
# The scores rank_todo.py works out and writes, so a blank cell reads as no score yet.
derived: tuple[str, ...]
# The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back.
# The column naming the goals an item serves; read_goals reads it, given what a failure calls the item, and write_goals writes it back.
goals_column: str
read_goals: typing.Callable[[str, str], Moves | Failure]
write_goals: typing.Callable[[Moves], str]
@@ -59,17 +59,17 @@ class Shape:
return tuple(column for column in self.columns if column not in self.optional)
def parse_moves(id_: str, cell: str) -> Moves | Failure:
def parse_moves(label: str, cell: str) -> Moves | Failure:
"""A Moves cell: empty, or each goal the item moves, named once, and how far. ranking.py's cited_goals_failure holds the rules that need the goals file."""
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
return Failure(f"{label}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
goals = [goal for goal, _ in moves]
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
return Failure(f"{label} cites goal {repeated[0]} twice; name each goal once")
if nested := [(parent, goal) for parent in goals for goal in goals if goal.startswith(parent + ".")]:
return Failure(f"item {id_} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
return Failure(f"{label} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
return moves
@@ -77,7 +77,7 @@ def write_moves(moves: Moves) -> str:
return ", ".join(f"{goal} by {by}" for goal, by in moves)
def parse_cited(id_: str, cell: str) -> Moves:
def parse_cited(label: str, cell: str) -> Moves:
"""An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move."""
return tuple((goal.strip(), None) for goal in cell.split(","))
@@ -268,49 +268,64 @@ def parse_row(row: str, table: Table) -> Item | Failure:
if isinstance(found, Failure):
return found
named = dict(zip(table.columns, found))
exempt = check_cells(row, named)
if isinstance(exempt, Failure):
return exempt
id_, tagline = named["ID"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
shape = shape_of(table.columns)
scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns)
fields = item_fields({name: cell for name, cell in named.items() if cell or name not in shape.derived}, f"item {id_}", shape, int(id_))
if isinstance(fields, Failure):
return fields
assert fields.release is not None, "table_rows refuses a table without a Release column"
return Item(int(id_), fields.release, fields.exempt, tagline, fields.scores, fields.moves, fields.blocked_by)
@dataclasses.dataclass(frozen=True)
class ItemFields:
"""The cells of an item that a caller named, each held to the items table's format. A cell it didn't name reads as empty, and the release as None."""
release: Release | None = None
exempt: Exempt = ""
scores: dict[str, int] = dataclasses.field(default_factory=dict)
moves: Moves = ()
blocked_by: tuple[int, ...] = ()
def item_fields(named: dict[str, str], label: str, shape: Shape = SHAPE, id_: int | None = None) -> ItemFields | Failure:
"""Each of the Release, Exempt, score, goals and Blocked-by cells that named holds by column name, held to shape's format; the one check every plan backend makes of an item's cells. label opens each message, such as "item 12" or "the item to file". id_ is the item's own ID, which its Blocked by may not name."""
release = named.get("Release")
if release is not None and parsed(release) is None:
return Failure(f"{label}'s Release {release!r} is not a semver version, such as 1.2.0")
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{label}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
scores = parse_scores(label, named, shape.score_columns)
if isinstance(scores, Failure):
return scores
blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, ""))
if isinstance(blocked_by, Failure):
return blocked_by
moves = shape.read_goals(named["ID"], named[shape.goals_column])
moves = shape.read_goals(label, named.get(shape.goals_column, ""))
if isinstance(moves, Failure):
return moves
return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by)
blocked_by = parse_ids(named.get(BLOCKED_BY, ""))
if blocked_by is None:
return Failure(f"{label}'s {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
if id_ in blocked_by:
return Failure(f"{label} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
return ItemFields(None if release is None else release_of(release), exempt, scores, moves, blocked_by)
def is_exempt(cell: str) -> typing.TypeGuard[Exempt]:
return cell in EXEMPTIONS
def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure:
"""Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it."""
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if parsed(release) is None:
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if not is_exempt(exempt):
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
return exempt
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
"""Each score in names that the row holds; only an optional one may be missing, since the table holds every needed column."""
def parse_scores(label: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
"""Each score in names that named holds; only an optional one may be missing, since the table holds every needed column."""
scores: dict[str, int] = {}
for name in names:
if name not in named:
continue
top = LEVELS.get(name, TOP_SCORE)
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= top:
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
return Failure(f"{label}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
scores[name] = int(named[name])
return scores
@@ -322,10 +337,21 @@ def parse_ids(cell: str) -> tuple[int, ...] | None:
return tuple(int(id_) for id_ in cell.split(", ") if id_)
def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure:
blocked_by = parse_ids(cell)
if blocked_by is None:
return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"")
if int(id_) in blocked_by:
return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
return blocked_by
def row_cells(item: Item, shape: Shape) -> dict[str, str]:
"""item's cells by column name, as a row of a table in shape holds them; the Score, which only ranking works out, aside."""
return {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves)}
def tagline_text(cell: str) -> str:
"""The tagline an Item cell holds, as plain text: without the bold, each | unescaped."""
return cell.strip().removeprefix("**").removesuffix("**").replace("\\|", "|")
def detail_heading(id_: int, tagline: str) -> str:
"""The heading under ## Details that opens item id_'s detail; tagline is plain text."""
return f"### {id_}. {tagline}"
def items_shape(found: list[Item]) -> Shape:
"""The shape a table of found needs: OLD_SHAPE where an item holds a score only that shape has, as a plan not yet reshaped does."""
return OLD_SHAPE if any(set(item.scores) - set(SHAPE.score_columns) for item in found) else SHAPE
+10 -3
View File
@@ -1,10 +1,10 @@
"""What every plan backend must hold, as tests. A backend's test case inherits PlanStoreContract and unittest.TestCase, and builds its store in new_store. record_store.contract is its twin for records."""
import typing
from release_plan.todo_table import BLOCKED_BY, Item, MOVES
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan_store.stores import Plan, PlanStore, TAGLINE, Written
from release_plan.release import release_of
from plan_store.plans import Plan, PlanStore, TAGLINE, Written
from plan.release import release_of
FIRST = {"Release": "0.1.0", TAGLINE: "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", MOVES: "1 by 9"}
SECOND = {"Release": "0.2.0", TAGLINE: "Ship the later thing.", "L": "2", "E": "1", "I": "1", "S": "2", MOVES: "1 by 8", "Exempt": "owner"}
@@ -72,6 +72,13 @@ class PlanStoreContract:
self.assertEqual(self.items(store)[id_].release, release_of("0.3.0"))
self.assertEqual(self.items(store)[id_].detail, "")
def test_an_edit_with_a_comment_sets_the_fields_as_one_without(self) -> None:
store = self.new_store()
id_ = self.filed(store, FIRST, "Why it counts.")
self.assertEqual(store.edit(id_, {"L": "2"}, None, "A small change to one module."), Written(id_))
item = self.items(store)[id_]
self.assertEqual((item.scores["L"], item.detail), (2, "Why it counts."))
def test_finish_removes_the_item_and_keeps_the_others(self) -> None:
store = self.new_store()
first, second = self.filed(store, FIRST, "Why it counts."), self.filed(store, SECOND, "Later detail.")
+11 -6
View File
@@ -2,9 +2,9 @@
import dataclasses
from plan_store.markdown_edits import bold_cell, plain
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, no_item, Plan, Written
from failure import Failure
from release_plan.todo_table import Item, parse_row, SHAPE, Table
from plan.todo_table import Item, parse_row, SHAPE, Table
@dataclasses.dataclass
@@ -12,6 +12,8 @@ class MemoryPlan:
"""A plan held in memory, as a tracker holds one: in the order filed, unranked, with no bar. Where fails is set, every read and write fails with it as the reason."""
rows: dict[int, dict[str, str]] = dataclasses.field(default_factory=dict)
details: dict[int, str] = dataclasses.field(default_factory=dict)
# Each comment an edit gave, under its item's ID, as a tracker posts them on the item's issue.
comments: dict[int, list[str]] = dataclasses.field(default_factory=dict)
next_id: int = 1
label: str = "the plan in memory"
tracked: str | None = None
@@ -26,14 +28,17 @@ class MemoryPlan:
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
return self.put(self.next_id, cells(fields), detail)
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
if id_ not in self.rows:
return Failure(f"{self.label} holds no item {id_}")
return self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
return Failure(no_item(self.label, id_))
written = self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
if comment is not None and isinstance(written, Written):
self.comments.setdefault(id_, []).append(comment)
return written
def finish(self, id_: int) -> Written | Failure:
if self.fails or id_ not in self.rows:
return Failure(self.fails or f"{self.label} holds no item {id_}")
return Failure(self.fails or no_item(self.label, id_))
del self.rows[id_]
self.details.pop(id_, None)
return Written(id_)
+221 -102
View File
@@ -1,36 +1,30 @@
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into and finished over Jira's REST API.
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into, edited and finished over Jira's REST API.
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores.
`add` files an item as a new child issue, marked with FILED_BY, and `finish` moves an item's issue to a done status. edit is a Failure until todo.md's item 382."""
import base64
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
import dataclasses
import pathlib
import re
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, no_item, Plan, Written
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from rest_client.env_file import read_env
from plan.release import parsed, Release, tagged
from plan import ranking
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
PROPERTY = "plan-item"
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
# Seconds each connect and each read may wait.
TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
READ_ONLY = "the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
# The key in PROPERTY's value that marks an issue the loop filed, and its value. An edit of an issue without it, which a person filed, writes only PROPERTY and a comment.
FILED_BY = ("Filed by", "loop")
# The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so.
ISSUE_TYPE = "Task"
@@ -43,24 +37,17 @@ DONE = "done"
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again"
# What a failed move ends with, for the same reason.
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
# What a failed edit ends with, for the same reason.
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at {key} before editing the item again"
# The scores a caller sets, L, E, I and S; R is worked out from them.
SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.derived)
# The fields of PROPERTY's value that an edit may set.
SCORED = (*SET_SCORES, MOVES, "Exempt")
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
class ReadsScoring(typing.Protocol):
def read(self) -> ranking.Scoring | Failure:
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
@dataclasses.dataclass(frozen=True)
@@ -73,7 +60,7 @@ class Issue:
# The key of each issue this one "is blocked by".
blockers: tuple[str, ...]
# PROPERTY's value; an empty object where the issue holds none.
scores: object
scores: dict[str, typing.Any]
@property
def number(self) -> int:
@@ -85,11 +72,13 @@ class JiraPlan:
"""The plan under epic, read and written with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
finish_by: Finish | None = None
# How add scores an item: by the config's formula and bar, with the goal weights the project's records give.
scoring: ReadsScoring = dataclasses.field(kw_only=True)
@property
def label(self) -> str:
@@ -110,39 +99,66 @@ class JiraPlan:
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files the item as a child issue, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
"""Files the item as a child issue, where it scores at the config's bar or above or is exempt, and ranks it as `placing` says.
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
Jira takes the links and the rank after the issue. One it refuses leaves the issue filed, so the write counts as landed, and a note says what to do by hand."""
filing = filing_of(fields, detail, self.epic)
if isinstance(filing, Failure):
return filing
scoring = self.scoring.read()
if isinstance(scoring, Failure):
return Failure(f"cannot score the item to file: {scoring.reason}")
value = filed_score(filing.item, scoring)
if isinstance(value, Failure):
return value
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
issue_fields = filing.fields
if detail.strip():
description = self.to_adf(detail)
if isinstance(description, Failure):
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
issue_fields = issue_fields | {"description": description}
description = self.description_of(detail)
if isinstance(description, Failure):
return description
issue_fields = filing.fields | ({"description": description} if description else {})
version = self.fix_version(filing.release, authorization)
if isinstance(version, Failure):
return version
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
return missing
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read.
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
before = placing(answered, filing.item, value, scoring)
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
if isinstance(created, Failure):
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}")
key = created.get("key") if isinstance(created, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key):
return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(epic=self.epic.key)}")
return Written(number(key), self.linked_and_ranked(key, filing.blockers, before, authorization))
def linked_and_ranked(self, key: str, blockers: tuple[str, ...], before: str | None | Failure, authorization: str) -> tuple[str, ...]:
"""Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses."""
notes = []
for blocker in filing.blockers:
for blocker in blockers:
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
if isinstance(linked, Failure):
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
return Written(number(key), tuple(notes))
if isinstance(before, Failure):
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
elif before is not None and (refused := self.rank_refusal(key, before, authorization)):
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
return tuple(notes)
def rank_refusal(self, key: str, before: str, authorization: str) -> str | None:
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
if isinstance(answer, Failure):
return answer.reason
entries = answer.get("entries") if isinstance(answer, dict) else None
refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else []
return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None
def fix_version(self, release: str, authorization: str) -> str | Failure:
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
@@ -151,18 +167,63 @@ class JiraPlan:
if isinstance(versions, Failure):
return Failure(f"cannot read {project}'s Fix Versions: {versions.reason}")
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or file the item under a release it has")
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or name a release it has")
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure:
"""Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_."""
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
key = f"{project_of(self.epic.key)}-{id_}"
found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
return Failure(no_item(self.label, id_)) if found is None else found
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
return Failure(READ_ONLY)
def description_of(self, detail: str) -> dict[str, typing.Any] | None | Failure:
"""The Jira description that holds detail, as ADF; None for a blank detail, which leaves an issue without one."""
if not detail.strip():
return None
description = self.to_adf(detail)
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
A comment Jira refuses leaves the edit made, so the write counts as landed, and a note says to post the comment by hand."""
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
raw = self.child(id_, authorization)
if isinstance(raw, Failure):
return raw
issue = issue_of(raw)
if isinstance(issue, Failure):
return issue
key = issue.key
revision = revision_of(issue, cells(fields), detail, comment)
if isinstance(revision, Failure):
return revision
body = revision.body
if detail is not None:
description = self.description_of(detail)
if isinstance(description, Failure):
return description
body = body | {"fields": body.get("fields", {}) | {"description": description}}
said = self.to_adf(comment) if comment and comment.strip() else None
if isinstance(said, Failure):
return Failure(f"cannot convert the comment to a Jira comment: {said.reason}")
if revision.release is not None:
version = self.fix_version(revision.release, authorization)
if isinstance(version, Failure):
return version
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
url = f"{self.epic.site}/rest/api/3/issue/{key}"
edited = self.http("PUT", url, authorization, body)
if isinstance(edited, Failure):
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
if said is None:
return Written(id_)
posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
return Written(id_, (f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ())
def finish(self, id_: int) -> Written | Failure:
"""Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it."""
@@ -171,12 +232,10 @@ class JiraPlan:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
raw = self.child(id_, authorization)
if isinstance(raw, Failure):
return raw
key = f"{project_of(self.epic.key)}-{id_}"
if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered):
return Failure(f"{self.label} holds no item {id_}")
url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions"
offered = self.http("GET", url, authorization, None)
if isinstance(offered, Failure):
@@ -198,6 +257,8 @@ class Filing:
scores: dict[str, typing.Any]
# The key of each issue the item is blocked by.
blockers: tuple[str, ...]
# The item as ranking scores it, under the ID 0, since Jira numbers it once filed.
item: Item
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
@@ -209,26 +270,97 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
if unfit := unfit_text(summary, detail):
return unfit
release = named.get("Release", "")
if parsed(release) is None:
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
levels = parse_scores("to file", named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
return unfit_moves
if not is_exempt(exempt):
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
blockers = parse_ids(named.get(BLOCKED_BY, ""))
if blockers is None:
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
checked = item_fields(named | {"Release": release}, "the item to file")
if isinstance(checked, Failure):
return checked
assert checked.release is not None, "item_fields refuses an empty Release"
project = project_of(epic.key)
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
if exempt == SECURITY:
if checked.exempt == SECURITY:
issue_fields["labels"] = [SECURITY]
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by))
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
"""The item's score, or why it may not be filed: it lacks a score the formula may use, names a goal it may not, or scores under the bar without being exempt."""
if missing := next((name for name in SET_SCORES if name not in item.scores), None):
return Failure(f"the item to file has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}")
value = ranking.item_score(item, scoring, "the item to file")
if not isinstance(value, Failure) and ranking.falls_under(item, value, scoring.bar):
return Failure(f"the item to file scores {value:.1f}, under the bar {scoring.bar:g}; don't file it, or mark it with a reason the bar doesn't apply")
return value
def placing(answered: list[object], new: Item, value: float, scoring: ranking.Scoring) -> str | None | Failure:
"""The key of the issue to rank the new item, which scores value, just before; None where it stays last, where Jira files it. answered is the epic's open children in backlog order.
Only the issues the loop filed count, so the team's rank of every other issue stays as it is. The new item goes before the first of them that ranks after it as todo.md orders a release's items, blockers aside: a question first, then a security finding, as ranking.FIRST orders them, then the higher score. A tie goes after the older issue. Release doesn't count, as docs/decisions.md records."""
place = (ranking.FIRST.get(new.exempt, len(ranking.FIRST)), -value)
for raw in answered:
issue = issue_of(raw)
if isinstance(issue, Failure):
return issue
if issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
continue
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
if missing := next((name for name in SET_SCORES if name not in scored.scores), None):
return Failure(f"{issue.key} holds no {missing}")
# Only the scores and the moves change a score.
other = ranking.item_score(dataclasses.replace(new, scores=scored.scores, moves=scored.moves), scoring, issue.key)
if isinstance(other, Failure):
return other
if (ranking.FIRST.get(scored.exempt, len(ranking.FIRST)), -other) > place:
return issue.key
return None
@dataclasses.dataclass(frozen=True)
class Revision:
"""An edit checked as far as the issue and the flags allow. The description, the comment and the Fix Version's name still need the codec or a request."""
# The body of the request that edits the issue, without its description and its Fix Version.
body: dict[str, typing.Any]
# The release to move the issue to; None where the edit names none.
release: str | None
def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure:
"""The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made.
The summary, description and Fix Version of an issue a person filed are the team's, so there an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. No edit changes a link."""
held = issue.scores
if BLOCKED_BY in named:
return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira")
own = held.get(FILED_BY[0]) == FILED_BY[1]
if not own and ("Item" in named or "Release" in named or detail is not None):
return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description and Fix Version in Jira")
if not own and not (comment and comment.strip()):
return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why")
body: dict[str, typing.Any] = {}
if "Item" in named:
summary = plain(named["Item"]).strip()
if not summary:
return Failure("the item has no tagline")
body["fields"] = {"summary": summary}
if unfit := unfit_text(named.get("Item", ""), detail or ""):
return unfit
release = named.get("Release")
if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, f"item {issue.key}"), Failure):
return checked
if any(name in named for name in SCORED):
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
scored = scores(issue.key, texts)
if isinstance(scored, Failure):
return scored
if scored.scores and any(name not in scored.scores for name in SET_SCORES):
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
value = held | scored.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt}
body["properties"] = [{"key": PROPERTY, "value": value}]
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
return Revision(body, release)
def offer_of(raw: object) -> tuple[str, str, str, str] | None:
@@ -265,16 +397,8 @@ def project_of(key: str) -> str:
return key.rpartition("-")[0]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
"""The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan."""
"""The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan."""
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
if isinstance(seen, Failure):
@@ -302,14 +426,19 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu
def issue_of(raw: object) -> Issue | Failure:
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
# The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it.
try:
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
fields = raw["fields"]
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
held = raw.get("properties", {}).get(PROPERTY, {})
summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"])
except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
issue = Issue(key, summary, description, versions, blockers, held)
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value")
return issue
@@ -350,13 +479,12 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
release = earliest_release(issue.fix_versions)
if release is None:
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "")
def earliest_release(names: tuple[str, ...]) -> Release | None:
@@ -365,18 +493,9 @@ def earliest_release(names: tuple[str, ...]) -> Release | None:
return min(releases, default=None)
def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure:
def scores(key: str, held: dict[str, typing.Any]) -> ItemFields | Failure:
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
named = {name: str(value) for name, value in held.items()}
levels = parse_scores(key, named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves = parse_moves(key, named.get(MOVES, ""))
if isinstance(moves, Failure):
return moves
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
return levels, moves, exempt
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
checked = item_fields(named, f"item {key}")
# Jira's screens don't show PROPERTY, so the message says where the value is.
return Failure(f"{checked.reason}; {key} holds it in its issue property {PROPERTY}") if isinstance(checked, Failure) else checked
+6 -5
View File
@@ -1,9 +1,10 @@
"""The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells."""
import re
from release_plan.todo_table import cells, DETAILS, item_details, items_table, Table
from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text
from failure import Failure
from release_plan.ranking import stated
from plan_store.plans import no_item
from plan.ranking import stated
# A line that would end ## Details (##) or could open another item's detail (###).
HEADING = re.compile(r"^#{2,3} ", re.M)
@@ -47,7 +48,7 @@ def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label
if isinstance(details, Failure):
return details
row = dict(zip(table.columns, held))
tagline = plain(named["Item"]) if "Item" in named else plain(row["Item"]).replace("\\|", "|")
tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"])
kept = details.get(id_, "") if detail is None else detail
if unfit := unfit_text(tagline, "" if detail is None else detail):
return unfit
@@ -90,7 +91,7 @@ def with_detail(text: str, id_: int, tagline: str, detail: str) -> str:
"""text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank."""
if not detail.strip():
return text
entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n"
entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n"
section = DETAILS.search(text)
if section is None:
return text.rstrip("\n") + f"\n\n## Details\n\n{entry}"
@@ -113,7 +114,7 @@ def row_index(table: Table, id_: int, label: str) -> int | Failure:
return found
if found[0] == str(id_):
return at
return Failure(f"{label} holds no item {id_}")
return Failure(no_item(label, id_))
def held_table(lines: list[str], label: str) -> Table | Failure:
+73
View File
@@ -0,0 +1,73 @@
"""What every plan backend reads and writes: a Plan, a Written, the PlanStore protocol they all meet, and the fields a caller may set on an item."""
import dataclasses
import typing
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan.release import Release
TAGLINE = "Tagline"
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
@dataclasses.dataclass(frozen=True)
class Plan:
"""A plan as one read found it."""
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
items: list[Item]
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
renamed: frozenset[Release] = frozenset()
@dataclasses.dataclass(frozen=True)
class Written:
"""A write that landed."""
id: int
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
notes: tuple[str, ...] = ()
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost."""
@property
def label(self) -> str:
"""What a message calls the plan, such as its path."""
@property
def tracked(self) -> str | None:
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
def read(self) -> Plan | Failure:
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
def finish(self, id_: int) -> Written | Failure:
"""Removes item id_ with its detail."""
def no_item(label: str, id_: int | str) -> str:
"""What every store says of an item id_ that the plan label names doesn't hold. `chunk-pr merge` reads `todo-item show`'s answer by it, through says_no_item."""
return f"{label} holds no item {id_}"
def says_no_item(reason: str, id_: int | str) -> bool:
"""Whether a failure's reason, such as `todo-item show`'s, says the plan doesn't hold item id_, as no_item words it."""
return no_item("", id_) in reason
def cells(fields: dict[str, str]) -> dict[str, str]:
"""fields by the items table's column names."""
unknown = set(fields) - set(FIELDS)
if unknown:
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
+39
View File
@@ -0,0 +1,39 @@
"""The goal weights a plan is ranked by, read from the goals file, the decision log and the comprehension history, for the markdown plan and for the scoring of a plan in Jira."""
import dataclasses
import decimal
from failure import Failure
from project_config.settings import JiraScoring
from plan import ranking
from record_store.stores import RecordStore
# What the reader of a missing or empty goals file is told.
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
@dataclasses.dataclass(frozen=True)
class StatedScoring:
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
stated: JiraScoring
goals: RecordStore
decisions: RecordStore
history: RecordStore
floor: decimal.Decimal
def read(self) -> ranking.Scoring | Failure:
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
goals_text = goals.read()
if isinstance(goals_text, Failure):
return goals_text
if not goals_text:
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
decisions_text = decisions.read()
if isinstance(decisions_text, Failure):
return decisions_text
history_text = history.read()
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
+11 -179
View File
@@ -1,163 +1,30 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
The config's `plan` setting names the backend. A path names a markdown file, todo.md, which `todo_md` keeps. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
import decimal
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import pathlib
import typing
from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.stores import goals_store, store as record_store, RecordStore
from plan_store import markdown_edits
from plan_store.todo_md import FilePlan, plan_of
from record_store.stores import goals_store, store as record_store
from plan_store.jira_epic import JiraPlan
from plan_store.plans import Plan, PlanStore
from project_config.settings import ProjectConfig
from release_plan import ranking
from release_plan.release import Release
from text_files.file_writes import replace_file
TAGLINE = "Tagline"
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
# What the reader of a missing todo.md is told.
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
# What the reader of a missing or empty goals file is told.
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
@dataclasses.dataclass(frozen=True)
class Plan:
"""A plan as one read found it."""
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
items: list[Item]
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
renamed: frozenset[Release] = frozenset()
@dataclasses.dataclass(frozen=True)
class Written:
"""A write that landed."""
id: int
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
notes: tuple[str, ...] = ()
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads, files and finishes, and fails an edit until todo.md's item 382. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue or to a move is lost."""
@property
def label(self) -> str:
"""What a message calls the plan, such as its path."""
@property
def tracked(self) -> str | None:
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
def read(self) -> Plan | Failure:
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release."""
def finish(self, id_: int) -> Written | Failure:
"""Removes item id_ with its detail."""
@dataclasses.dataclass(frozen=True)
class FilePlan:
"""A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
path: pathlib.Path
tracked: str | None
goals: RecordStore
decisions: RecordStore
history: RecordStore
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
floor: decimal.Decimal
@property
def label(self) -> str:
return str(self.path)
def read(self) -> Plan | Failure:
if not self.path.exists():
return NoItemsTable(f"{self.path}: not found; {MISSING}")
text = read_text(self.path, MISSING)
return text if isinstance(text, Failure) else plan_of(text)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
ranked = ranking.rank(text, *texts[1:], self.floor)
if isinstance(ranked, Failure):
return ranked
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
return Failure(under[0])
return self.written(id_, ranked)
def finish(self, id_: int) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:], self.floor)
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
"""Writes ranked's text to the file."""
unwritten = replace_file(self.path.resolve(), ranked.text.encode("utf-8"))
if unwritten:
return Failure(f"{self.path}: {unwritten.reason}")
return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar))
def texts(self) -> tuple[str, str, str, str] | Failure:
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
goals = self.goals.read()
if isinstance(goals, Failure):
return goals
if not goals:
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
decisions = self.decisions.read()
if isinstance(decisions, Failure):
return decisions
history = self.history.read()
return history if isinstance(history, Failure) else (plan, goals, decisions, history)
from plan_store.scoring import StatedScoring
def store(config: ProjectConfig) -> PlanStore:
"""The store config names for the plan."""
if config.epic is None:
return file_plan(config)
# Imported here, since jira_epic builds on this module's Plan and Written.
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish)
# load refuses a config that names an epic and no formula or bar.
assert config.jira_scoring is not None
scoring = StatedScoring(config.jira_scoring, goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor)
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish, scoring=scoring)
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
@@ -171,38 +38,3 @@ def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan |
return plan.read()
text = file_at(revision, plan.tracked, cwd, run)
return text if isinstance(text, Failure) else plan_of(text)
def plan_of(todo: str) -> Plan | Failure:
"""The plan a todo.md's text holds."""
found = items(todo)
if isinstance(found, Failure):
return found
details = item_details(todo)
if isinstance(details, Failure):
return details
marked = renames(todo)
if isinstance(marked, Failure):
return marked
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
def cells(fields: dict[str, str]) -> dict[str, str]:
"""fields by the items table's column names."""
unknown = set(fields) - set(FIELDS)
if unknown:
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
"""path's text; where it is missing, a Failure saying missing."""
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; {missing}")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
+289 -40
View File
@@ -1,4 +1,5 @@
import base64
import dataclasses
import pathlib
import sys
import tempfile
@@ -7,13 +8,14 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, Finish
from release_plan.todo_table import EXEMPTIONS
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
from plan.todo_table import EXEMPTIONS
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan, Written
from plan_store.plans import Plan, Written
from plan import ranking
from adf_codec.convert import Refused
from release_plan.release import release_of
from plan.release import release_of
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
@@ -63,7 +65,7 @@ class JiraPlan(unittest.TestCase):
return [text_of(document) for document in documents]
def store(self) -> jira_epic.JiraPlan:
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown, scoring=Stated())
def read(self, *issues: dict[str, object]) -> Plan | Failure:
self.pages, self.calls = [{"issues": list(issues)}], []
@@ -142,7 +144,7 @@ class JiraPlan(unittest.TestCase):
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security; ABC-34 holds it in its issue property plan-item"))
def test_reads_every_page(self):
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
@@ -181,12 +183,12 @@ class JiraPlan(unittest.TestCase):
self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]])
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")))
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")), scoring=Stated())
self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}]
self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused"))
def test_a_codec_that_cannot_run_fails_the_read(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"))
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"), scoring=Stated())
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed"))
@@ -210,10 +212,6 @@ class JiraPlan(unittest.TestCase):
self.pages = [{"issues": [issue("OTHER-5")]}]
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
def test_edit_fails_since_the_store_does_not_edit_yet(self):
self.assertEqual(self.store().edit(34, {"L": "2"}, None), Failure("the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"))
self.assertEqual(self.calls + self.epic_calls, [])
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
@@ -224,6 +222,24 @@ VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions"
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again"
FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"}
PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"}
RANK = "https://acme.atlassian.net/rest/agile/1.0/issue/rank"
# Goal 1 weighs 1 and goal 2, a maintain goal, 0.5, so under the formula V / 2**S, FIELDS scores 9 / 2 = 4.5.
README = "# P\n\n## Goals\n\n**Void:** code health, since a test project has no code to read.\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n\n## Audience\n\nMe.\n"
@dataclasses.dataclass(frozen=True)
class Stated:
"""Stands in for the scoring a project's config states, with the goal weights README gives."""
formula: str = "V / 2**S"
bar: float = 1
def read(self) -> ranking.Scoring | Failure:
return ranking.config_scoring(self.formula, self.bar, README, "", "", DEFAULT_FLOOR)
def filed(key: str, moves: str = "1 by 9", s: int = 1, exempt: str = "") -> dict[str, object]:
"""An open child the loop filed, which scores 9 / 2**s with moves "1 by 9"."""
return issue(key, scores=PROPERTY | {"Moves": moves, "S": s, "Exempt": exempt})
class Filing(unittest.TestCase):
@@ -236,25 +252,27 @@ class Filing(unittest.TestCase):
self.created: object = {"id": "10040", "key": "ABC-40"}
self.linked: object = None
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}, "odd", {"name": ["0.1.0"]}, {"name": {"en": "0.1.0"}}]
self.ranked: object = None
self.scoring = Stated()
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue and self.linked to a new link."""
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue, self.linked to a new link and self.ranked to a rank."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions, RANK: self.ranked}.get(url, {"key": "ABC-12"})
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
return adf(markdown)
def add(self, fields: dict[str, str] = FIELDS, detail: str = ""):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf).add(fields, detail)
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=self.scoring).add(fields, detail)
def sent(self, url: str) -> list[object]:
return [body for _, sent_to, body in self.calls if sent_to == url]
def test_files_the_item_as_a_task_under_the_epic_marked_as_the_loops(self):
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.calls, [("GET", VERSIONS, None), ("POST", ISSUES, {
self.assertEqual([call for call in self.calls if call[1] != SEARCH and "/issue/ABC-12" not in call[1]], [("GET", VERSIONS, None), ("POST", ISSUES, {
"fields": {"project": {"key": "ABC"}, "parent": {"key": "ABC-12"}, "issuetype": {"name": "Task"}, "summary": "Count the runs.", "fixVersions": [{"name": "0.1.0"}]},
"properties": [{"key": "plan-item", "value": PROPERTY}],
})])
@@ -297,9 +315,9 @@ class Filing(unittest.TestCase):
def test_each_field_out_of_format_fails_saying_how(self):
cases = (
({"Tagline": "** **"}, "the item has no tagline"),
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
({"L": "9"}, "the item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item to file's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
)
for change, reason in cases:
with self.subTest(change=change):
@@ -307,6 +325,7 @@ class Filing(unittest.TestCase):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Tagline"}), Failure("the item has no tagline"))
def test_an_item_without_moves_files_with_none(self):
self.scoring = Stated(bar=0)
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Moves"}), Written(40))
self.assertEqual(self.sent(ISSUES)[0]["properties"][0]["value"]["Moves"], "") # type: ignore[index]
@@ -315,7 +334,7 @@ class Filing(unittest.TestCase):
self.add(FIELDS | {"Colour": "red"})
def test_an_item_without_a_release_fails_naming_the_field(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item to file's Release '' is not a semver version, such as 1.2.0"))
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
@@ -346,7 +365,7 @@ class Filing(unittest.TestCase):
for versions in ([{"name": "0.1.0"}], {"name": "0.3.0"}, [], 7):
with self.subTest(versions=versions):
self.versions = versions
self.assertEqual(self.add(FIELDS | {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or file the item under a release it has"))
self.assertEqual(self.add(FIELDS | {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or name a release it has"))
self.assertEqual(self.sent(ISSUES), [])
def test_fix_versions_that_cannot_be_read_fail_before_anything_is_filed(self):
@@ -371,10 +390,258 @@ class Filing(unittest.TestCase):
self.assertIsInstance(self.add(), Failure)
self.assertEqual(self.calls, [])
def test_an_item_under_the_bar_fails_before_any_request(self):
self.assertEqual(self.add(FIELDS | {"Moves": "2 by 1", "S": "3"}), Failure("the item to file scores 0.1, under the bar 1; don't file it, or mark it with a reason the bar doesn't apply"))
self.assertEqual(self.calls, [])
def test_the_bar_holds_the_score_rounded_to_one_decimal(self):
for formula, bar, filed_ in (("0.96", 1, True), ("0.6", 0.7, False)):
with self.subTest(formula=formula, bar=bar):
self.scoring = Stated(formula=formula, bar=bar)
self.assertEqual(self.add() == Written(40), filed_)
def test_an_exempt_item_under_the_bar_files(self):
self.assertEqual(self.add(FIELDS | {"Moves": "", "Exempt": "owner"}), Written(40))
def test_an_item_that_names_a_goal_the_goals_file_lacks_fails_before_any_request(self):
self.assertEqual(self.add(FIELDS | {"Moves": "3 by 1"}), Failure("the item to file cites goal 3, which the goals file's ## Goals does not number"))
self.assertEqual(self.calls, [])
def test_an_item_without_every_score_fails_before_any_request(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "S"}), Failure("the item to file has no S: score it on L, E, I and S"))
self.assertEqual(self.calls, [])
def test_a_formula_that_does_not_parse_fails_before_any_request(self):
self.scoring = Stated(formula="V +")
self.assertEqual(self.add(), Failure("cannot score the item to file: the formula 'V +' does not parse"))
self.assertEqual(self.calls, [])
def test_a_formula_that_gives_the_item_no_finite_score_fails_before_any_request(self):
self.scoring = Stated(formula="1 ** (1 / (S - S))")
self.assertEqual(self.add(), Failure("the formula gives the item to file no finite score"))
self.assertEqual(self.calls, [])
def test_ranks_the_item_just_before_the_first_issue_the_loop_filed_that_scores_lower(self):
# ABC-30 and ABC-33 are a person's, ABC-31 a security finding, and ABC-32 scores as much as the new item.
self.open = [issue("ABC-30"), filed("ABC-31", s=4, exempt="security"), filed("ABC-32"), issue("ABC-33", scores={"L": 1, "E": 1, "I": 1, "S": 4, "Moves": "1 by 1"}), filed("ABC-34", s=2), filed("ABC-35", s=3)]
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-34"}])
self.assertEqual([method for method, url, _ in self.calls if url == RANK], ["PUT"])
def test_ranks_a_security_finding_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
self.open = [issue("ABC-30"), filed("ABC-31", exempt="security"), filed("ABC-32"), filed("ABC-33", s=4)]
self.assertEqual(self.add(FIELDS | {"Exempt": "security", "S": "4"}), Written(40))
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
def test_ranks_a_question_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
self.open = [filed("ABC-31", exempt="question"), filed("ABC-32", s=4, exempt="security")]
self.assertEqual(self.add(FIELDS | {"Exempt": "question"}), Written(40))
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
def test_leaves_the_item_last_where_no_issue_the_loop_filed_scores_lower(self):
self.open = [issue("ABC-30", scores={}), filed("ABC-31"), filed("ABC-32", s=2, exempt="security")]
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.sent(RANK), [])
def test_a_rank_jira_refuses_leaves_the_item_filed_with_a_note(self):
self.open = [filed("ABC-34", s=2)]
refusals = (
(Failure("PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"), "PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"),
({"entries": [{"issueKey": "ABC-40", "status": 400, "errors": ["Rank is not configured"]}]}, "Rank is not configured"),
({"entries": [{"status": 200}, {"status": 400}, {"status": 404, "errors": ["gone", "locked"]}]}, "Jira answered 400; gone; locked"),
)
for answer, reason in refusals:
with self.subTest(answer=answer):
self.ranked = answer
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it before ABC-34: {reason}; rank it in Jira",)))
def test_an_issue_the_loop_filed_that_does_not_score_leaves_the_item_filed_unranked_with_a_note(self):
unscored = {name: value for name, value in PROPERTY.items() if name != "S"}
for open_, reason in (
(filed("ABC-34", moves="3 by 1", s=2), "ABC-34 cites goal 3, which the goals file's ## Goals does not number"),
(issue("ABC-34", scores=unscored), "ABC-34 holds no S"),
(issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"),
):
with self.subTest(reason=reason):
self.calls.clear()
self.open = [open_]
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it: {reason}; rank it in Jira",)))
self.assertEqual(self.sent(RANK), [])
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
COMMENT = "Scored for planning: a small change to one module."
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at ABC-34 before editing the item again"
class Editing(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.calls: list[tuple[str, str, object]] = []
# The loop filed ABC-34. A person filed ABC-35, which nobody scored, and ABC-36, which holds scores.
self.open: list[object] = [issue("ABC-34", scores=PROPERTY), issue("ABC-35"), issue("ABC-36", scores={"L": 3, "E": 1, "I": 1, "S": 2})]
self.edited: object = None
self.commented: object = {"id": "10100"}
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}]
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit and self.commented to a new comment."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
if method == "PUT":
return self.edited
return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
return adf(markdown)
def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment)
def writes(self) -> list[tuple[str, str, object]]:
"""Each request that changes Jira, in order."""
return [call for call in self.calls if call[0] == "PUT" or call[1].endswith("/comment")]
def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self):
self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34))
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {
"fields": {"summary": "Count every run.", "description": adf("Why it counts.")},
"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2, "Moves": ""}}],
})])
def test_sends_only_what_the_edit_names(self):
self.edit(34, {"Tagline": "Count every run."})
self.edit(34, {"E": "3"})
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
def test_an_empty_detail_removes_the_description(self):
self.edit(34, {}, " \n")
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})])
def test_an_edit_of_the_release_sets_the_fix_version_as_the_project_spells_it(self):
self.assertEqual(self.edit(34, {"Release": "0.2.0"}), Written(34))
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"fixVersions": [{"name": "v0.2.0"}]}})])
def test_an_edit_of_the_release_and_the_tagline_sends_both(self):
self.edit(34, {"Release": "0.2.0", "Tagline": "Count every run."})
self.assertEqual(self.writes()[0][2], {"fields": {"summary": "Count every run.", "fixVersions": [{"name": "v0.2.0"}]}})
def test_an_empty_tagline_fails_before_any_write(self):
self.assertEqual(self.edit(34, {"Tagline": "** **"}), Failure("the item has no tagline"))
self.assertEqual(self.writes(), [])
def test_a_release_the_project_has_no_fix_version_for_fails_before_any_write(self):
self.assertEqual(self.edit(34, {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or name a release it has"))
self.assertEqual(self.writes(), [])
def test_an_exempt_that_becomes_or_stops_being_security_adds_or_removes_the_label(self):
self.edit(34, {"Exempt": "security"})
self.open = [issue("ABC-34", scores=PROPERTY | {"Exempt": "security"})]
self.edit(34, {"Exempt": "owner"})
self.edit(34, {"Exempt": "security"})
self.assertEqual([body.get("update") for _, _, body in self.writes()], [{"labels": [{"add": "security"}]}, {"labels": [{"remove": "security"}]}, None]) # type: ignore[attr-defined]
def test_scores_an_issue_a_person_filed_and_comments_why(self):
self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35))
self.assertEqual(self.writes(), [
("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}),
("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}),
])
def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self):
self.edit(36, {"L": "2"}, None, COMMENT)
self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]})
def test_a_persons_issue_is_never_labelled(self):
self.edit(36, {"Exempt": "security"}, None, COMMENT)
self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator]
def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self):
for comment in (None, "", " \n"):
with self.subTest(comment=comment):
self.assertEqual(self.edit(35, {"L": "2"}, None, comment), Failure("a person filed ABC-35, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why"))
self.assertEqual(self.writes(), [])
def test_what_a_person_wrote_or_planned_is_never_edited(self):
for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")):
with self.subTest(fields=fields, detail=detail):
self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description and Fix Version in Jira"))
self.assertEqual(self.writes(), [])
def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self):
self.assertEqual(self.edit(35, {"L": "2", "E": "2"}, None, COMMENT), Failure("ABC-35 would hold some of L, E, I, S and not the rest: set them together"))
self.assertEqual(self.edit(35, {"Exempt": "question"}, None, COMMENT), Written(35))
self.assertEqual(len(self.writes()), 2)
def test_a_comment_on_an_edit_of_the_loops_own_issue_is_posted_too(self):
self.edit(34, {"L": "2"}, None, COMMENT)
self.assertEqual(self.writes()[1], ("POST", f"{ISSUES}/ABC-34/comment", {"body": adf(COMMENT)}))
def test_a_comment_jira_refuses_leaves_the_edit_made_with_a_note(self):
self.commented = Failure("HTTP 403")
self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",)))
def test_an_edit_of_the_blockers_fails_since_the_store_changes_no_link(self):
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Failure("the loop doesn't change an issue's links: link ABC-34 in Jira"))
self.assertEqual(self.writes(), [])
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self):
self.assertEqual(self.edit(40, {"L": "2"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40"))
self.assertEqual(self.writes(), [])
def test_each_field_out_of_format_fails_before_any_write_saying_how(self):
for fields, detail, reason in (
({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"),
({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"),
({"Exempt": "tired"}, None, f"item ABC-34's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Release": "soon"}, None, "item ABC-34's Release 'soon' is not a semver version, such as 1.2.0"),
({"Tagline": " "}, None, "the item has no tagline"),
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
({}, "## Why", "the detail holds a ## or ### heading"),
):
with self.subTest(fields=fields, detail=detail):
failed = self.edit(34, fields, detail)
self.assertIsInstance(failed, Failure)
self.assertIn(reason, failed.reason)
self.assertEqual(self.writes(), [])
def test_a_detail_or_a_comment_that_does_not_convert_fails_before_any_write(self):
self.to_adf = lambda markdown: Failure("the codec is down") # type: ignore[method-assign]
self.assertEqual(self.edit(34, {}, "Why."), Failure("cannot convert the item's detail to a Jira description: the codec is down"))
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure("cannot convert the comment to a Jira comment: the codec is down"))
self.assertEqual(self.writes(), [])
def test_an_edit_jira_refuses_fails_with_jiras_reason_and_posts_no_comment(self):
self.edited = Failure("HTTP 400: Summary is too long")
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure(f"cannot edit ABC-34: HTTP 400: Summary is too long; {PERHAPS_EDITED}"))
self.assertEqual(len(self.writes()), 1)
def test_an_issue_in_another_shape_or_a_search_that_fails_fails_the_edit(self):
self.open = [{"key": "ABC-34", "fields": {}}]
self.assertIn("ABC-34 is not in the shape", self.edit(34, {"L": "2"}).reason)
self.open = [issue("ABC-34", scores=["odd"])] # type: ignore[arg-type]
self.assertEqual(self.edit(34, {"L": "2"}), Failure("ABC-34's issue property plan-item is not a JSON object"))
self.assertEqual(self.writes(), [])
def test_a_missing_env_file_fails_before_any_request(self):
self.env.unlink()
self.assertIsInstance(self.edit(34, {"L": "2"}), Failure)
self.assertEqual(self.calls, [])
def test_what_it_edits_reads_back_as_the_item(self):
self.edit(34, {"Tagline": "Count every run.", "S": "4"}, "Why it counts.")
body = self.writes()[0][2]
held = issue("ABC-34", summary=body["fields"]["summary"], scores=body["properties"][0]["value"], description=body["fields"]["description"]) # type: ignore[index]
self.open = [held]
plan = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], scoring=Stated()).read()
assert isinstance(plan, Plan), plan
self.assertEqual((plan.items[0].tagline, plan.items[0].scores["S"], plan.items[0].scores["L"], plan.items[0].detail), ("**Count every run.**", 4, 1, "Why it counts."))
def transition(id_: str, name: str, status: str, category: str = "done") -> dict[str, object]:
return {"id": id_, "name": name, "to": {"name": status, "statusCategory": {"key": category}}}
@@ -398,7 +665,7 @@ class Finishing(unittest.TestCase):
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
def finish(self, id_: int = 34, by: Finish | None = Finish("Mark as done", "Done")):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by).finish(id_)
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by, scoring=Stated()).finish(id_)
def posts(self) -> list[tuple[str, str, object]]:
return [call for call in self.calls if call[0] == "POST" and call[1] != SEARCH]
@@ -457,24 +724,6 @@ class Finishing(unittest.TestCase):
self.assertEqual(self.calls, [])
class Requests(unittest.TestCase):
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(jira_epic.error_message(answer), message)
if __name__ == "__main__":
unittest.main()
+45 -19
View File
@@ -8,23 +8,23 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, ProjectConfig, SETTINGS
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, JiraScoring, ProjectConfig, SETTINGS
from failure import Failure
from record_store.stores import FileStore
from record_store.stores import FileStore, goals_store, store as record_store
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from release_plan.test_ranking import README, SCORED, VOID
from release_plan.release import release_of
from plan_store import stores
from plan.todo_table import NoItemsTable
from plan_store import plans, scoring, stores, todo_md
from plan.test_ranking import README, SCORED, VOID
from plan.release import release_of
EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
class MemoryPlanContract(PlanStoreContract, unittest.TestCase):
def new_store(self) -> stores.PlanStore:
def new_store(self) -> plans.PlanStore:
return MemoryPlan()
@@ -32,10 +32,10 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def new_store(self) -> stores.FilePlan:
def new_store(self) -> todo_md.FilePlan:
(self.folder / "todo.md").write_text(EMPTY)
(self.folder / "README.md").write_text(README)
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
return todo_md.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
class FilePlan(FilePlanContract):
@@ -62,7 +62,7 @@ class FilePlan(FilePlanContract):
def test_an_edited_tagline_heads_the_detail_too(self):
store = self.new_store()
id_ = self.filed(store, FIRST, "Why it counts.")
store.edit(id_, {stores.TAGLINE: "Count `a | b` runs."}, None)
store.edit(id_, {plans.TAGLINE: "Count `a | b` runs."}, None)
text = (self.folder / "todo.md").read_text()
self.assertIn("| **Count `a \\| b` runs.** |", text)
self.assertIn(f"### {id_}. Count `a | b` runs.\n\nWhy it counts.\n", text)
@@ -84,7 +84,7 @@ class FilePlan(FilePlanContract):
self.assertEqual(self.filed(store, FIRST), 10)
todo.write_text("".join(line.replace("| 4 | 1 | 1 by 9 |", "| 4 | 10 | 1 by 9 |") if line.startswith("| 10 ") else line for line in todo.read_text().splitlines(keepends=True)))
written = store.edit(first, {"E": "2"}, None)
assert isinstance(written, stores.Written), written
assert isinstance(written, plans.Written), written
self.assertIn("item 10 ", written.notes[0])
def test_an_id_it_holds_no_item_for_fails_naming_the_file(self):
@@ -118,7 +118,7 @@ class FilePlan(FilePlanContract):
def test_reads_the_releases_marked_renamed(self):
store = self.new_store()
(self.folder / "todo.md").write_text(EMPTY + "\n## Renamed\n\n- 0.2.1 renamed to 0.3.0\n")
self.assertEqual(store.read(), stores.Plan([], frozenset({release_of("0.2.1")})))
self.assertEqual(store.read(), plans.Plan([], frozenset({release_of("0.2.1")})))
def test_a_field_it_does_not_know_is_a_programming_error(self):
with self.assertRaises(ValueError):
@@ -130,9 +130,9 @@ class FilePlan(FilePlanContract):
id_ = self.filed(store, FIRST)
before = (self.folder / "todo.md").read_text()
broken, split = "the tagline holds a line break; keep it on one line", "the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s"
self.assertEqual(store.add(FIRST | {stores.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST | {plans.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST, "## Why\n"), Failure(split))
self.assertEqual(store.edit(id_, {stores.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {plans.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {}, "### Why\n"), Failure(split))
self.assertEqual((self.folder / "todo.md").read_text(), before)
@@ -157,7 +157,7 @@ class FilePlan(FilePlanContract):
(self.folder / "README.md").write_text(README.replace(VOID, ""))
kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND)
row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")]
self.assertIsInstance(store.finish(finished), stores.Written)
self.assertIsInstance(store.finish(finished), plans.Written)
self.assertIn(row[0], (self.folder / "todo.md").read_text())
return row[0]
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
@@ -200,21 +200,47 @@ class Store(unittest.TestCase):
def test_a_path_picks_the_markdown_file(self):
config = self.config()
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
self.assertEqual((type(picked), picked.label, picked.tracked), (todo_md.FilePlan, "/checkout/todo.md", "todo.md"))
def test_the_markdown_file_ranks_with_the_configs_floor(self):
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V", 1)))
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http, scoring=picked.scoring))
def test_an_epic_finishes_an_item_as_the_config_says(self):
finish = Finish("Mark as done", "Done")
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish))
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish, jira_scoring=JiraScoring("V", 1)))
self.assertEqual(picked.finish_by, finish)
def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self):
config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5"))
picked = stores.store(config)
self.assertEqual(picked.scoring, scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
class StatedScoring(unittest.TestCase):
def test_weighs_the_goals_the_goals_file_holds(self):
weighed = scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual((weighed.bar, list(weighed.goals)), (1.5, ["1", "2", "2.1"]))
def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self):
for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)):
with self.subTest(floor=floor):
weighed = scoring.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual(weighed.weights["code health"] > weighed.weights["1"] * 2, under)
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
with self.subTest(reason=reason):
read = scoring.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(reason), read.reason)
if __name__ == "__main__":
unittest.main()
+141
View File
@@ -0,0 +1,141 @@
"""A plan kept as a markdown file, todo.md, in the shape `rank_todo.py --help` shows: read, filed into, edited, finished, and ranked or checked in place."""
import dataclasses
import decimal
import pathlib
from plan_store.plans import cells, Plan, Written
from failure import Failure
from plan.todo_table import item_details, items, NoItemsTable, renames
from plan_store import markdown_edits
from plan import ranking
from record_store.stores import RecordStore
from text_files.file_writes import replace_file
from plan_store.scoring import weighing_texts
# What the reader of a missing todo.md is told.
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
@dataclasses.dataclass(frozen=True)
class FilePlan:
"""A plan kept as a markdown file at path. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
path: pathlib.Path
tracked: str | None
goals: RecordStore
decisions: RecordStore
history: RecordStore
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
floor: decimal.Decimal
@property
def label(self) -> str:
return str(self.path)
def read(self) -> Plan | Failure:
if not self.path.exists():
return NoItemsTable(f"{self.path}: not found; {MISSING}")
text = read_text(self.path, MISSING)
return text if isinstance(text, Failure) else plan_of(text)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
ranked = ranking.rank(text, *texts[1:], self.floor)
if isinstance(ranked, Failure):
return ranked
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
return Failure(under[0])
return self.written(id_, ranked)
def finish(self, id_: int) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:], self.floor)
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
def rank(self) -> ranking.Ranked | Failure:
"""Ranks the file in place, writing it where ranking changed it. The caller prints `reported`'s lines."""
texts = self.texts()
if isinstance(texts, Failure):
return texts
ranked = ranking.rank(*texts, self.floor)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := self.replaced(ranked.text)):
return unwritten
return ranked
def check(self) -> list[str]:
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, or an item scores under the bar."""
texts = self.texts()
if isinstance(texts, Failure):
return [texts.reason]
ranked = ranking.rank(*texts, self.floor)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"]
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar]
def reported(self, ranked: ranking.Ranked) -> list[str]:
"""Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr."""
return [f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar]
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
"""Writes ranked's text to the file."""
return self.replaced(ranked.text) or Written(id_, tuple(self.reported(ranked)))
def replaced(self, text: str) -> Failure | None:
unwritten = replace_file(self.path.resolve(), text.encode("utf-8"))
return Failure(f"{self.path}: {unwritten.reason}") if unwritten else None
def texts(self) -> tuple[str, str, str, str] | Failure:
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
def plan_of(todo: str) -> Plan | Failure:
"""The plan a todo.md's text holds."""
found = items(todo)
if isinstance(found, Failure):
return found
details = item_details(todo)
if isinstance(details, Failure):
return details
marked = renames(todo)
if isinstance(marked, Failure):
return marked
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
"""path's text; where it is missing, a Failure saying missing."""
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; {missing}")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
+27 -20
View File
@@ -31,6 +31,13 @@ and readme.md, since the reviewers and the rules name those files.
Jira's backlog order, and `project-config plan` prints the setting as the config spells it. Such a
config must set `env-file`, and that file must hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN.
Such a config must also set two settings. `jira-score-formula` is the formula that scores an item.
`jira-score-bar` is the lowest score at which `todo-item add` files an item that isn't exempt, as a
bare number. They hold what a todo.md states as `Score` and `Bar`, which `rank_todo.py --help` describes:
jira-score-formula = "100 * V / (2**S + 8)"
jira-score-bar = 1
`jira-finish-transition` and `jira-finish-status` are optional settings, set together and only
beside such a plan, since each Jira workflow differs. `todo-item finish` moves an item's issue by
the workflow transition the first names. That transition must lead to the status the second names,
@@ -84,8 +91,12 @@ aims for. While the panel's overall score is under it, code health weighs 4 time
ranking, and a scoring run with a mean under it asks for a floor item. A legacy project, whose code
scores low, may lower it. Left out, it is 7.0.
`project-config tooling-on-host` and `project-config readability-floor` print their values; the full
listing shows each only where the config changes it from what it is when left out.
`parallel-chunks` is an optional setting, a whole number of 1 or more: the most chunks of the project
loop-claude runs at once, each in its own tmux window. Left out, it is 1.
`project-config tooling-on-host`, `project-config readability-floor` and `project-config parallel-chunks`
print their values; the full listing shows each only where the config changes it from what it is when
left out.
Four optional settings say how the project writes, for a project whose owners don't write as
~/.claude/CLAUDE.md does:
@@ -121,13 +132,15 @@ Exit 1, naming each fault on stderr, where no config names the checkout, or its
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
without a `plan` in Jira, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
without a `plan` in Jira, names a Jira `plan` and leaves out `jira-score-formula` or `jira-score-bar`, sets
one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything
but a number, sets `readability-floor` to anything but a number
from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or more, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
from project_config.settings import CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed
from failure import Failure
from git_cli.git_repo import git, Git
from project_config import templates
@@ -144,23 +157,17 @@ def main(argv: list[str]) -> int:
if isinstance(config, Failure):
print(config.reason, file=sys.stderr)
return 1
switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host}
if argv and argv[0] in switches:
print("true" if switches[argv[0]] else "false")
return 0
if argv == [READABILITY_FLOOR]:
print(config.readability_floor)
return 0
if argv and argv[0] in config.texts:
print(config.texts[argv[0]])
return 0
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
if argv and argv[0] not in paths:
# A one-value setting prints its value, its default where the config leaves it out; one without a default, as `notifier`, prints only where set.
scalars = {scalar.name: scalar.shown(value) for scalar in SCALARS if (value := getattr(config, scalar.field)) is not None}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
shown = paths | scalars
if argv and argv[0] not in shown:
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
return 1
defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
print(paths[argv[0]] if argv else "\n".join(listed))
# The listing leaves out each one-value setting at its default.
defaults = ProjectConfig(config.key, config.folder, config.top, {})
listed = [*(f"{name}: {path}" for name, path in paths.items()), *(f"{scalar.name}: {scalars[scalar.name]}" for scalar in SCALARS if getattr(config, scalar.field) != getattr(defaults, scalar.field))]
print(shown[argv[0]] if argv else "\n".join(listed))
return 0
+107 -16
View File
@@ -10,7 +10,10 @@ import tomllib
import typing
from failure import Failure
from plan.formula import parse_formula
from plan.todo_table import SHAPE
from project_config import templates
from plan.ranking import variables
PROJECTS = ".claude-projects"
CONFIG = "config.toml"
@@ -32,6 +35,8 @@ TOOLING_ON_HOST = "tooling-on-host"
READABILITY_FLOOR = "readability-floor"
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
DEFAULT_FLOOR = decimal.Decimal("7.0")
# The most chunks of the project loop-claude runs at once, each in its own tmux window; 1 where left out. Three readers seated as the README's audience picked the spelling 2-1 over concurrent-chunks.
PARALLEL_CHUNKS = "parallel-chunks"
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
LANGUAGE = "language"
COMMIT_TITLE = "commit-title"
@@ -43,7 +48,12 @@ TOUCH_PREDICTIONS = "touch-predictions"
JIRA_FINISH_TRANSITION = "jira-finish-transition"
JIRA_FINISH_STATUS = "jira-finish-status"
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
# Two settings, needed where `plan` names a Jira epic and allowed only there: what a todo.md states under ## Scoring.
JIRA_SCORE_FORMULA = "jira-score-formula"
JIRA_SCORE_BAR = "jira-score-bar"
JIRA_SCORE = (JIRA_SCORE_FORMULA, JIRA_SCORE_BAR)
# The settings allowed only where `plan` names a Jira epic.
JIRA_PLAN_ONLY = (*JIRA_FINISH, *JIRA_SCORE)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
@@ -78,6 +88,13 @@ class Finish:
status: str
@dataclasses.dataclass(frozen=True)
class JiraScoring:
"""How a plan in Jira scores an item: by formula, such as `100 * V / (2**S + 8)`, with bar the lowest score at which one is filed."""
formula: str
bar: float
@dataclasses.dataclass(frozen=True)
class Page:
"""A Confluence Cloud page: site is its site's address, such as https://acme.atlassian.net, page_id its number, and spelling the setting's value as the config writes it."""
@@ -103,6 +120,7 @@ class ProjectConfig:
wait_for_approval: bool = False
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
parallel_chunks: int = 1
language: str = "English"
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
@@ -115,6 +133,8 @@ class ProjectConfig:
notifier: Notifier | None = None
# The config's `jira-finish-transition` and `jira-finish-status`, or None where it sets neither.
jira_finish: Finish | None = None
# The config's `jira-score-formula` and `jira-score-bar`, which it sets where `plan` names an epic.
jira_scoring: JiraScoring | None = None
# The Confluence page of each record the config keeps on one, by the record's setting.
pages: dict[str, Page] = dataclasses.field(default_factory=dict)
@@ -174,38 +194,94 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None)
waits = values.get(WAIT_FOR_APPROVAL, False)
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values}
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*(f"`{scalar.name}` is {values[scalar.name]!r}, {read.reason}" for scalar, read in scalars.items() if isinstance(read, Unfit)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
# Each setting that reaches a service needs the file that holds its credentials.
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY if name in values and not epics["plan"]),
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
]
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
# faults names a floor the config misspells.
assert floor is not None
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, pages=pages)
# faults names a formula or bar a plan in Jira lacks or misspells.
assert scoring is not None or not epics["plan"]
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages)
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
@dataclasses.dataclass(frozen=True)
class Unfit:
"""Why a setting's value doesn't fit it, as the end of the sentence "`<setting>` is <value>, <reason>"."""
reason: str
@dataclasses.dataclass(frozen=True)
class Scalar:
"""An optional setting that holds one value, not a path: the ProjectConfig field it sets, whose default is its value where the config leaves it out, how its value is read, and how `project-config <name>` prints it."""
name: str
field: str
# The value, or Unfit; typed Any, since each Scalar reads into its own field's type.
read: typing.Callable[[object], typing.Any]
shown: typing.Callable[[typing.Any], str] = str
def switch(value: object) -> bool | Unfit:
return value if isinstance(value, bool) else Unfit("not true or false")
def floor_read(value: object) -> decimal.Decimal | Unfit:
floor = floor_of(value)
return Unfit(f"not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`") if floor is None else floor
def parallel_read(value: object) -> int | Unfit:
return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`")
def notifier_read(value: object) -> Notifier | Unfit:
return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}")
def text_read(fault: typing.Callable[[object], str | None]) -> typing.Callable[[object], str | Unfit]:
"""A text setting's reader, from the check that says why a value doesn't fit."""
def read(value: object) -> str | Unfit:
found = fault(value)
return Unfit(found) if found else str(value)
return read
def formula_fault(value: object) -> str | None:
"""Why value is no formula that may score an item, as todo.md's `Score` line states one; None where it is one."""
if not isinstance(value, str):
return "not a formula, such as \"100 * V / (2**S + 8)\""
parsed = parse_formula(value, variables(SHAPE))
return parsed.reason if isinstance(parsed, Failure) else None
def bar_of(value: object) -> float | None:
"""The bar value spells, an integer or a float; None where it spells none, as for a boolean or TOML's nan or inf, as floor_of says."""
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
return float(value)
def name_of(value: object) -> str | None:
@@ -240,6 +316,21 @@ def language_fault(value: object) -> str | None:
return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"'
# Each one-value setting, in the order `project-config` lists them.
SCALARS = (
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"),
Scalar(READABILITY_FLOOR, "readability_floor", floor_read),
Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read),
Scalar(NOTIFIER, "notifier", notifier_read),
Scalar(LANGUAGE, "language", text_read(language_fault)),
Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)),
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
)
OPTIONAL = tuple(sorted((ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS))))
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
"""Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names."""
return any(path.resolve().is_relative_to(place.resolve()) for place in places)
+10
View File
@@ -71,6 +71,16 @@ def fits(template: str, title: str) -> bool:
return pattern(template).fullmatch(title) is not None
def misfits(template: str, branch_template: str, branch: str | None, title: str) -> bool:
"""Whether title breaks template on branch, the checkout's branch or None where HEAD is detached. On a branch that fits branch_template, a plan item's, a title must fit template. Any other branch, such as a release review's, has no ID for {id}, so every title fits there (CLAUDE.md → "Git, commits, and PRs")."""
return branch is not None and branch_fits(branch_template, branch) and not fits(template, title.strip())
def title_of(template: str, branch_template: str, branch: str, id_: str, summary: str) -> str:
"""The title template makes of summary on branch, with id_ for {id}; summary alone on a branch that doesn't fit branch_template, as misfits allows."""
return template.replace(ID, id_).replace(SUMMARY, summary) if branch_fits(branch_template, branch) else summary
def summary_of(template: str, title: str) -> str:
"""title's summary. A title that doesn't fit template is its own summary, so a commit from before the config named the template reads as it always did."""
found = pattern(template).fullmatch(title)
+73 -3
View File
@@ -9,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
from project_config.settings import env_files, Epic, Finish, held, JiraScoring, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import located, title_templates
@@ -31,7 +31,8 @@ standards = "~/.claude/skills/larv-review/standards"
"""
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n'
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + JIRA_SCORING
DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions"
@@ -320,6 +321,40 @@ class LoadTest(ConfigCase):
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure())
def test_a_jira_plan_holds_the_formula_and_bar_it_scores_by(self) -> None:
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
named = load(self.checkout, self.checkout, self.home)
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.jira_scoring, JiraScoring("100 * V / (2**S + 8)", 0.5))
def test_a_plan_in_a_file_holds_no_formula_or_bar_of_the_configs(self) -> None:
self.write("acme", CLIENT)
named = load(self.checkout, self.checkout, self.home)
assert isinstance(named, ProjectConfig), named
self.assertIsNone(named.jira_scoring)
def test_a_jira_plan_without_a_formula_or_a_bar_fails_naming_each(self) -> None:
self.write("acme", JIRA_CLIENT.replace(JIRA_SCORING, ""))
self.assertIn("`plan` names a Jira epic, so `jira-score-formula` must be set, as `project-config --help` shows; `plan` names a Jira epic, so `jira-score-bar` must be set", self.failure())
def test_a_scoring_setting_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
config = self.write("acme", JIRA_CLIENT) / "config.toml"
for formula, bar in (('" "', "true"), ("3", '"1"'), ('"V"', "nan")):
with self.subTest(formula=formula, bar=bar):
config.write_text(JIRA_CLIENT.replace(JIRA_SCORING, f"jira-score-formula = {formula}\njira-score-bar = {bar}\n"))
reason = self.failure()
self.assertIn("jira-score-bar` is", reason)
self.assertEqual("jira-score-formula` is" in reason, formula != '"V"')
config.write_text(CLIENT + JIRA_SCORING)
self.assertIn("`jira-score-formula` is set, so `plan` must name a Jira epic; `jira-score-bar` is set, so `plan` must name a Jira epic", self.failure())
def test_a_formula_that_doesnt_parse_fails_naming_the_setting_and_why(self) -> None:
config = self.write("acme", JIRA_CLIENT) / "config.toml"
for formula, why in (("V +", "the formula 'V +' does not parse"), ("X", "the formula 'X' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses")):
with self.subTest(formula=formula):
config.write_text(JIRA_CLIENT.replace('"100 * V / (2**S + 8)"', f'"{formula}"'))
self.assertIn(f"`jira-score-formula` is '{formula}': {why}", self.failure())
def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None:
self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n')
self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure())
@@ -427,6 +462,28 @@ class LoadTest(ConfigCase):
self.assertIn("`readability-floor` is ", found.reason)
self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason)
def test_parallel_chunks_is_an_optional_whole_number_from_1_that_is_1_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertEqual(left_out.parallel_chunks, 1)
for spelled in (1, 3, 12):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.parallel_chunks, spelled)
def test_parallel_chunks_that_is_no_whole_number_from_1_fails_naming_it(self) -> None:
folder = self.write("acme", CLIENT)
for spelled in ('"2"', "0", "-1", "2.0", "true", "inf"):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn("`parallel-chunks` is ", found.reason)
self.assertIn(", not a whole number of 1 or more, such as `parallel-chunks = 2`", found.reason)
def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -462,7 +519,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -592,6 +649,11 @@ class ToolTest(ConfigCase):
self.assertEqual(self.run_tool("jira-finish-status").stdout, "Done\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["jira-finish-transition: Mark as done", "jira-finish-status: Done"])
def test_prints_the_formula_and_bar_a_jira_plan_scores_by(self) -> None:
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
self.assertEqual((self.run_tool("jira-score-formula").stdout, self.run_tool("jira-score-bar").stdout), ("100 * V / (2**S + 8)\n", "0.5\n"))
self.assertIn("jira-score-formula: 100 * V / (2**S + 8)\njira-score-bar: 0.5\n", self.run_tool().stdout)
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
folder = self.write("acme", CLIENT)
left_out = self.run_tool("wait-for-approval")
@@ -612,6 +674,14 @@ class ToolTest(ConfigCase):
self.assertEqual((self.run_tool("tooling-on-host").stdout, self.run_tool("readability-floor").stdout), ("true\n", "5\n"))
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["tooling-on-host: true", "readability-floor: 5"])
def test_prints_parallel_chunks_and_lists_it_only_where_the_config_changes_it(self) -> None:
folder = self.write("acme", CLIENT)
self.assertEqual(self.run_tool("parallel-chunks").stdout, "1\n")
self.assertNotIn("parallel-chunks", self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + "parallel-chunks = 3\n")
self.assertEqual(self.run_tool("parallel-chunks").stdout, "3\n")
self.assertIn("parallel-chunks: 3", self.run_tool().stdout.splitlines())
def test_prints_the_language_and_each_template_and_lists_them_only_where_the_config_sets_them(self) -> None:
folder = self.write("acme", CLIENT)
defaults = {"language": "English", "commit-title": "{summary}", "pull-request-title": "{summary}", "branch": "item-{id}"}
+38 -9
View File
@@ -10,8 +10,10 @@ save refuses them: edit the epic in Jira.
open prints the path of a file holding the record's text, and nothing else. Read and edit that
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
path is a copy under ~/.local/state/project-record/<key>/, written afresh with the record as it
stands, so open it again before each edit. A record that doesn't exist yet has no file at the path:
path is a copy under ~/.local/state/project-record/<key>/<worktree>/, a folder named for the
worktree that ran open, so two worktrees of one project don't share a copy. The copy is written
afresh with the record as it stands, so open it again before each edit. open also removes the
folders of worktrees git no longer lists. A record that doesn't exist yet has no file at the path:
create it there.
save stores the file's text in the record, and prints one line saying so. Where the record is kept
@@ -19,22 +21,25 @@ as a file, there is nothing left to store, and save says so. Run it after every
steps work wherever a project keeps the record.
For a record kept on a Confluence page, save refuses where someone saved the page after open read
it, and the human decides what follows. The copy keeps the unsaved edit until open runs again and
writes the copy afresh.
it or after save last wrote it, and the human decides what follows. The copy keeps the unsaved edit
until open runs again and writes the copy afresh.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
import hashlib
import pathlib
import shutil
import sys
from failure import Failure
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
from git_cli.git_repo import git, Git
from project_config.main import located
from project_config.settings import ProjectConfig
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
COMMANDS = ("open", "save")
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree.
COPIES = ".local/state/project-record"
# The goals file opens like a record, though it is a setting of its own.
GOALS = "goals-and-audience"
@@ -49,7 +54,7 @@ def main(argv: list[str]) -> int:
return 2
home = pathlib.Path.home()
config = located(None, home)
done = config if isinstance(config, Failure) else act(argv[0], *opened(config, argv[1], home))
done = config if isinstance(config, Failure) else performed(config, argv[0], argv[1], home)
if isinstance(done, Failure):
print(f"project-record: {done.reason}", file=sys.stderr)
return 1
@@ -57,10 +62,34 @@ def main(argv: list[str]) -> int:
return 0
def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path, run: Git = git) -> str | Failure:
"""What command, one of COMMANDS, prints for the record called name. An open also prunes the copies of removed worktrees."""
if command == "open":
pruned(config, home, run)
return act(command, *opened(config, name, home))
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
copy = home / COPIES / config.key / f"{name}.md"
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
"""The store of the record called name, and the copy it gets where it isn't kept as a file."""
copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md"
return (goals_store(config) if name == GOALS else store(config, name)), copy
def worktree_folder(top: pathlib.Path) -> str:
"""The name of the folder that holds the copies of the worktree at top: the worktree's own name, for a reader, and a hash of its path, since two worktrees in different folders may share a name."""
return f"{top.name}-{hashlib.sha256(str(top).encode()).hexdigest()[:8]}"
def pruned(config: ProjectConfig, home: pathlib.Path, run: Git = git) -> None:
"""Remove the copies of the worktrees git no longer lists, so the folders don't pile up one per chunk. Best effort: a folder that stays only takes disk, and where git can't list the worktrees nothing is removed."""
listed = run("worktree", "list", "--porcelain")
folders = home / COPIES / config.key
if isinstance(listed, Failure) or not folders.is_dir():
return
worktrees = [config.top, *(pathlib.Path(line.removeprefix("worktree ")) for line in listed.splitlines() if line.startswith("worktree "))]
kept = {worktree_folder(worktree) for worktree in worktrees}
for stale in (folder for folder in folders.iterdir() if folder.is_dir() and folder.name not in kept):
shutil.rmtree(stale, ignore_errors=True)
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
+81 -9
View File
@@ -17,19 +17,91 @@ from project_config.settings import Page, ProjectConfig
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
COPIES = pathlib.Path("/home/me/.local/state/project-record/acme")
def worktree_config(top: str, **kept: Page) -> ProjectConfig:
return ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept)
class Opened(unittest.TestCase):
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
def test_a_record_on_a_confluence_page_gets_a_copy_in_a_folder_of_its_worktree(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
record, copy = main.opened(config, "decisions", pathlib.Path("/home/me"))
self.assertEqual(copy, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.md"))
assert isinstance(record, ConfluencePage), record
self.assertEqual(record.kept, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.version"))
record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me"))
self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md"))
self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$")
self.assertIsInstance(record, ConfluencePage)
def test_the_goals_file_opens_through_the_goals_store(self):
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {"goals-and-audience": pathlib.Path("/code/acme/README.md")})
record, copy = main.opened(config, "goals-and-audience", pathlib.Path("/home/me"))
self.assertEqual((record.label, copy), ("/code/acme/README.md", pathlib.Path("/home/me/.local/state/project-record/acme/goals-and-audience.md")))
record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me"))
self.assertEqual((record.label, copy.parent.parent, copy.name), ("/code/acme/README.md", COPIES, "goals-and-audience.md"))
def test_two_worktrees_of_one_project_get_copies_that_differ(self):
home = pathlib.Path("/home/me")
main_checkout = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
other = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
self.assertNotEqual(main_checkout, other)
def test_one_worktree_always_gets_the_same_copy(self):
home = pathlib.Path("/home/me")
first = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
self.assertEqual(first, main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1])
def test_two_worktrees_named_alike_in_different_folders_get_copies_that_differ(self):
home = pathlib.Path("/home/me")
first = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
second = main.opened(worktree_config("/other/acme-item-5"), "goals-and-audience", home)[1]
self.assertNotEqual(first, second)
class Pruned(unittest.TestCase):
def setUp(self) -> None:
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.config = worktree_config("/code/acme-item-5")
self.folders = self.home / ".local/state/project-record/acme"
for top in ("/code/acme", "/code/acme-item-5", "/code/acme-item-6"):
copy = main.opened(worktree_config(top), "goals-and-audience", self.home)[1]
copy.parent.mkdir(parents=True)
copy.write_text("edit")
def kept(self) -> set[str]:
return {folder.name for folder in self.folders.iterdir()}
def listed(self, *tops: str):
return lambda *args, **kwargs: "" if args != ("worktree", "list", "--porcelain") else "".join(f"worktree {top}\nHEAD abc\nbranch refs/heads/x\n\n" for top in tops)
def test_removes_the_copies_of_worktrees_git_no_longer_lists_and_keeps_the_others(self):
main.pruned(self.config, self.home, self.listed("/code/acme", "/code/acme-item-5"))
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
def test_always_keeps_the_copy_of_the_worktree_that_asked(self):
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertIn(main.worktree_folder(pathlib.Path("/code/acme-item-5")), self.kept())
def test_removes_nothing_where_git_cannot_list_the_worktrees(self):
main.pruned(self.config, self.home, lambda *args, **kwargs: Failure("not a repository"))
self.assertEqual(len(self.kept()), 3)
def test_leaves_files_beside_the_folders_alone(self):
(self.folders / "decisions.md").write_text("from before the folders")
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertTrue((self.folders / "decisions.md").exists())
def test_a_copy_that_cannot_be_removed_does_not_fail_the_open(self):
self.folders.chmod(0o500)
self.addCleanup(self.folders.chmod, 0o700)
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertEqual(len(self.kept()), 3)
def test_an_open_prunes_and_a_save_does_not(self):
run = self.listed("/code/acme", "/code/acme-item-5")
self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.")
self.assertEqual(len(self.kept()), 3)
self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md")
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
def test_does_nothing_where_the_project_has_no_copies(self):
main.pruned(worktree_config("/code/acme"), self.home / "elsewhere", self.listed("/code/acme"))
class Act(unittest.TestCase):
+5 -4
View File
@@ -93,8 +93,8 @@ import pathlib
import sys
from failure import Failure
from plan_store.stores import file_plan
from project_config.main import located
from release_plan import plan_file
def main(argv: list[str]) -> int:
@@ -116,15 +116,16 @@ def main(argv: list[str]) -> int:
# The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them.
if todo.resolve() != config.plan_file.resolve():
return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is"))
plan = file_plan(config, todo)
if check:
failures = plan_file.check_failures(todo, config)
failures = plan.check()
for line in failures:
print(line, file=sys.stderr)
return 1 if failures else 0
ranked = plan_file.rank_file(todo, config)
ranked = plan.rank()
if isinstance(ranked, Failure):
return fail(ranked)
for line in plan_file.report_lines(todo, ranked):
for line in plan.reported(ranked):
print(line, file=sys.stderr)
return 1 if ranked.under_bar else 0
+6 -7
View File
@@ -73,11 +73,11 @@ def main(argv: list[str]) -> int:
def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure:
text = record.read()
if isinstance(text, Failure):
return text
held = record.held()
if isinstance(held, Failure):
return held
# An empty record starts with its title.
text = text or "# Reading cost\n"
text = held.text or "# Reading cost\n"
figures = new_figures(text, archive, checkout, home)
if isinstance(figures, Failure):
return figures
@@ -86,9 +86,8 @@ def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home:
readings = readings_of(text)
if isinstance(readings, Failure):
return readings
if marks and (unwritten := record.write(text)):
return unwritten
return Updated(len(figures), readings)
written = record.write(text, held.version) if marks else None
return written if isinstance(written, Failure) else Updated(len(figures), readings)
def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure:
+8 -1
View File
@@ -19,6 +19,7 @@ from reading_cost.measure import Checkout, Reading
from failure import Failure
from reading_cost import figures, main, measure
from transcript_archive.read import finished_chunks, FinishedChunk
from record_store.held import Held
from test_env import isolated_env
from record_store.fakes import MemoryStore
from transcript_archive import outcomes
@@ -235,9 +236,15 @@ class Located(unittest.TestCase):
class Update(unittest.TestCase):
def test_writes_over_the_version_it_read(self):
record = MemoryStore("# Reading cost\n", version=2)
archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.assertNotIsInstance(main.update(record, archive, Checkout("/c/p", "/c/p", frozenset(), BRANCH), "/h", "2026-11-14T00:00:00Z"), Failure)
self.assertEqual(record.overs, ["2"])
def test_fails_where_the_record_refuses_the_write(self):
class Unwritable(MemoryStore):
def write(self, text: str) -> Failure | None:
def write(self, text: str, over: str | None) -> Held | Failure:
return Failure("the wiki is down")
archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
+31 -59
View File
@@ -1,54 +1,42 @@
"""A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim.
A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
A write never overwrites a teammate's edit: it sends the version after the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
import dataclasses
import json
import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from plan_store.jira_epic import basic_auth, Http, TIMEOUT, ToAdf, ToMarkdown
from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client import json_request
from record_store.held import Held
from project_config.settings import Page
from text_files.file_writes import replace_file
# What Confluence answers to a write whose version isn't the one after the version it holds.
CONFLICT = 409
SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents"
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Seen:
"""The page's version number and title as the store last read or wrote them. A write needs both."""
"""The page's version number and title as a read found them or a write left them. A write needs both, so a Held's version holds both, as JSON."""
version: int
title: str
@property
def token(self) -> str:
return json.dumps(dataclasses.asdict(self))
@dataclasses.dataclass
class ConfluencePage:
"""The text of page as markdown, read and written with the credentials env_file holds.
kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory."""
"""The text of page as markdown, read and written with the credentials env_file holds."""
page: Page
env_file: pathlib.Path
kept: pathlib.Path | None = None
http: Http = http_json
http: Http = confluence_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
seen: Seen | None = None
@property
def label(self) -> str:
@@ -64,18 +52,19 @@ class ConfluencePage:
def read(self) -> str | Failure:
"""The page's text as markdown; empty where the page is."""
held = self.held()
return held if isinstance(held, Failure) else held.text
def held(self) -> Held | Failure:
"""The page's text as markdown, with its version and title as the version a write over it names."""
answer = self.fetched("?body-format=atlas_doc_format")
if isinstance(answer, Failure):
return answer
seen, held = answer
if not isinstance(held, str):
seen, body = answer
if not isinstance(body, str):
return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format")
text = self.converted(held)
if isinstance(text, Failure):
return text
# Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw.
unkept = self.keep(seen)
return unkept or text
text = self.converted(body)
return text if isinstance(text, Failure) else Held(text, seen.token)
def converted(self, held: str) -> str | Failure:
"""The markdown of the body held, the JSON of an ADF document; empty where held is."""
@@ -92,14 +81,9 @@ class ConfluencePage:
return Failure(f"cannot convert {self.label} to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
"""Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands."""
seen = self.seen or self.recalled()
if seen is None:
fetched = self.fetched("")
if isinstance(fetched, Failure):
return fetched
seen = fetched[0]
def write(self, text: str, over: str | None) -> Held | Failure:
"""Replaces the page's text with text, as the version after over, the one held() gave. Where over is None, it replaces the page as it stands."""
seen = self.seen_of(over)
if isinstance(seen, Failure):
return seen
document = self.to_adf(text)
@@ -114,7 +98,7 @@ class ConfluencePage:
return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})")
if isinstance(answer, Failure):
return Failure(f"cannot write {self.label}: {answer.reason}")
return self.keep(Seen(seen.version + 1, seen.title))
return Held(text, Seen(seen.version + 1, seen.title).token)
def fetched(self, query: str) -> tuple[Seen, object] | Failure:
"""The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't."""
@@ -133,25 +117,13 @@ class ConfluencePage:
adf = body.get("atlas_doc_format") if isinstance(body, dict) else None
return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None
def keep(self, seen: Seen) -> Failure | None:
self.seen = seen
if self.kept is None:
return None
def seen_of(self, over: str | None) -> Seen | Failure:
"""The version and title a write sends: those over holds, else the page's as it stands."""
if over is None:
fetched = self.fetched("")
return fetched if isinstance(fetched, Failure) else fetched[0]
try:
self.kept.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.kept}: {failure.strerror}")
unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode())
return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None
def recalled(self) -> Seen | Failure | None:
"""The version and title the file kept holds; None where kept is None or names no file."""
if self.kept is None:
return None
try:
held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8"))
held: typing.Any = json.loads(over)
return Seen(int(held["version"]), str(held["title"]))
except FileNotFoundError:
return None
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}")
except (ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}")
+14 -3
View File
@@ -1,6 +1,7 @@
"""What every record backend must hold, as tests. A backend's test case inherits RecordStoreContract and unittest.TestCase, and builds its store in new_store."""
import typing
from record_store.held import Held
from record_store.stores import RecordStore
@@ -8,6 +9,7 @@ class RecordStoreContract:
"""Runs against the store new_store returns: one that holds no record yet."""
assertEqual: typing.Callable[..., None]
assertIsNone: typing.Callable[..., None]
assertIsInstance: typing.Callable[..., None]
assertTrue: typing.Callable[..., None]
def new_store(self) -> RecordStore:
@@ -19,14 +21,23 @@ class RecordStoreContract:
def test_reads_back_what_it_wrote_to_the_character(self) -> None:
store = self.new_store()
text = "# Decisions\n\n- Å, 🔴 and a | pipe\n\n\n"
self.assertIsNone(store.write(text))
self.assertEqual(store.write(text, None), store.held())
self.assertEqual(store.read(), text)
def test_a_write_replaces_the_whole_record(self) -> None:
store = self.new_store()
store.write("first\nsecond\n")
self.assertIsNone(store.write("third\n"))
first = store.write("first\nsecond\n", None)
assert isinstance(first, Held), first
# A write over the version the last one left replaces the record, as a later save does.
self.assertIsInstance(store.write("third\n", first.version), Held)
self.assertEqual(store.read(), "third\n")
def test_holds_its_text_with_the_version_a_write_over_it_names(self) -> None:
store = self.new_store()
store.write("text\n", None)
held = store.held()
assert isinstance(held, Held), held
self.assertEqual(held.text, "text\n")
def test_names_itself_for_a_message(self) -> None:
self.assertTrue(self.new_store().label.strip())
+13 -4
View File
@@ -2,21 +2,30 @@
import dataclasses
from failure import Failure
from record_store.held import Held
@dataclasses.dataclass
class MemoryStore:
"""A record held in memory, as a backend outside git holds one. Set fails to make every read and write fail with that reason."""
"""A record held in memory, as a backend outside git holds one: versioned as a wiki page is, refusing a write over a version it no longer holds. Set fails to make every read and write fail with that reason. overs holds the version each write named, so a test can check that a caller wrote over the version it read."""
text: str = ""
label: str = "the record in memory"
tracked: str | None = None
fails: str | None = None
version: int = 0
overs: list[str | None] = dataclasses.field(default_factory=list)
def read(self) -> str | Failure:
return Failure(self.fails) if self.fails else self.text
def write(self, text: str) -> Failure | None:
def held(self) -> Held | Failure:
return Failure(self.fails) if self.fails else Held(self.text, str(self.version))
def write(self, text: str, over: str | None) -> Held | Failure:
self.overs.append(over)
if self.fails:
return Failure(self.fails)
self.text = text
return None
if over is not None and over != str(self.version):
return Failure(f"someone saved {self.label} since version {over}")
self.text, self.version = text, self.version + 1
return Held(text, str(self.version))
+9
View File
@@ -0,0 +1,9 @@
"""A record as a read found it or a write left it, which every record backend gives."""
import dataclasses
@dataclasses.dataclass(frozen=True)
class Held:
"""A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's."""
text: str
version: str | None = None

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