Compare commits

..

53 Commits

Author SHA1 Message Date
lilleman 411819c38d Cut release 0.16.0
CI / tests (pull_request) Successful in 4m13s
2026-11-27 15:00:18 +01:00
lilleman 0613be57c0 Record the comprehension check: paired ruling better at 4a35c74f against 606cf25e
CI / tests (pull_request) Successful in 4m25s
2026-11-27 14:55:30 +01:00
lilleman a00439f37a Point a comment at the moved digest module 2026-11-27 14:55:30 +01:00
lilleman 4a35c74f08 Merge remote-tracking branch 'origin/main' into release-review-0.16.0
CI / tests (pull_request) Has been cancelled
2026-11-27 14:48:13 +01:00
lilleman 66aa74097f Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); approved with one nit: a patch cut's ci.sh failure says to fix the reason and rerun, which fits a ci.sh that never started
CI / tests (pull_request) Has been cancelled
2026-11-27 14:47:59 +01:00
lilleman 37a87eb15e Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved 2026-11-27 14:47:59 +01:00
lilleman 539f9799cb Answer principles round 4: 0 🔴, 0 🟡 (0 misread); approved with one nit: the review refusal's test checks the facts the message carries, not its whole sentence
CI / tests (pull_request) Successful in 4m28s
2026-11-27 14:43:17 +01:00
Lilleman b6ebfc2ef9 File the push that skips its review request while the forge lags the pushed head
CI / tests (pull_request) Successful in 4m51s
2026-11-27 14:28:43 +01:00
lilleman 81d6e89e6c Answer prose round 1: 0 🔴, 6 🟡 (0 misread); every fix is in the stability round's commit
CI / tests (pull_request) Successful in 4m13s
2026-11-27 14:14:28 +01:00
lilleman 1a18131efc Answer product-owner round 1: 1 🔴, 0 🟡 (0 misread); the UTC trace, the changelog's two cut flags and the review refusal's title are in the stability round's commit 2026-11-27 14:14:28 +01:00
lilleman 74066a3134 Answer stability round 1: 1 🔴, 1 🟡 (0 misread); stamp deploy-release's trace in UTC, end a stopped run's trace, drop redundant assertions, and the product-owner and prose fixes 2026-11-27 14:14:28 +01:00
lilleman 3eb57d44c6 Merge remote-tracking branch 'origin/main' into release-review-0.16.0
CI / tests (pull_request) Successful in 4m55s
2026-11-27 13:32:10 +01:00
lilleman 72c5903cb0 Kill the mutants that survived on the release's changed lines, and say 1 minute, not 1 minutes
CI / tests (pull_request) Successful in 4m10s
2026-11-27 13:08:58 +01:00
Lilleman 2bf574fba4 File two review-setup gaps: guards checked against every state, and mutation tools run in the module's folder
CI / tests (pull_request) Successful in 4m56s
2026-11-27 12:46:30 +01:00
lilleman 3b4ff44e7a Answer principles round 3: 0 🔴, 0 🟡 (0 misread); approved 2026-11-27 12:10:32 +01:00
lilleman be96c36591 Answer principles round 2: 0 🔴, 1 🟡 (0 misread); remove ci.sh's container when a patch cut stops it, show task-bench's count defaults where they apply, and take ci.sh's bound from the forge's wait
CI / tests (pull_request) Successful in 4m47s
2026-11-27 12:09:14 +01:00
Lilleman fdb57a02a5 Renumber the claimed-output item to 549 after a concurrent item 548
CI / tests (pull_request) Successful in 5m29s
2026-11-27 12:01:23 +01:00
lilleman 4fc4763710 Answer principles round 1: 0 🔴, 1 🟡 (0 misread); bound and stream a patch cut's ci.sh, keep a trace of each deploy-release run, fail on file errors and a missing Unreleased heading, read the plan once per cut, one home for the review title, inject task-bench's container names, one spelling of its task kind
CI / tests (pull_request) Has been cancelled
2026-11-27 11:57:54 +01:00
Lilleman 29ddb01947 Merge remote-tracking branch 'origin/main' into claimed-output-fresh-state
CI / tests (pull_request) Has been cancelled
2026-11-27 11:54:08 +01:00
Lilleman 5079e75294 Run claimed output from a fresh checkout's state, and check claims about what a command writes
CI / tests (pull_request) Has been cancelled
2026-11-27 11:51:45 +01:00
Lilleman d90b62bfe6 File item 548: honour merge = human where a chunk records the default branch as its base
CI / tests (pull_request) Successful in 5m9s
2026-11-27 11:47:01 +01:00
lilleman f8ad35c1f9 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no vulnerabilities found 2026-11-27 11:38:33 +01:00
lilleman 6aa730ea5b Answer architecture round 3: 0 🔴, 0 🟡 (0 misread); approved, nothing to change 2026-11-27 11:37:20 +01:00
lilleman 7c7d43023b Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); move task_bench's shared Side and Rust test-module scanner to the package top, rename figures.py to run_figures.py, check for cycles between a package's parts, and move REVIEW_LABEL into the backend protocol
CI / tests (pull_request) Successful in 5m13s
2026-11-27 11:36:37 +01:00
Lilleman 5b51d7e081 File item 547: tell a failure's cause from a status code, never from a tool's message text
CI / tests (pull_request) Successful in 4m21s
2026-11-27 11:34:10 +01:00
lilleman b563a597f1 Answer architecture round 1: 0 🔴, 6 🟡 (0 misread); count a release review only where it names the next release, split task_bench into bugs, features and figures, group README's packages
CI / tests (pull_request) Successful in 4m55s
2026-11-27 11:23:08 +01:00
lilleman 82fdbee1a4 File an item: reviewers check an outside service's setup steps against its current documentation
CI / tests (pull_request) Successful in 4m59s
2026-11-27 09:48:39 +01:00
lilleman 3a48a91684 File item 545: write each missing Touches list before the next chunk
CI / tests (pull_request) Successful in 4m30s
2026-11-27 01:08:26 +01:00
lilleman d1b01c76c8 Record the reading cost before the release review of 0.16.0
CI / tests (pull_request) Successful in 7m45s
2026-11-27 00:51:01 +01:00
lilleman 2c5aab4578 Release review of 0.16.0
CI / tests (pull_request) Has been cancelled
2026-11-27 00:50:38 +01:00
lilleman 11e7f90b01 Finish item 525 in the plan
CI / tests (pull_request) Successful in 9m23s
2026-11-26 16:11:14 +01:00
lilleman 606cf25ed2 Record the comprehension check: two scoring runs at 68611733, floor item 300 refreshed
CI / tests (pull_request) Has been cancelled
2026-11-26 16:10:57 +01:00
lilleman 68611733fe Record the reading cost before item 525
CI / tests (pull_request) Successful in 4m51s
2026-11-26 13:17:12 +01:00
lilleman 79ae24abf4 Finish item 528 in the plan
CI / tests (pull_request) Successful in 6m37s
2026-11-26 12:38:48 +01:00
lilleman c259d5fbb2 Finish item 527 in the plan 2026-11-26 12:38:47 +01:00
lilleman 87f168c4c9 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); drop a report the tree held before the run, move a comment back to its function
CI / tests (pull_request) Has been cancelled
2026-11-26 12:35:53 +01:00
lilleman 794adafb91 Leave the scratch folder out of its own copy by name
CI / tests (pull_request) Successful in 6m14s
2026-11-26 12:08:55 +01:00
lilleman 8b1c9ff184 Fail the scratch copy's test on a socket, not a patched function
CI / tests (pull_request) Successful in 8m49s
2026-11-26 11:45:36 +01:00
lilleman 014d085f26 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); reworded in the two answers before this one
CI / tests (pull_request) Has been cancelled
2026-11-26 11:42:20 +01:00
lilleman ea4d2408b2 Answer product-owner round 1: 0 🔴, 3 🟡 (0 misread); say how the tools get their dependencies and which names count as tests, file item 544 2026-11-26 11:42:20 +01:00
lilleman 874e417e27 Answer stability round 1: 0 🔴, 5 🟡 (0 misread); run both tools in a scratch copy, read Infection's two sources, end PHPUnit's list, spell glob characters 2026-11-26 11:42:20 +01:00
lilleman 76de4fa497 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-26 11:42:20 +01:00
lilleman 47084dc3df Test the planters' edges that mutants survived
CI / tests (pull_request) Successful in 6m5s
2026-11-26 11:03:39 +01:00
lilleman 632023ed21 Sort the two planters' imports
CI / tests (pull_request) Successful in 5m35s
2026-11-26 10:42:42 +01:00
lilleman ffe2048b73 Plant task-bench's bugs in TypeScript and PHP, from Stryker's and Infection's killed mutants
CI / tests (pull_request) Has been cancelled
2026-11-26 10:39:36 +01:00
lilleman 48270c0439 Record the reading cost 2026-11-26 10:39:36 +01:00
lilleman 9eea738d57 Finish item 543 in the plan
CI / tests (pull_request) Successful in 5m30s
2026-11-26 10:23:12 +01:00
lilleman d97709eccd Answer prose round 1: 0 🔴, 2 🟡 (0 misread); reword both rules, define fixup
CI / tests (pull_request) Has been cancelled
2026-11-26 10:22:58 +01:00
lilleman a929e2ccc0 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); keep a blanked row 2026-11-26 10:22:54 +01:00
lilleman 4b51675596 Add two testing rules: assert the exception exists, filter after fixups
CI / tests (pull_request) Has been cancelled
2026-11-26 10:20:46 +01:00
lilleman 1ed9491d9a Finish item 524 in the plan
CI / tests (pull_request) Successful in 5m2s
2026-11-26 10:14:36 +01:00
lilleman 77d0b91595 Merge remote-tracking branch 'origin/main' into item-524
CI / tests (pull_request) Successful in 5m14s
2026-11-26 08:54:18 +01:00
lilleman 166778ef0b Record the reading cost of the last three chunks 2026-11-26 03:39:32 +01:00
71 changed files with 2500 additions and 501 deletions
+3 -2
View File
@@ -157,8 +157,9 @@
!bin/subagent_rung/*.py
!bin/task-bench
!bin/task_bench/
!bin/task_bench/*.py
!bin/task_bench/gather-prompt.md
!bin/task_bench/**/
!bin/task_bench/**/*.py
!bin/task_bench/figures/gather-prompt.md
!bin/test_*.py
!bin/text_files/
!bin/text_files/*.py
+6 -2
View File
@@ -1,11 +1,15 @@
# Changelog
## Unreleased
## 0.16.0
- `task-bench` plants bugs in PHP, from the mutants Infection logs as killed, and reads the task it gives from the message PHPUnit prints.
- `task-bench` plants bugs in TypeScript and JavaScript, from the mutants Stryker reports as killed, and reads the task it gives from the error `node --test` prints.
- Testing principles now say that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete.
- task-bench leaves out of a fix a change Haiku makes to a Rust test module that stands in the file of the code it tests, and passes over a Rust mutant whose test modules it cannot tell apart.
- loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human.
- larv-review's prose pass takes a second round after a fix that rewrites a claim a command or a source file can check, such as generated output, a number or a licence term.
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for a release later than the last cut.
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for the release its title names: `Release review of 0.16.0` reviews 0.16.0 and no other.
- `deploy-release --cut` and `--cut-patch` keep each step, with its time in UTC, in a file under `~/.local/state/deploy-release/`, and `--cut-patch` stops `ci.sh` after 30 minutes, naming the log that holds its output.
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself.
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
+35 -18
View File
@@ -196,7 +196,7 @@ Once the next release holds no item in `todo.md` and its release review has land
bin/deploy-release --cut
```
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time in UTC, in a file of its own under `~/.local/state/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first:
@@ -236,22 +236,19 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, Python and Rust files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, PHP, Python, Rust, TypeScript and JavaScript files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
### Packages under `bin/`
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks.
`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. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks. Within each group below, the entries are in alphabetical order.
#### Driving chunks
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either.
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path.
- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `deploy_release` imports `release_plan`'s `release_standing`.
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic:
- `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `epic_run.py` holds what stays the same through one run of do-epic, such as its config, its Jira store and its paths, and starts the chunks that may start now.
- `planning.py` settles, before the chunks start, where each open issue is worked, its scores and the order the issues start in, through `split.py`, `repo_pick.py`, `issue_scores.py` and `ranking.py`.
@@ -267,29 +264,49 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`.
- `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic.
- `e2e/` holds `do-epic-e2e`.
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
#### The plan, the records and releases
- `deploy_release` imports `release_plan`'s `release_standing`.
- `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`), an item's `Touches:` prediction and where two overlap (`touches.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; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
#### Git, forges and Atlassian
- `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. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`.
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
- `git_cli/` runs git for every tool (`git_repo.py`), reads the git calls in a shell command (`git_command.py`), and keeps an epic's working branch level with the default branch (`epic_branch.py`).
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
#### Measuring and replaying
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes`, `routing_figures` and `task_bench`. It imports `reading_cost`'s record path.
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, Python and Rust files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `task_bench/` holds `task-bench`, which has Haiku fix, build or add a task in containers: a bug planted in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files (`bugs/`), or one of the project's bench features, its data sources or the features its history shipped (`features/`). `figures/` measures the runs and holds `task-bench gather`.
#### The shell, the machine and text
- `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`.
- `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.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
#### Tests and tools of one file
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `repo_checks/` tests the repo itself.
- `test_env.py` serves the tests.
## Test
+8 -5
View File
@@ -28,11 +28,14 @@ and prints that the release reviews and the cuts are the human's to call. It pri
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 the next release holds no item, it says so, and names the release where todo.md named it
since the cut. Where no change is unreleased (the ## Unreleased entries, or else the commits
since the cut), that release is to be planned first. Otherwise its release review is due, and
once the review has landed the release is finished and ready to cut. The review has landed
once a commit titled `Release review of <release>`, where <release> is exactly the next
release, is on the default branch after the newest v* tag, or anywhere on a branch with no
tag. The one exception: where todo.md named no next release since the cut, such a commit
counts whichever release it names.
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
+4 -2
View File
@@ -705,7 +705,9 @@ class Plans(unittest.TestCase):
def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self):
said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main", BRANCH).why
self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said)
self.assertIn("has landed yet.", said)
self.assertIn("no commit titled `Release review of 0.2.0` has landed yet.", said)
self.assertIn("`chunk-preflight --help`", said)
self.assertIn("`Release review of <release>` has landed since the cut.", planned(EMPTY, LastCut("v0.1.0", "", 4, [EMPTY]), "origin/main", BRANCH).why, "todo.md named no release since the cut")
self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main", BRANCH).why)
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
@@ -722,7 +724,7 @@ class Plans(unittest.TestCase):
)
for todo, commits, todos, reviewed, fact, release in cases:
with self.subTest(todo=todo, commits=commits, todos=todos, reviewed=reviewed):
why = planned(todo, LastCut("v0.1.0", "", commits, todos, reviewed), "origin/main", BRANCH).why
why = planned(todo, LastCut("v0.1.0", "", commits, todos, frozenset({(0, 2, 0)} if reviewed else ())), "origin/main", BRANCH).why
self.assertIn(fact, why)
self.assertIn(release, why)
+79
View File
@@ -0,0 +1,79 @@
"""Run a patch's ci.sh with its output in a file the human can follow, and stop it where it runs too long."""
import contextlib
import os
import pathlib
import signal
import subprocess
import typing
from deploy_release.patch import Ci, CiRan
from failure import Failure
from deploy_release.trace import Say
from forge.pulls import WAIT_SECONDS
# As long as a pull request's checks get, since they run the same ci.sh.
CI_SECONDS = WAIT_SECONDS
# How long a stopped ci.sh has to end on SIGINT before it is killed.
GRACE_SECONDS = 10
# How long docker has to remove a stopped ci.sh's container.
REMOVE_SECONDS = 60
# Where ci.sh reads the name to give its test container.
CONTAINER = "CI_CONTAINER"
# Removes the container of a name, running or not; a Failure where it may still run.
Remove = typing.Callable[[str], Failure | None]
def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remove: Remove, grace: float = GRACE_SECONDS) -> Ci:
"""Runs ci.sh in a worktree with its output in log, as it comes, and its test container named container. A Failure where it can't start, where log can't be written, or where it still runs after seconds. In that last case the runner stops ci.sh, each process ci.sh started, and that container."""
def run(worktree: pathlib.Path) -> CiRan | Failure:
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
try:
with log.open("wb") as output:
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container})
try:
code = process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
left = stopped(process, grace, container, remove)
running = f", but its container {container} may still run: {left.reason}" if left else ""
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped{running}; {log} holds its output")
except BaseException:
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
stopped(process, grace, container, remove)
raise
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
except OSError as failure:
return Failure(f"ci.sh could not run: {failure}")
return run
def stopped(process: subprocess.Popen[bytes], grace: float, container: str, remove: Remove) -> Failure | None:
"""End process's whole group, SIGINT first, then SIGKILL once grace seconds have passed, and then its container; a Failure where the container may still run."""
try:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=grace)
finally:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
process.wait()
# The daemon runs the container, outside the group, and no signal to ci.sh's docker CLI ends the tests in it. It is removed last, once nothing in the group can start it.
left = remove(container)
return left
def removed_container(container: str, run: typing.Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> Failure | None:
"""Removes container with docker, running or not; None too where no such container exists."""
argv = ["docker", "rm", "--force", container]
try:
ran = run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=REMOVE_SECONDS)
except (OSError, subprocess.TimeoutExpired) as failure:
return Failure(f"{' '.join(argv)} failed: {failure}")
return Failure(f"{' '.join(argv)} failed: {ran.stderr.strip()}") if ran.returncode else None
def lasting(seconds: float) -> str:
count, unit = (seconds / 60, "minute") if seconds >= 60 else (seconds, "second")
return f"{count:g} {unit}{'' if count == 1 else 's'}"
+58 -39
View File
@@ -3,9 +3,9 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import contextlib
import dataclasses
import pathlib
import shutil
import sys
import tempfile
import typing
@@ -17,17 +17,26 @@ from failure import Failure
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from forge.commands import forge_of, runner
from plan.release import newest_tag, Release, tagged, UNRELEASED_HEADING, version
from plan.release import newest_tag, Release, REVIEW_TITLE, tagged, UNRELEASED_HEADING, version
from forge import pulls
from deploy_release import release_pull
from deploy_release.trace import Say
from project_config import templates
CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version."
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
@dataclasses.dataclass(frozen=True)
class Ready:
"""The next release, which holds no item in todo.md while changes are unreleased."""
release: Release
# Whether its release review has landed.
reviewed: bool
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None], say: Say) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped. say takes each step as it finishes."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
@@ -37,17 +46,20 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
ref = default_ref(cwd=clone)
if isinstance(ref, Failure):
return ref
release = ready_release(clone, ref)
if isinstance(release, Failure):
return release
named = version(release)
if isinstance(patched := patch_refusal(clone, ref, release), Failure):
ready = ready_release(clone, ref)
if isinstance(ready, Failure):
return ready
named = version(ready.release)
# The patch refusal comes before the review's: a patch takes no release review, so "hasn't landed" would send the human the wrong way.
if isinstance(patched := patch_refusal(clone, ref, ready.release), Failure):
return patched
if not ready.reviewed:
return Failure(f"the release review of {named} hasn't landed: {ref} holds no commit titled `{REVIEW_TITLE}{named}` after the newest tag. `chunk-preflight --help` says which commit counts.")
title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}"
merged = commit_titled(title, ref, clone)
if merged is None:
build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep, say)
if isinstance(landed, Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
@@ -59,13 +71,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
return merged
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
return made
said(f"tagged {merged[:12]} {tag}")
say(f"tagged {merged[:12]} {tag}")
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
delete_release_branch(clone, branch)
say(f"pushed the tag {tag}")
delete_release_branch(clone, branch, say)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
@@ -83,21 +95,16 @@ def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None:
return None
def said(step: str) -> None:
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
print(f"deploy-release: {step}", file=sys.stderr)
def delete_release_branch(clone: str, branch: str) -> None:
def delete_release_branch(clone: str, branch: str, say: Say) -> None:
"""Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then."""
listed = branch_head(branch, clone)
if listed is None:
return
deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone)
if isinstance(deleted, Failure):
said(f"warning: the branch {branch} stays on origin: {deleted.reason}")
say(f"warning: the branch {branch} stays on origin: {deleted.reason}")
else:
said(f"deleted the branch {branch} on origin")
say(f"deleted the branch {branch} on origin")
def drop_unpushed_cut_tags(clone: str) -> Failure | None:
@@ -134,23 +141,23 @@ def clone_plan(clone: str) -> FilePlan:
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased."""
def ready_release(clone: str, ref: str) -> Ready | Failure:
"""The next release, as chunk-preflight works it out, where it holds no item in todo.md and changes are unreleased, with whether its release review has landed: the caller decides whether the cut needs one."""
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
if isinstance(plan.plan, Failure):
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
return Ready(release, reviewed=True)
case ReadyToCut():
return Failure("todo.md names no release after the last one cut")
case Next(release=release) if release is not None:
return Failure(f"release {version(release)} still holds items in todo.md")
case ReviewDue(release=release) if not review and release is not None:
return release
case ReviewDue(release=release):
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
case ReviewDue(release=release) if release is not None:
return Ready(release, reviewed=False)
case ReviewDue():
return Failure("the release review of the next release hasn't landed")
case Unplanned():
return Failure("every change is released already: nothing has landed since the last release cut")
case Cut(release=release):
@@ -170,7 +177,7 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None]) -> Failure | None:
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None], say: Say) -> Failure | None:
"""Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it.
build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet."""
@@ -188,7 +195,7 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
if isinstance(pushed := build(head), Failure):
return pushed
said(f"pushed the branch {branch}")
say(f"pushed the branch {branch}")
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
if isinstance(head, Failure):
return head
@@ -198,19 +205,19 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
return created
number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, str):
said(f"opened pull request {number}")
say(f"opened pull request {number}")
if isinstance(number, Failure):
return number
required = pulls.required_checks(on, base, run)
if isinstance(required, Failure):
return required
said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
say(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
if isinstance(passed := pulls.checks_passed(on, number, head, required, run, sleep), Failure):
return passed
said(f"the checks of pull request {number} passed")
say(f"the checks of pull request {number} passed")
if isinstance(merged := release_pull.merge(on, number, head, run), Failure):
return merged
said(f"merged pull request {number}")
say(f"merged pull request {number}")
return None
@@ -232,16 +239,28 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
with scratch_worktree(clone, ref) as worktree:
if isinstance(worktree, Failure):
return worktree
changelog = worktree / "CHANGELOG.md"
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
changelog.write_text(renamed)
def renamed(changelog: str | None) -> str | Failure:
text, count = UNRELEASED_HEADING.subn(f"## {named}", changelog or "", count=1)
return text if count else Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"rename ## Unreleased to ## {named} in the cut's worktree", "Nothing is pushed.", renamed), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, branch, replacing)
def rewritten(file: pathlib.Path, doing: str, outcome: str, rewrite: typing.Callable[[str | None], str | Failure]) -> Failure | None:
"""Replace file's text with what rewrite makes of it, or of None where there is no such file. Where rewrite gives a Failure, return it and leave the file. Where the file can't be read or written, the Failure names doing, the step that stopped, then the file, and ends with outcome, a sentence on where that leaves the run."""
try:
text = rewrite(file.read_text(encoding="utf-8") if file.exists() else None)
if isinstance(text, Failure):
return text
file.write_text(text, encoding="utf-8")
except (OSError, UnicodeError) as failure:
return Failure(f"could not {doing}: {failure}" + ("" if str(file) in str(failure) else f" ({file})") + f". {outcome}")
return None
@contextlib.contextmanager
def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]:
"""A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it."""
+35 -7
View File
@@ -18,7 +18,7 @@ memory, stay as they are.
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
refuses without changing anything, unless that release holds no item in todo.md, its release review has
landed and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
landed, as chunk-preflight --help counts one, and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
release that is a patch of the newest tag, such as 0.15.2 after v0.15.1, since it would ship all of main: cut that
with --cut-patch.
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
@@ -33,6 +33,9 @@ with --cut-patch.
deletes the branch on origin, then moves <checkout> to the tag as above. A failed delete only warns.
It says on stderr as each step finishes, and ends stdout, after the changelog, with the line
`Done: v<version> is cut and pushed, and <checkout> is on it.`
It keeps each of those lines, with its time in UTC, in the run's trace: a file of its own under
$XDG_STATE_HOME/deploy-release (default ~/.local/state/deploy-release), named by when the run began. --cut-patch does too.
Where Ctrl-C or an unexpected fault ends the run, the trace ends with a line that starts `stopped:`.
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
@@ -51,7 +54,8 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
3. It runs ci.sh on that commit, and stops where it fails, before anything is tagged.
3. It runs ci.sh on that commit and names on stderr the file, beside the run's trace, that takes ci.sh's output. It
stops where ci.sh fails or still runs after 30 minutes, before anything is tagged.
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
@@ -62,13 +66,16 @@ pull request. Once the merge-back has merged, the release is cut: where only the
"""
import os
import pathlib
import shlex
import sys
import time
from deploy_release.ci_script import ci_runner, CI_SECONDS, removed_container
from deploy_release.cut import cut
from deploy_release.patch import cut_patch
from deploy_release.deploy import deploy
from failure import Failure
from deploy_release import trace
def main(argv: list[str]) -> int:
@@ -82,12 +89,33 @@ def main(argv: list[str]) -> int:
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
return 1
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
if commits is not None:
moved = cut_patch(os.getcwd(), checkout, commits, time.sleep)
else:
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
if not cutting and commits is None:
moved = deploy(checkout)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
return 1
print(moved)
return 0
clone, now = os.getcwd(), time.time
folder, name = trace.trace_folder(os.environ, pathlib.Path.home()), trace.run_name(now(), os.getpid())
begun = trace.started(folder, name, f"deploy-release {shlex.join([*argv[:2 if patching else 1], checkout])} in {clone}", now)
if isinstance(begun, Failure):
print(f"deploy-release: warning: {begun.reason}", file=sys.stderr)
file = None if isinstance(begun, Failure) else begun
say = trace.saying(file, now, sys.stderr)
try:
if commits is not None:
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say, f"deploy-release-ci-{name}", removed_container))
else:
moved = cut(clone, checkout, time.sleep, say)
except BaseException as stopped:
# Ctrl-C or a fault nobody foresaw: its traceback reaches only the terminal, so the trace says the run ended here.
trace.kept(file, f"stopped: {stopped!r}", now, sys.stderr)
raise
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
say(moved.reason)
return 1
print(moved)
# The ending is on stdout already, so only the trace takes it.
trace.kept(file, moved.splitlines()[-1], now, sys.stderr)
return 0
+67 -34
View File
@@ -5,15 +5,15 @@ A rerun takes the tag an earlier run pushed, once it checks the tag lists the sa
import dataclasses
import pathlib
import re
import subprocess
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, rewritten, same_origin, scratch_worktree
from deploy_release.deploy import deploy
from failure import Failure
from forge.commands import forge_of
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
from deploy_release.trace import Say
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
@@ -36,29 +36,42 @@ class Patch:
entries: list[str]
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit."""
@dataclasses.dataclass(frozen=True)
class CiRan:
code: int
# stdout and stderr, as ci.sh interleaved them.
output: str
class Ci(typing.Protocol):
"""Runs the ci.sh that worktree holds, as ci_script.ci_runner's does: a Failure where it could not start or was stopped."""
def __call__(self, worktree: pathlib.Path) -> CiRan | Failure: ...
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None], say: Say, ci: Ci) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit. say takes each step as it finishes, and ci runs the patch's ci.sh."""
patch = planned(clone, checkout, commits)
if isinstance(patch, Failure):
return patch
for commit in patch.commits:
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
say(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
tag, branch = f"v{patch.named}", f"release-{patch.named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch, say, ci)
if isinstance(made, Failure):
return made
build = lambda replacing: push_merge_back(clone, patch, replacing)
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep, say), Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
return fetched
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
delete_release_branch(clone, branch)
delete_release_branch(clone, branch, say)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
@@ -88,12 +101,12 @@ def planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
if base is None or cut is None:
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
named = version((cut[0], cut[1], cut[2] + 1))
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
if version(release) != named:
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
ready = ready_release(clone, ref)
if isinstance(ready, Failure):
return ready
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut whether or not ready.reviewed.
if version(ready.release) != named:
return Failure(f"the next release in todo.md is {version(ready.release)}, not {named}, the patch of {base}: file the fix under {named}")
picked = patch_commits(clone, ref, base, commits)
if isinstance(picked, Failure):
return picked
@@ -118,7 +131,7 @@ def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] |
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none, or where ref's CHANGELOG.md has no such section, which the merge-back moves the entries out of."""
added: set[str] = set()
for commit in commits:
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
@@ -128,7 +141,11 @@ def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | F
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
unreleased = section(changelog, UNRELEASED_TITLE)
# The merge-back finds the heading with unreleased_start only after the tag is pushed, so check it here first.
if unreleased is None or unreleased_start(changelog.split("\n")) is None:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section, which the patch's entries come from: add it on {ref}")
entries = [line for line in unreleased if line in added]
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
@@ -143,7 +160,7 @@ def tagged_entries(clone: str, patch: Patch) -> Failure | None:
return None
def tag_patch(clone: str, patch: Patch) -> Failure | None:
def tag_patch(clone: str, patch: Patch, say: Say, ci: Ci) -> Failure | None:
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
with scratch_worktree(clone, patch.base) as worktree:
@@ -152,21 +169,22 @@ def tag_patch(clone: str, patch: Patch) -> Failure | None:
for commit in patch.commits:
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
head = lambda changelog: headed("# Changelog\n" if changelog is None else changelog, patch.entries, patch.named)
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"head CHANGELOG.md with ## {patch.named} in the patch's worktree", "Nothing is tagged.", head), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref), Failure):
say(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref, ci), Failure):
return tested
said("ci.sh passed")
say("ci.sh passed")
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
return made
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
say(f"pushed the tag {tag}")
return None
@@ -187,7 +205,8 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
if not diff:
return None
patch_file = worktree.parent / "commit.patch"
patch_file.write_text(diff)
if isinstance(written := rewritten(patch_file, f"write {commit[:12]}'s changes to a file to apply", "Nothing is tagged.", lambda _: diff), Failure):
return written
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), cwd=str(worktree)), Failure):
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
return Failure(
@@ -199,14 +218,16 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
return None
def run_ci(worktree: pathlib.Path, ref: str) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
def run_ci(worktree: pathlib.Path, ref: str, ci: Ci) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head, run by ci; a Failure with the end of its output where it fails, or with ci's reason where it could not run or was stopped."""
if not (worktree / "ci.sh").exists():
return Failure("the patch holds no ci.sh to test it with")
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
if ran.returncode == 0:
ran = ci(worktree)
if isinstance(ran, Failure):
return Failure(f"{ran.reason}. Nothing is tagged: fix that and rerun.")
if ran.code == 0:
return None
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
tail = "\n".join(ran.output.strip().splitlines()[-30:])
return Failure(f"ci.sh failed on the patch, so nothing is tagged. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
@@ -217,19 +238,31 @@ def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure
return worktree
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
# The tag is pushed by now, so each stop here says that a rerun with the same commits takes it and builds only this merge-back again.
rerun = f"v{patch.named} is pushed, and a rerun with the same commits merges it back."
def move(changelog: str | None) -> str | Failure:
moved = moved_entries(changelog or "", patch.entries, patch.named, patch.ref)
return Failure(f"{moved.reason}: add the heading there. {rerun}") if isinstance(moved, Failure) else moved
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"move the entries of {patch.named} out of ## Unreleased in the merge-back's worktree", rerun, move), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, f"release-{patch.named}", replacing)
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section."""
def moved_entries(changelog: str, entries: list[str], named: str, ref: str) -> str | Failure:
"""changelog, as ref holds it, with entries taken out of its ## Unreleased section and put in a ## named section right below that section; a Failure where it has no such heading."""
lines = changelog.split("\n")
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
start = unreleased_start(lines)
if start is None:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased heading to move the entries of {named} from")
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
kept = [line for line in lines[start + 1:end] if line not in entries]
while kept and not kept[-1].strip():
kept.pop()
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])
def unreleased_start(lines: list[str]) -> int | None:
"""The index in lines of a changelog's ## Unreleased heading; None where it has none."""
return next((index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line)), None)
+364 -5
View File
@@ -1,16 +1,22 @@
import contextlib
import io
import json
import os
import pathlib
import signal
import subprocess
import sys
import tempfile
import threading
import time
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from deploy_release import ci_script, cut, patch, trace
from failure import Failure
from test_env import isolated_env
from deploy_release import patch
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
@@ -244,7 +250,7 @@ class Cut(unittest.TestCase):
(fake / name).write_text(FAKE_FORGE)
(fake / name).chmod(0o755)
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"}
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}", "XDG_STATE_HOME": str(self.temp / "state")}
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
self.clone = self.temp / "claude-config"
@@ -470,6 +476,77 @@ class Cut(unittest.TestCase):
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
def traces(self) -> list[str]:
"""The text of each run's trace, oldest first."""
return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")]
def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self):
self.assert_cut(self.cut())
[kept] = self.traces()
lines = kept.splitlines()
self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}Z deploy-release --cut {self.target} in {self.clone}$")
self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z pushed the tag v0\.2\.0$")
self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1])
[file] = (self.temp / "state" / "deploy-release").glob("*.log")
self.assertRegex(file.name, r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z-[0-9]+\.log$")
def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self):
self.assert_cut(self.cut())
self.assertEqual(self.cut().returncode, 1)
first, second = self.traces()
self.assertTrue(second.endswith(" release 0.3.0 still holds items in todo.md\n"), second)
self.assertNotIn("still holds items", first)
def test_refuses_a_release_whose_review_has_not_landed_naming_the_commit_title_that_counts(self):
self.assert_cut(self.cut())
self.git(self.clone, "pull", "-q", "--ff-only", "origin", "main")
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.2.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Ship item 2")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut()
self.assertEqual(ran.returncode, 1)
self.assertIn("the release review of 0.3.0 hasn't landed", ran.stderr)
self.assertIn("`Release review of 0.3.0`", ran.stderr)
self.assertIn("`chunk-preflight --help`", ran.stderr)
def test_a_cut_stopped_by_ctrl_c_ends_its_trace_saying_so(self):
self.set_checks("pending")
process = subprocess.Popen([sys.executable, str(TOOL), "--cut", str(self.target)], cwd=self.clone, env=self.env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(process.kill)
deadline = time.monotonic() + 30
while not any("waiting for the checks" in kept for kept in self.traces()) and time.monotonic() < deadline:
time.sleep(0.05)
process.send_signal(signal.SIGINT)
self.assertNotEqual(process.wait(timeout=30), 0)
[kept] = self.traces()
self.assertRegex(kept.splitlines()[-1], r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z stopped: KeyboardInterrupt\(\)$")
def test_reads_whether_the_next_releases_review_landed_beside_the_release(self):
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 2, 0), reviewed=True))
self.plan_patch()
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False))
def test_says_why_no_release_is_ready_where_nothing_has_landed_or_no_release_is_named_and_reviewed(self):
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO}, "Cut release 0.4.0")
self.git(self.clone, "tag", "-a", "v0.4.0", "-m", "Cut release 0.4.0")
self.git(self.clone, "push", "-q", "origin", "main", "--tags")
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("every change is released already: nothing has landed since the last release cut"))
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Third.\n\n## 0.4.0\n\n- Second.\n\n## 0.1.0\n\n- First.\n"}, "Ship a third change")
self.git(self.clone, "push", "-q", "origin", "main")
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), Failure("the release review of the next release hasn't landed"))
def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self):
ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}))
self.assertEqual(ran.returncode, 1)
self.assertIn("CHANGELOG.md on origin/main has no ## Unreleased section", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_says_where_ci_shs_output_goes_and_keeps_it_there(self):
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"}))
self.assertEqual(ran.returncode, 0, ran.stderr)
[log] = (self.temp / "state" / "deploy-release").glob("*-ci.log")
self.assertEqual(log.read_text(), "the suite ran\n")
self.assertIn(f"ci.sh's output goes to {log}", ran.stderr)
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
self.commit({"feature.txt": "new\n"}, "Add a feature")
@@ -678,6 +755,285 @@ class Cut(unittest.TestCase):
def still_runs(pid: int) -> bool:
"""Whether the process pid runs: one that ended and that nobody has waited for yet doesn't."""
try:
return pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
except OSError:
return False
@contextlib.contextmanager
def typed(text: bytes) -> typing.Iterator[None]:
"""This process's stdin holding text, as a terminal someone typed it at would, for what a child inherits."""
kept = os.dup(0)
reading, writing = os.pipe()
os.write(writing, text)
os.close(writing)
os.dup2(reading, 0)
os.close(reading)
try:
yield
finally:
os.dup2(kept, 0)
os.close(kept)
class PatchCi(unittest.TestCase):
"""The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh."""
def setUp(self):
self.worktree = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)])
self.log = self.worktree / "ci.log"
self.said: list[str] = []
self.removed: list[str] = []
self.remove = lambda container: self.removed.append(container)
def test_passes_where_ci_sh_exits_zero(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
seen: list[pathlib.Path] = []
self.assertIsNone(patch.run_ci(self.worktree, "origin/main", lambda worktree: seen.append(worktree) or patch.CiRan(0, "fine\n")))
self.assertEqual(seen, [self.worktree])
def test_a_failed_ci_sh_gives_the_last_30_lines_of_its_output(self):
(self.worktree / "ci.sh").write_text("exit 1\n")
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: patch.CiRan(1, "".join(f"line {number}\n" for number in range(1, 41))))
self.assertIsInstance(failed, Failure)
self.assertIn("ci.sh failed on the patch, so nothing is tagged. Fix it on origin/main", failed.reason)
self.assertTrue(failed.reason.endswith("\nline 11\n" + "\n".join(f"line {number}" for number in range(12, 41))), failed.reason)
self.assertNotIn("line 10\n", failed.reason)
def test_a_ci_sh_that_could_not_run_or_was_stopped_tags_nothing_and_gives_the_runners_reason(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: Failure("ci.sh still ran after 30 minutes and was stopped; /state/run-ci.log holds its output"))
self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped; /state/run-ci.log holds its output. Nothing is tagged: fix that and rerun."))
def test_refuses_a_patch_without_ci_sh_before_running_anything(self):
self.assertEqual(patch.run_ci(self.worktree, "origin/main", lambda worktree: self.fail("ran")), Failure("the patch holds no ci.sh to test it with"))
def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self):
(self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n")
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertEqual(ran, patch.CiRan(3, "out\nerr\n"))
self.assertEqual(self.log.read_text(), "out\nerr\n")
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"])
def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self):
(self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n")
began = time.monotonic()
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
self.assertLess(time.monotonic() - began, 20)
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
self.assertEqual(self.log.read_text(), "started\n")
child = int((self.worktree / "child.pid").read_text())
deadline = time.monotonic() + 5
while still_runs(child) and time.monotonic() < deadline:
time.sleep(0.05)
self.assertFalse(still_runs(child), "the process ci.sh started still runs")
def test_the_runner_kills_a_stopped_ci_sh_that_ignores_the_interrupt_once_its_grace_has_passed(self):
(self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n")
began = time.monotonic()
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
self.assertLess(time.monotonic() - began, 20)
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
self.assertEqual(self.removed, ["ci-of-a-test"])
def test_the_runner_stops_ci_sh_and_removes_its_container_where_the_cut_is_interrupted(self):
(self.worktree / "ci.sh").write_text("trap '' INT\necho started\nsleep 60\n")
def interrupt_once_ci_sh_runs():
while not (self.log.exists() and self.log.read_bytes()):
time.sleep(0.02)
os.kill(os.getpid(), signal.SIGINT)
began = time.monotonic()
threading.Thread(target=interrupt_once_ci_sh_runs, daemon=True).start()
with self.assertRaises(KeyboardInterrupt):
ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
self.assertLess(time.monotonic() - began, 20)
self.assertEqual(self.removed, ["ci-of-a-test"])
def test_stopping_a_ci_sh_that_ended_already_still_removes_its_container(self):
process = subprocess.Popen(["true"], start_new_session=True)
process.wait()
self.assertIsNone(ci_script.stopped(process, 0.2, "ci-of-a-test", self.remove))
self.assertEqual(self.removed, ["ci-of-a-test"])
def test_the_runner_gives_ci_sh_no_input_to_wait_for(self):
(self.worktree / "ci.sh").write_text('read line\necho "read: $line"\n')
with typed(b"typed\n"):
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertEqual(ran, patch.CiRan(0, "read: \n"))
def test_the_runner_gives_output_that_is_not_utf_8_with_each_such_byte_replaced(self):
(self.worktree / "ci.sh").write_text("printf 'caf\\351 ok\\n'\n")
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertEqual(ran, patch.CiRan(0, "caf\ufffd ok\n"))
def test_the_runner_says_its_bound_in_minutes_from_a_minute_up(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
for seconds, lasting in ((1800, "30 minutes"), (60, "1 minute"), (59, "59 seconds"), (1, "1 second")):
with self.subTest(seconds=seconds):
self.said.clear()
ci_script.ci_runner(self.log, seconds, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after {lasting}"])
def test_the_runner_names_ci_shs_container_and_removes_it_where_it_stops_ci_sh(self):
(self.worktree / "ci.sh").write_text('echo "$CI_CONTAINER"\nsleep 60\n')
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
self.assertEqual(self.log.read_text(), "ci-of-a-test\n")
self.assertEqual(self.removed, ["ci-of-a-test"])
def test_the_runner_says_where_the_container_of_a_stopped_ci_sh_may_still_run(self):
(self.worktree / "ci.sh").write_text("sleep 60\n")
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", lambda container: Failure("docker rm --force ci-of-a-test failed: no daemon"), grace=0.2)(self.worktree)
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped, but its container ci-of-a-test may still run: docker rm --force ci-of-a-test failed: no daemon; {self.log} holds its output"))
def test_the_runner_removes_no_container_where_ci_sh_ends_in_time(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertEqual(self.removed, [])
def test_removing_a_container_gives_a_failure_where_docker_fails_and_none_where_it_removes(self):
asked: list[list[str]] = []
def docker(code: int, stderr: str):
return lambda argv, **options: asked.append(argv) or subprocess.CompletedProcess(argv, code, "", stderr)
self.assertIsNone(ci_script.removed_container("ci-of-a-test", docker(0, "")))
self.assertEqual(asked, [["docker", "rm", "--force", "ci-of-a-test"]])
self.assertEqual(ci_script.removed_container("ci-of-a-test", docker(1, "Cannot connect to the Docker daemon\n")), Failure("docker rm --force ci-of-a-test failed: Cannot connect to the Docker daemon"))
def test_removing_a_container_gives_a_failure_where_docker_cannot_start(self):
def no_docker(argv, **options):
raise FileNotFoundError("docker")
self.assertEqual(ci_script.removed_container("ci-of-a-test", no_docker), Failure("docker rm --force ci-of-a-test failed: docker"))
def test_removing_a_container_gives_dockers_own_error_and_no_input_to_wait_for(self):
fake = self.worktree / "fake-bin"
fake.mkdir()
(fake / "docker").write_text('#!/bin/sh\nread line\necho "no daemon for $*, read: $line" >&2\nexit 1\n')
(fake / "docker").chmod(0o755)
found_first = lambda argv, **options: subprocess.run(argv, env={**os.environ, "PATH": f"{fake}:{os.environ['PATH']}"}, **options)
with typed(b"typed\n"):
left = ci_script.removed_container("ci-of-a-test", found_first)
self.assertEqual(left, Failure("docker rm --force ci-of-a-test failed: no daemon for rm --force ci-of-a-test, read:"))
def test_removing_a_container_gives_a_failure_where_docker_takes_longer_than_a_minute(self):
def slow_docker(argv, **options):
raise subprocess.TimeoutExpired(argv, options["timeout"])
left = ci_script.removed_container("ci-of-a-test", slow_docker)
self.assertIsInstance(left, Failure)
self.assertTrue(left.reason.startswith("docker rm --force ci-of-a-test failed: "), left.reason)
self.assertIn("timed out after 60 seconds", left.reason)
def test_ci_sh_names_its_container_only_where_it_is_given_a_name(self):
script = (pathlib.Path(__file__).resolve().parents[2] / "ci.sh").read_text()
self.assertIn('${CI_CONTAINER:+--name "$CI_CONTAINER"}', script)
def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self):
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree / "gone")
self.assertIsInstance(ran, Failure)
self.assertIn("ci.sh could not run: ", ran.reason)
self.assertIn(str(self.worktree / "gone"), ran.reason)
def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
self.assertIsInstance(ran, Failure)
self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason)
class Trace(unittest.TestCase):
"""What a cut says, in-process, with the clock and stderr handed in."""
def setUp(self):
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
# 2026-11-27T09:30:05Z, in seconds since the epoch.
self.now = lambda: 1795771805.0
def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self):
self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release"))
self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release"))
def test_names_a_run_by_its_start_and_its_process(self):
self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05Z-4711")
def test_starts_a_trace_with_the_command_then_appends_each_step_with_its_time_and_says_it(self):
file = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
self.assertEqual(file, self.temp / "state" / "deploy-release" / "run.log")
out = io.StringIO()
say = trace.saying(file, self.now, out)
say("pushed the tag v0.2.0")
say("merged pull request 3")
self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n")
self.assertEqual(file.read_text(), "2026-11-27T09:30:05Z deploy-release --cut\n2026-11-27T09:30:05Z pushed the tag v0.2.0\n2026-11-27T09:30:05Z merged pull request 3\n")
def test_starts_a_later_runs_trace_beside_the_earlier_one(self):
folder = self.temp / "state" / "deploy-release"
first = trace.started(folder, "first", "deploy-release --cut", self.now)
second = trace.started(folder, "second", "deploy-release --cut-patch a..b", self.now)
self.assertEqual((first, second), (folder / "first.log", folder / "second.log"))
self.assertEqual(second.read_text(), "2026-11-27T09:30:05Z deploy-release --cut-patch a..b\n")
self.assertEqual(first.read_text(), "2026-11-27T09:30:05Z deploy-release --cut\n")
def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self):
(self.temp / "state").write_text("a file where the folder goes\n")
made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
self.assertIsInstance(made, Failure)
self.assertIn(str(self.temp / "state" / "deploy-release" / "run.log"), made.reason)
def test_still_says_each_step_where_there_is_no_trace_or_it_cannot_be_written(self):
out = io.StringIO()
trace.saying(None, self.now, out)("pushed the tag v0.2.0")
trace.saying(self.temp / "gone" / "run.log", self.now, out)("merged pull request 3")
self.assertEqual(out.getvalue().splitlines()[:2], ["deploy-release: pushed the tag v0.2.0", "deploy-release: merged pull request 3"])
self.assertIn(f"warning: the trace {self.temp / 'gone' / 'run.log'} could not be written", out.getvalue().splitlines()[2])
class Rewritten(unittest.TestCase):
"""A cut's file edits, where the filesystem refuses one."""
def setUp(self):
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
def test_replaces_a_files_text_and_hands_none_for_a_file_that_is_not_there(self):
file = self.temp / "CHANGELOG.md"
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: f"{text!r} new\n"))
self.assertEqual(file.read_text(), "None new\n")
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: text.upper()))
self.assertEqual(file.read_text(), "NONE NEW\n")
def test_a_file_that_cannot_be_read_or_written_is_a_failure_naming_the_step_and_the_file(self):
folder = self.temp / "CHANGELOG.md"
folder.mkdir()
# A folder can't be read as a file, and a file in a folder that isn't there can't be written.
for file in (folder, self.temp / "gone" / "commit.patch"):
with self.subTest(file=file):
failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1", "Nothing is tagged.", lambda text: "new\n")
self.assertIsInstance(failed, Failure)
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1: "), failed.reason)
self.assertEqual(failed.reason.count(str(file)), 1, failed.reason)
self.assertTrue(failed.reason.endswith(f"'{file}'. Nothing is tagged."), failed.reason)
def test_a_file_that_is_not_utf_8_is_a_failure_naming_the_step_and_the_file(self):
file = self.temp / "CHANGELOG.md"
file.write_bytes(b"caf\xe9\n")
failed = cut.rewritten(file, "head CHANGELOG.md", "Nothing is tagged.", lambda text: "new\n")
self.assertIsInstance(failed, Failure)
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md: "), failed.reason)
self.assertTrue(failed.reason.endswith(f" ({file}). Nothing is tagged."), failed.reason)
self.assertEqual(failed.reason.count(str(file)), 1, failed.reason)
self.assertEqual(file.read_bytes(), b"caf\xe9\n")
def test_gives_the_rewrites_own_failure_and_leaves_the_file(self):
file = self.temp / "CHANGELOG.md"
file.write_text("old\n")
self.assertEqual(cut.rewritten(file, "x", "y", lambda text: Failure("no heading")), Failure("no heading"))
self.assertEqual(file.read_text(), "old\n")
class PatchChangelog(unittest.TestCase):
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
@@ -689,14 +1045,17 @@ class PatchChangelog(unittest.TestCase):
def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
def test_leaves_an_older_section_entry_that_reads_the_same(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
def test_puts_the_section_last_where_unreleased_is_the_last_section(self):
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1", "origin/main"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
def test_a_changelog_without_an_unreleased_heading_is_a_failure_that_names_it(self):
self.assertEqual(patch.moved_entries("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed."], "0.1.1", "origin/main"), Failure("CHANGELOG.md on origin/main has no ## Unreleased heading to move the entries of 0.1.1 from"))
if __name__ == "__main__":
+57
View File
@@ -0,0 +1,57 @@
"""What a cut says as each step finishes: on stderr, and in a file of the run's own, so the steps outlast the terminal."""
import pathlib
import time
import typing
from failure import Failure
from text_files import utc_stamp
# Says that one step of a cut finished, as `saying` makes it.
Say = typing.Callable[[str], None]
# The time now, in seconds since the epoch, as time.time gives it.
Clock = typing.Callable[[], float]
def trace_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
"""The folder each cut keeps its trace in, under the state folder as run-heavy finds it."""
state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state")
return pathlib.Path(state) / "deploy-release"
def run_name(began: float, pid: int) -> str:
"""The name of the files one run keeps, which sorts by when it began: that time in UTC, with no colon, so the name is valid on every disk."""
return f"{time.strftime('%Y-%m-%dT%H-%M-%SZ', time.gmtime(began))}-{pid}"
def stamped(at: float, line: str) -> str:
return f"{utc_stamp.utc(at)} {line}\n"
def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure:
"""A new trace, <folder>/<name>.log, whose first line is command; a Failure where it can't be written."""
file = folder / f"{name}.log"
try:
folder.mkdir(parents=True, exist_ok=True)
file.write_text(stamped(now(), command), encoding="utf-8")
except OSError as failure:
return Failure(f"the trace {file} could not be started: {failure}")
return file
def kept(trace: pathlib.Path | None, line: str, now: Clock, out: typing.TextIO) -> None:
"""Append line with its time, in UTC, to trace, where there is one. A trace that can't be written only warns on out, since the cut's own steps count."""
if trace is None:
return
try:
with trace.open("a", encoding="utf-8") as file:
file.write(stamped(now(), line))
except OSError as failure:
print(f"deploy-release: warning: the trace {trace} could not be written: {failure}", file=out)
def saying(trace: pathlib.Path | None, now: Clock, out: typing.TextIO) -> Say:
"""Says each step on out, so the human sees how far the cut got before the changelog fills the screen, and keeps it in trace."""
def say(step: str) -> None:
print(f"deploy-release: {step}", file=out)
kept(trace, step, now, out)
return say
+1 -2
View File
@@ -8,11 +8,10 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY
from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE
from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, REVIEW_LABEL, unfit, unfit_label
from failure import Failure
from do_epic.backend.jira_status import moved_by, moved_to
from plan.todo_table import MOVES
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.jira_start import Start, started
FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"]
+2
View File
@@ -9,6 +9,8 @@ from plan.todo_table import Exempt, item_fields, ItemFields, Moves, MOVES
from failure import Failure
from plan_store.jira_epic import SET_SCORES
# Marks the issue that asks for a repo's release review, beside the label that names the repo (finish.py). Not `release-review`, which could pass for the team's own release process: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one 3-0 from four.
REVIEW_LABEL = "do-epic-release-review"
# What a tracker accepts as a label: Jira refuses a label holding white space.
LABEL = re.compile(r"\S+")
+1 -1
View File
@@ -13,7 +13,7 @@ from do_epic.backend.contract import EpicStoreContract
from failure import Failure
from do_epic.backend.jira import JiraEpic
from adf_codec.convert import Refused
from do_epic.repo_pick import REVIEW_LABEL
from do_epic.backend.protocol import REVIEW_LABEL
from do_epic.backend.jira_start import Start
SITE = "https://acme.atlassian.net"
+2 -2
View File
@@ -34,8 +34,8 @@ import types
from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault
from failure import Failure
from do_epic.backend.protocol import LABEL
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL
from do_epic.backend.protocol import LABEL, REVIEW_LABEL
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME
from text_files.markdown_text import listed
from model_routing.ladder_file import read_ladder, SHIPPED
from do_epic.split import SPLIT_LABEL
+2 -2
View File
@@ -7,8 +7,8 @@ import fcntl
import pathlib
import typing
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL, team_label
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, team_label
from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL
from do_epic.epic_record import EpicRecord
from failure import Failure
from text_files.markdown_text import listed
+4 -3
View File
@@ -12,13 +12,14 @@ import pathlib
import typing
from do_epic.chunk_prompt import DRIVER
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL
from failure import Failure
from do_epic import findings
from do_epic.split import finished
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo, REVIEW_LABEL
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo
from text_files.markdown_text import listed
from text_files.piped_text import piped
from plan.release import REVIEW_TITLE
# Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it.
CLOSE = "--close-epic"
@@ -67,7 +68,7 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib
f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. "
f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"<summary>\" {findings.LABEL} <label> {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. "
f"The `<label>` is {listed([f'`{label_of(Repo(name), team)}` for {name}' for name in lacking], 'and')}. "
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `Release review of {epic}`. "
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `{REVIEW_TITLE}{epic}`. "
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
f"The chunk is finished once each issue is filed: {DRIVER} works them, and starts this chunk again once the epic holds no open issue."
)
+35 -18
View File
@@ -104,33 +104,50 @@ class Poll:
def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop:
"""Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was."""
# The last reason said for staying parked.
said = None
told = Told(poll, shown)
while True:
now = poll.gate()
if isinstance(now, gates.Gate):
awaits, stays = now.on, None
if isinstance(now, gates.Open):
full = resumed(poll.repo, poll.loop, poll.epic)
if full is None:
return unparked(poll, on, now)
told.tell(parked.SLOT, f"{now.news}, but the chunk stays parked: {full}")
elif isinstance(now, Failure):
told.tell(told.awaits or on, f"cannot read the gate: {now.reason}")
else:
if now.on != on:
if failed := poll.record(now):
return Stop(1, failed.reason)
on = now.on
elif isinstance(now, Failure):
awaits, stays = shown or on, f"cannot read the gate: {now.reason}"
else:
full = resumed(poll.repo, poll.loop, poll.epic)
if full is None:
failed = parked.unpark(poll.folder, poll.key)
return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}."
awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}"
if awaits != shown:
tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux)
shown = awaits
if stays is not None and stays != said:
say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True)
said = stays
told.tell(now.on, None)
poll.epic.effects.sleep(POLL_SECONDS)
@dataclasses.dataclass
class Told:
"""What the human has been told of a parked chunk, so that each read of its gate tells only what changed: what its window's name says it awaits, None where nothing yet, and the last reason said for staying parked."""
poll: Poll
awaits: str | None
reason: str | None = None
def tell(self, awaits: str, reason: str | None) -> None:
"""Names the window after what the chunk awaits, and says the reason it stays parked, None where the gate says it all. It skips what it told last."""
if awaits != self.awaits:
tmux.park(self.poll.loop.window, awaits, self.poll.epic.effects.tmux)
self.awaits = awaits
if reason is not None and reason != self.reason:
say(f"{reason}; trying again every {POLL_SECONDS} seconds", self.poll.epic.effects, stdout=True)
self.reason = reason
def unparked(poll: Poll, on: str, now: gates.Open) -> str | Stop:
"""Removes the file of the chunk that was parked on the gate on: what to tell its worker, which now says why it resumes."""
failed = parked.unpark(poll.folder, poll.key)
if failed is not None:
return Stop(1, failed.reason)
return f"{DRIVER_PARKED} its pull request awaited {"a person's merge" if on == gates.MERGE else on}. It resumes now: {now.news}."
def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None:
"""scheduler.resume for the parked chunk in loop's window, whose work is in the repo called repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
# A chunk that resumes starts no other, so it needs no start order.
-2
View File
@@ -16,8 +16,6 @@ from claude_code.entries import structured_output
REPO_PREFIX = "repo:"
CLAUDE_LABEL = "do-epic-claude"
HUMAN_LABEL = "do-epic-human"
# Marks the issue that asks for a repo's release review, beside the label that names the repo (finish.py). Not `release-review`, which could pass for the team's own release process: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one 3-0 from four.
REVIEW_LABEL = "do-epic-release-review"
# A repo's name is a folder name and part of a clone address, so claude's answer or a label a person typed must not hold a slash, a colon or a leading dot.
REPO_NAME = re.compile(r"\w[\w.-]*")
+15 -5
View File
@@ -2,6 +2,7 @@
import json
import os
import pathlib
import re
import typing
from mutate_changes.changed_lines import by_folder, label, runs
@@ -12,6 +13,9 @@ from git_cli.git_repo import Git
# cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out.
CARGO_FINISHED = frozenset({0, 2, 3})
CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable")
INFECTION = "vendor/bin/infection" # the project's own, as Composer installs it
# npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none.
STRYKER_RUN = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"]
GREMLINS_UNKILLED = frozenset({"LIVED", "NOT COVERED"})
# What Gremlins v0.6.0 needs of the diff it reads from git: one run of lines per hunk is all it mutates, so a hunk holds the changed
# lines and none around them, nor a neighbouring change; it takes each file's path after a b/; and it reads no colour codes. A user's git
@@ -112,14 +116,20 @@ def outcome_lines(path: pathlib.Path) -> list[str]:
return path.read_text(encoding="utf-8", errors="replace").splitlines() if path.is_file() else []
def glob_escaped(path: str) -> str:
"""A path as a glob that matches it. Stryker 10.1.1 reads each entry of --mutate as a glob, in which `app/[slug]/page.tsx`
matches `app/s/page.tsx` and not the file of that name. It reads a backslash as a slash, so no character can be escaped: a `?`
stands for each one a glob gives a meaning, and matches it."""
return re.sub(r"[][!()*+@{}]", "?", path)
# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't
# tell from a run that broke, so either fails the run.
def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure:
"""For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line
naming the files with no package.json above them, if any.
Stryker runs in the nearest folder above each file that holds a package.json. npx runs the project's own @stryker-mutator/core, else
one an earlier npx run cached, and installs none."""
Stryker runs in the nearest folder above each file that holds a package.json."""
report: list[str] = []
unplaced: list[str] = []
for folder, files in sorted(by_folder(top, changed, ("package.json",)).items()):
@@ -127,8 +137,8 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
if not os.path.isfile(os.path.join(top, folder, "package.json")):
unplaced = sorted(files)
continue
mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
ran = run(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
mutate = ",".join(f"{glob_escaped(path)}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
ran = run([*STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran)
report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()])
@@ -137,7 +147,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure:
"""A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base."""
ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top)
ran = run([INFECTION, "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output("Infection", ran)
return ["Infection in the checkout's top:", *ran.output.splitlines()]
+13 -1
View File
@@ -17,12 +17,12 @@ from mutate_changes.changed_lines import added_lines, by_folder, not_mutated, ru
from mutate_changes.mutmut_tool import copy_files, Ended, Folder, mutate_folder, NO_MUTANT, reported
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_lines, named, statuses
from failure import Failure
from mutate_changes.in_diff_tools import glob_escaped, run_stryker, with_plain_git_diff
from mutate_changes.bare_imports import imported_by_file_name
from test_env import isolated_env
from mutate_changes.mutmut_setup import left_out, mutmut_config
from mutate_changes import main
from mutate_changes.tool_process import Ran, run_tool, scratch_folder
from mutate_changes.in_diff_tools import with_plain_git_diff
SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n"
# The shape of the file mutmut 3 writes under mutants/: the original of each function and its mutants, with the original's lines.
@@ -163,6 +163,18 @@ class InDiffTools(unittest.TestCase):
self.assertEqual((env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"], env["GIT_CONFIG_KEY_6"], "GIT_CONFIG_KEY_7" in env), ("7", "diff.context", "diff.interHunkContext", False))
def test_a_path_goes_to_stryker_with_a_question_mark_for_each_character_a_glob_gives_a_meaning(self):
self.assertEqual(glob_escaped("app/[slug]/(shop)/{a}/b!c*d+e@f.tsx"), "app/?slug?/?shop?/?a?/b?c?d?e?f.tsx")
self.assertEqual(glob_escaped("src/pick-one_two.test.ts"), "src/pick-one_two.test.ts")
def test_stryker_is_handed_a_changed_file_whose_path_holds_a_globs_characters_as_a_glob_that_matches_it(self):
with tempfile.TemporaryDirectory() as top:
pathlib.Path(top, "package.json").write_text("{}")
ran: list[list[str]] = []
run_stryker(top, {"app/[slug]/page.tsx": frozenset({3, 4})}, lambda argv, cwd: ran.append(argv) or Ran(0, ""), 1)
self.assertEqual(ran[0][5:7], ["--mutate", "app/?slug?/page.tsx:3-4"])
class MutmutSetup(unittest.TestCase):
def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self):
for existing in ("", "[mutmut]\nsource_paths = old.py\nalso_copy = old\n"):
+2
View File
@@ -12,6 +12,8 @@ DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for 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.*)"
# What opens the title of a release review's first commit, before the release it reviews, or the epic's key in do-epic's finishing chunk. release_standing counts a review by it.
REVIEW_TITLE = "Release review of "
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
+21 -9
View File
@@ -230,6 +230,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
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 = [
# First what is wrong with a setting by itself, then with the settings together, then with the two that score a plan in Jira.
*(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)),
@@ -238,7 +239,26 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
*(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 []),
*([f"`{CODING_CONVENTIONS}` is {values[CODING_CONVENTIONS]!r}, not a list of paths, each {SPELLING}"] if conventions is None else []),
# Each setting that reaches a service needs the file that holds its credentials.
*combination_faults(values, epics, pages),
*([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 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_of(values), jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
def combination_faults(values: dict[str, object], epics: dict[str, Epic | None], pages: dict[str, Page]) -> list[str]:
"""Which of a config's settings may not stand together, as `project-config --help` says of each. values is the config, epics the Jira epic each of EPIC_SPELLINGS names, None where it names none, and pages the Confluence page of each record kept on one.
Three rules, in the order of the faults:
- a setting that reaches a service needs `env-file`;
- the goals in a Jira epic, a ranked record on a Confluence page and each of JIRA_PLAN_ONLY need `plan` to name a Jira epic, and such a plan needs both of JIRA_SCORE;
- the two JIRA_FINISH settings come together, and `review-request-comment` needs `epic-branch`."""
return [
*(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 []),
@@ -249,15 +269,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
*(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),
*finish_faults(values),
*([f"`{REVIEW_REQUEST_COMMENT}` is set, so `{EPIC_BRANCH}` must be set: the comment goes on pull requests into that branch"] if REVIEW_REQUEST_COMMENT in values and EPIC_BRANCH not in values else []),
*([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 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_of(values), jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
@dataclasses.dataclass(frozen=True)
+3 -2
View File
@@ -6,7 +6,7 @@ from failure import Failure
from plan.todo_table import Item, NoItemsTable
from text_files.markdown_text import listed
from plan_store.plans import Plan
from plan.release import Release, version
from plan.release import Release, REVIEW_TITLE, version
from project_config import templates
@@ -78,7 +78,8 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi
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.")
awaited = version(pick.release) if pick.release else "<release>"
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `{REVIEW_TITLE}{awaited}` has landed {'since the cut' if named is not None else 'yet'}. `chunk-preflight --help` says which commit counts. 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.")
+17 -15
View File
@@ -3,7 +3,7 @@ import dataclasses
from release_plan.awaiting_merge import awaiting, marked
from git_cli.git_repo import commits_since, file_at, git, Git
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, REVIEW_TITLE, tagged, UNRELEASED_TITLE
from failure import Failure
from forge.commands import forge_of, Run
from plan.todo_table import Item, items, next_item, renames
@@ -31,8 +31,8 @@ class LastCut:
commits: int | Failure
# todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; where the branch has no tag, at each commit that changed it. Empty where the tags cannot be read, and where no commit holds the plan.
todos_since: list[str] | Failure
# Whether a release review has landed since the tag, as release_reviewed reads it.
reviewed: bool | Failure = False
# The releases whose release review has landed since the cut, as reviewed_releases reads them.
reviews: frozenset[Release] | Failure = frozenset()
@dataclasses.dataclass(frozen=True)
@@ -70,7 +70,7 @@ class ReadyToCut:
@dataclasses.dataclass(frozen=True)
class ReviewDue:
"""The next release holds no item and work has landed towards it, but no release review has landed since the cut: `~/.claude/skills/larv-review/SKILL.md` → "Release review"."""
"""The next release holds no item and work has landed towards it, but its release review has not landed, as pick_from reads it: `~/.claude/skills/larv-review/SKILL.md` → "Release review"."""
# The next release, None where todo.md has named none since the cut.
release: Release | None
@@ -122,8 +122,8 @@ def default_plan(root: str, ref: str, plan: plans.PlanStore, changelog: stores.R
after = dated_cut(tag, changes)
since = tag if after is None else heading_commit(after, ref, changelog, root, run)
commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run)
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, titles, after, run)
return DefaultPlan(plan_stores.held_at(ref, plan, root, run), LastCut(tag, changes, commits, todos_since(tag, ref, plan.tracked, root, run), reviewed))
reviews = tag if isinstance(tag, Failure) else reviewed_releases(tag, ref, root, titles, after, run)
return DefaultPlan(plan_stores.held_at(ref, plan, root, run), LastCut(tag, changes, commits, todos_since(tag, ref, plan.tracked, root, run), reviews))
def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cwd: str, run: Git = git) -> str | None | Failure:
@@ -135,18 +135,18 @@ def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cw
return added if isinstance(added, Failure) else next(iter(added.split()), None)
def release_reviewed(tag: str | None, ref: str, cwd: str, titles: templates.Titles, after: Release | None = None, run: Git = git) -> bool | Failure:
"""Whether ref holds a commit titled as a release review opens, `Release review of <release>`: after tag, or anywhere where tag is None. A title that names no version, such as an epic's `Release review of ABC-12` (do_epic/finish.py), reviews no release.
def reviewed_releases(tag: str | None, ref: str, cwd: str, titles: templates.Titles, after: Release | None = None, run: Git = git) -> frozenset[Release] | Failure:
"""LastCut.reviews: each release that a commit on ref names in its title, as a release review opens, `Release review of <release>`. The commits read are those after tag, or all of them where tag is None. A title that names no version, such as an epic's `Release review of ABC-12` (do_epic/finish.py), reviews no release.
titles holds the project's title templates, and each commit title is read as the summary they give. after is the version a branch with no tag counts as cut, or None. A title counts only where its release is later than after, or than tag's version where after is None. A patch release cut beside the default branch and merged back leaves on ref, after its tag, the review of that patch, which reviews no later release.
titles holds the project's title templates, and each commit title is read as the summary they give. after is the version a branch with no tag counts as cut, or None. A release counts only where it is later than after, or than tag's version where after is None. A patch release cut beside the default branch and merged back leaves on ref, after its tag, the review of that patch, which reviews no later release. pick_from needs that where the next release has no name.
"""
log = run("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
if isinstance(log, Failure):
return log
summaries = [titles.summary(line) for line in log.splitlines()]
reviews = [summary.removeprefix("Release review of ") for summary in summaries if summary.startswith("Release review of ")]
reviews = [summary.removeprefix(REVIEW_TITLE) for summary in summaries if summary.startswith(REVIEW_TITLE)]
floor = after if after is not None else tagged(tag)
return any((named := parsed(review)) is not None and (floor is None or named > floor) for review in reviews)
return frozenset(named for review in reviews if (named := parsed(review)) is not None and (floor is None or named > floor))
def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str, run: Git = git) -> list[str] | Failure:
@@ -200,7 +200,7 @@ def chunk_item(found: list[Item], cut: LastCut) -> Pick:
def picked(weighed: Standing, cut: LastCut) -> Pick:
"""chunk_item's pick, from the plan's items already weighed against cut."""
upcoming = next_release(weighed, cut)
return pick_from(upcoming, next_item(weighed.carried), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
return pick_from(upcoming, next_item(weighed.carried), cut.reviews) if isinstance(upcoming, Upcoming) else upcoming
def next_release(weighed: Standing, cut: LastCut) -> Upcoming | Cut | Unknown:
@@ -249,9 +249,10 @@ def has_unreleased(cut: LastCut) -> bool | Failure:
return changes if isinstance(changes, Failure) else changes > 0
def pick_from(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
def pick_from(upcoming: Upcoming, first: Item | None, reviews: frozenset[Release] | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next. reviews is LastCut.reviews.
The next release's review has landed where reviews holds that release. Where the next release has no name, no title can name it, so a review of any release in reviews counts.
Unknown where the next release holds no item and the unreleased changes cannot be counted, or work has landed and git cannot say whether a release review has.
"""
if upcoming.plan_is_current:
@@ -260,8 +261,9 @@ def pick_from(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure)
return Unknown()
if not upcoming.unreleased:
return Unplanned(upcoming.release)
if isinstance(reviewed, Failure):
if isinstance(reviews, Failure):
return Unknown()
reviewed = bool(reviews) if upcoming.release is None else upcoming.release in reviews
return ReadyToCut(upcoming.release) if reviewed else ReviewDue(upcoming.release)
+84 -32
View File
@@ -145,16 +145,22 @@ class ChunkItem(unittest.TestCase):
)
for tag, changes, earliest, named, stands in cases:
with self.subTest(tag=tag, changes=changes, earliest=earliest, named=named):
self.assertEqual(release_standing.chunk_item(plan_under(earliest), release_standing.LastCut(tag, "", changes, naming(named), reviewed=True)), stands)
self.assertEqual(release_standing.chunk_item(plan_under(earliest), release_standing.LastCut(tag, "", changes, naming(named), frozenset({(0, 9, 3), (1, 2, 4), (1, 3, 0)}))), stands)
def test_calls_a_release_review_due_where_the_next_release_holds_no_item_and_none_landed_since_the_cut(self):
cut = lambda reviewed: release_standing.LastCut("v1.2.3", "", 4, naming({(1, 3, 0)}), reviewed)
self.assertEqual(release_standing.chunk_item([], cut(False)), release_standing.ReviewDue((1, 3, 0)))
self.assertEqual(release_standing.chunk_item([], cut(True)), release_standing.ReadyToCut((1, 3, 0)))
cut = lambda reviews: release_standing.LastCut("v1.2.3", "", 4, naming({(1, 3, 0)}), reviews)
self.assertEqual(release_standing.chunk_item([], cut(frozenset())), release_standing.ReviewDue((1, 3, 0)))
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 3, 0)}))), release_standing.ReadyToCut((1, 3, 0)))
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 2, 4), (1, 4, 0)}))), release_standing.ReviewDue((1, 3, 0)), "a review of another release reviews none of 1.3.0")
self.assertEqual(release_standing.chunk_item([], cut(Failure("log unreadable"))), release_standing.Unknown())
self.assertEqual(release_standing.chunk_item(plan_under((1, 3, 0)), cut(False)), release_standing.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out")
self.assertEqual(release_standing.chunk_item(plan_under((1, 3, 0)), cut(frozenset())), release_standing.Next((1, 3, 0), one((1, 3, 0))), "a review matters only once the release's items run out")
self.assertEqual(release_standing.chunk_item([], release_standing.LastCut("v1.2.3", "", 0, naming({(1, 3, 0)}))), release_standing.Unplanned((1, 3, 0)))
def test_counts_any_later_release_review_where_the_next_release_has_no_name(self):
cut = lambda reviews: release_standing.LastCut("v1.2.3", "", 4, [], reviews)
self.assertEqual(release_standing.chunk_item([], cut(frozenset())), release_standing.ReviewDue(None))
self.assertEqual(release_standing.chunk_item([], cut(frozenset({(1, 3, 0)}))), release_standing.ReadyToCut(None))
def test_takes_an_item_of_any_release_on_a_branch_with_no_tag(self):
for release in ((0, 0, 0), (0, 0, 1), (0, 1, 0)):
with self.subTest(release=release):
@@ -166,10 +172,11 @@ class ChunkItem(unittest.TestCase):
def test_calls_a_release_that_never_had_a_tag_finished_once_the_plan_files_no_item_under_it(self):
history = [HEADER + ROW.format(id=1, release="0.1.0") + ROW.format(id=2, release="0.1.1"), HEADER + ROW.format(id=2, release="0.1.1")]
cut = lambda reviewed: release_standing.LastCut(None, "", 4, history, reviewed)
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(False)), release_standing.ReviewDue((0, 1, 0)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(True)), release_standing.ReadyToCut((0, 1, 0)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), cut(False)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
cut = lambda reviews: release_standing.LastCut(None, "", 4, history, reviews)
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset())), release_standing.ReviewDue((0, 1, 0)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset({(0, 1, 1)}))), release_standing.ReviewDue((0, 1, 0)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 1)), cut(frozenset({(0, 1, 0)}))), release_standing.ReadyToCut((0, 1, 0)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), cut(frozenset())), release_standing.Next((0, 1, 0), one((0, 1, 0))))
def test_counts_a_dated_changelog_heading_as_cut_on_a_branch_with_no_tag(self):
changelog = "# Changelog\n\n## Unreleased\n\n## 0.0.1 - 2026-10-03\n\n- Shipped.\n"
@@ -211,30 +218,30 @@ class ChunkItem(unittest.TestCase):
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
run("init", "-q", "-b", "main")
run("commit", "-q", "--allow-empty", "-m", "Release review of ABC-12")
self.assertIs(release_standing.release_reviewed(None, "main", repo, BARE), False, "an epic's review reviews no release")
self.assertEqual(release_standing.reviewed_releases(None, "main", repo, BARE), frozenset(), "an epic's review reviews no release")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0")
run("tag", "v0.1.0")
run("commit", "-q", "--allow-empty", "-m", "Ship item 4")
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), False, "a review before the cut reviewed that release")
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset(), "a review before the cut reviewed that release")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
run("commit", "-q", "--allow-empty", "-m", "Answer architecture round 1: 0 🔴, 1 🟡 (0 misread); split loader")
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), True)
self.assertIs(release_standing.release_reviewed(None, "main", repo, BARE), True)
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset({(0, 2, 0)}))
self.assertEqual(release_standing.reviewed_releases(None, "main", repo, BARE), frozenset({(0, 1, 0), (0, 2, 0)}))
run("commit", "-q", "--allow-empty", "-m", "Release review of ABC-12")
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo, BARE), True)
self.assertIsInstance(release_standing.release_reviewed("v9.9.9", "main", repo, BARE), Failure)
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, True)
self.assertEqual(release_standing.reviewed_releases("v0.1.0", "main", repo, BARE), frozenset({(0, 2, 0)}))
self.assertIsInstance(release_standing.reviewed_releases("v9.9.9", "main", repo, BARE), Failure)
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset({(0, 2, 0)}))
run("tag", "v0.2.0")
run("commit", "-q", "--allow-empty", "-m", "PAY-9 - Release review of 0.3.0")
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, BARE), False)
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, Titles("PAY-{id} - {summary}", "{summary}")), True)
self.assertIs(release_standing.release_reviewed("v0.2.0", "main", repo, Titles("{summary}", "PAY-{id} - {summary}")), True, "a squash merge titles the commit as the pull request")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), Titles("PAY-{id} - {summary}", "{summary}")).cut.reviewed, True)
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, BARE), frozenset())
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, Titles("PAY-{id} - {summary}", "{summary}")), frozenset({(0, 3, 0)}))
self.assertEqual(release_standing.reviewed_releases("v0.2.0", "main", repo, Titles("{summary}", "PAY-{id} - {summary}")), frozenset({(0, 3, 0)}), "a squash merge titles the commit as the pull request")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), Titles("PAY-{id} - {summary}", "{summary}")).cut.reviews, frozenset({(0, 3, 0)}))
paths = {setting: pathlib.Path(repo, setting) for setting in SETTINGS} | {"plan": pathlib.Path(repo, "todo.md"), "changelog": pathlib.Path(repo, "CHANGELOG.md")}
config = ProjectConfig("acme", pathlib.Path(repo, "folder"), pathlib.Path(repo), paths)
self.assertIs(release_standing.project_plan(config, "main", repo).cut.reviewed, False)
self.assertIs(release_standing.project_plan(dataclasses.replace(config, commit_title="PAY-{id} - {summary}"), "main", repo).cut.reviewed, True)
self.assertIs(release_standing.project_plan(dataclasses.replace(config, pull_request_title="PAY-{id} - {summary}"), "main", repo).cut.reviewed, True)
self.assertEqual(release_standing.project_plan(config, "main", repo).cut.reviews, frozenset())
self.assertEqual(release_standing.project_plan(dataclasses.replace(config, commit_title="PAY-{id} - {summary}"), "main", repo).cut.reviews, frozenset({(0, 3, 0)}))
self.assertEqual(release_standing.project_plan(dataclasses.replace(config, pull_request_title="PAY-{id} - {summary}"), "main", repo).cut.reviews, frozenset({(0, 3, 0)}))
def test_counts_no_release_review_of_the_patch_release_cut_beside_main_as_a_review_of_the_next(self):
repo = tempfile.mkdtemp()
@@ -250,9 +257,29 @@ class ChunkItem(unittest.TestCase):
run("switch", "-q", "main")
run("merge", "-q", "--strategy", "ours", "--no-ff", "-m", "Merge release 0.15.2 into main", "v0.15.2")
# v0.15.2..main holds the review, which reviewed 0.15.2 itself, so 0.16.0 still waits for its own.
self.assertIs(release_standing.release_reviewed("v0.15.2", "main", repo, BARE), False)
self.assertEqual(release_standing.reviewed_releases("v0.15.2", "main", repo, BARE), frozenset())
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.16.0")
self.assertIs(release_standing.release_reviewed("v0.15.2", "main", repo, BARE), True)
self.assertEqual(release_standing.reviewed_releases("v0.15.2", "main", repo, BARE), frozenset({(0, 16, 0)}))
def test_counts_a_release_review_only_where_it_names_the_next_release(self):
repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
run("init", "-q", "-b", "main")
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.16.0"))
run("add", "todo.md")
run("commit", "-q", "-m", "Cut release 0.15.1")
run("tag", "v0.15.1")
pathlib.Path(repo, "todo.md").write_text(HEADER)
run("commit", "-q", "-a", "-m", "Ship item 1")
pick = lambda: release_standing.chunk_item([], release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut)
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)))
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.15.1")
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)), "a review opened before todo.md renamed the release names the cut one")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.17.0")
self.assertEqual(pick(), release_standing.ReviewDue((0, 16, 0)), "a review of 0.17.0 reviews none of 0.16.0")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.16.0")
self.assertEqual(pick(), release_standing.ReadyToCut((0, 16, 0)))
def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_no_tag(self):
repo = tempfile.mkdtemp()
@@ -263,13 +290,13 @@ class ChunkItem(unittest.TestCase):
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n")
run("add", "CHANGELOG.md")
run("commit", "-q", "-m", "Cut 0.0.1")
self.assertIs(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, False, "that review reviewed 0.0.1, which is cut")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset(), "that review reviewed 0.0.1, which is cut")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.commits, 0, "no commit follows the one that cut 0.0.1")
self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut), release_standing.Unplanned(None))
run("commit", "-q", "--allow-empty", "-m", "Ship item 2")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.commits, 1)
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0")
self.assertIs(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviewed, True)
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.reviews, frozenset({(0, 1, 0)}))
def test_counts_from_the_commit_on_the_named_branch_that_first_added_the_dated_heading_to_changelog_md(self):
repo = tempfile.mkdtemp()
@@ -319,16 +346,41 @@ class ChunkItem(unittest.TestCase):
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.2.0"))
run("add", "todo.md")
run("commit", "-q", "-m", "Plan")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], frozenset()))
run("tag", "v0.1.0")
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.2.0 - 2026-10-03\n")
run("add", "CHANGELOG.md")
run("commit", "-q", "-m", "Date 0.2.0")
held = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE)
self.assertEqual(held.plan, plan_of(HEADER + ROW.format(id=1, release="0.2.0")))
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], frozenset()))
self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0))))
def test_reads_the_plan_as_the_last_tag_holds_it_and_as_each_later_commit_left_it(self):
repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
run("init", "-q", "-b", "main")
before, tagged, after = (HEADER + ROW.format(id=1, release=release) for release in ("0.1.0", "0.2.0", "0.3.0"))
for text, title in ((before, "Plan 0.1.0"), (tagged, "Plan 0.2.0")):
pathlib.Path(repo, "todo.md").write_text(text)
run("add", "todo.md")
run("commit", "-q", "-m", title)
run("tag", "v0.1.0")
pathlib.Path(repo, "todo.md").write_text(after)
run("commit", "-q", "-am", "Plan 0.3.0")
self.assertEqual(release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE).cut.todos_since, [tagged, after])
def test_gives_gits_own_failure_as_the_reviews_where_the_tags_cannot_be_read(self):
repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
run("init", "-q", "-b", "main")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
no_tags = lambda *args, cwd: Failure("git tag failed: no tags") if "tag" in args else release_standing.git(*args, cwd=cwd)
cut = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE, no_tags).cut
self.assertEqual((cut.tag, cut.reviews), (Failure("git tag failed: no tags"), Failure("git tag failed: no tags")))
def test_reads_a_plan_and_a_changelog_outside_the_checkout_as_they_stand(self):
repo, folder = tempfile.mkdtemp(), pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", repo, str(folder)])
@@ -339,13 +391,13 @@ class ChunkItem(unittest.TestCase):
run("commit", "-q", "-m", "A todo.md the project's owners keep")
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
self.assertIsInstance(held.plan, NoItemsTable, "neither file exists yet")
self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], False))
self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], frozenset()))
plan = HEADER + ROW.format(id=2, release="0.2.0")
(folder / "todo.md").write_text(plan)
(folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0 - 2026-10-03\n")
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
self.assertEqual(held.plan, plan_of(plan))
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [], False), "no commit holds an earlier plan")
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [], frozenset()), "no commit holds an earlier plan")
(folder / "todo.md").write_bytes(b"\xff")
unreadable = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), changelog_of(repo), BARE)
self.assertEqual((unreadable.plan, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), []))
@@ -363,7 +415,7 @@ class ChunkItem(unittest.TestCase):
# Only this git knows where the checkout is, so a read that goes round it fails.
there = lambda *args, cwd: release_standing.git(*args, cwd=repo)
held = release_standing.default_plan("/nowhere", "main", plan_in("/nowhere"), changelog_of("/nowhere"), BARE, there)
self.assertEqual(held, release_standing.DefaultPlan(plan_of(plan), release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 0, [plan], False)))
self.assertEqual(held, release_standing.DefaultPlan(plan_of(plan), release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 0, [plan], frozenset())))
def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
+51 -8
View File
@@ -31,6 +31,36 @@ def package_imports(bin_folder: pathlib.Path) -> dict[str, set[str]]:
return imported
def imported_names(module: pathlib.Path) -> list[str]:
"""The dotted name of each thing the file module imports, as `a.b.c` for `from a.b import c`. A deferred import inside a function counts."""
found: list[str] = []
for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):
found += [alias.name for alias in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{alias.name}" for alias in node.names] if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module else []
return found
def part_imports(package: pathlib.Path) -> dict[str, set[str]]:
"""Each part of the package, with the other parts of it that its modules import, tests aside. A part is a module at the package's top, or a folder there with every module under it: a folder states that its modules belong together, so the top may not lean on a folder that leans on the top."""
imported: dict[str, set[str]] = {}
for module in package.rglob("*.py"):
if module.name.startswith("test_"):
continue
part = module.relative_to(package).parts[0].removesuffix(".py")
inside = [name.split(".")[1] for name in imported_names(module) if name.startswith(f"{package.name}.")]
imported.setdefault(part, set()).update(other for other in inside if other != part)
return imported
def part_cycles(bin_folder: pathlib.Path) -> dict[str, list[str]]:
"""Each package under bin_folder whose parts import in a cycle, with the parts along one."""
found = {}
for package in sorted(init.parent for init in bin_folder.glob("*/__init__.py")):
imported = part_imports(package)
if cycle(imported):
found[package.name] = cycle(imported)
return found
# The entry points that drive chunks. What two of them need lives in bin/chunk_driver/, so no other package imports one, its tests included.
DRIVERS = ("do_epic", "loop_claude")
@@ -62,18 +92,16 @@ def imports_of_test_modules(bin_folder: pathlib.Path) -> list[str]:
found = []
for module in sorted(bin_folder.rglob("*.py")):
package = module.relative_to(bin_folder).parts[0]
for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{alias.name}" for alias in node.names] if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module else []
for name in names:
top, *below = name.split(".")
tests = [part for part in below if part.startswith("test_")]
if tests and top != package:
found.append(f"{module.relative_to(bin_folder)} imports {name[:name.index(tests[0]) + len(tests[0])]}")
for name in imported_names(module):
top, *below = name.split(".")
tests = [part for part in below if part.startswith("test_")]
if tests and top != package:
found.append(f"{module.relative_to(bin_folder)} imports {name[:name.index(tests[0]) + len(tests[0])]}")
return sorted(set(found))
def cycle(imported: dict[str, set[str]]) -> list[str]:
"""One cycle among the packages, as the packages along it; empty where there is none."""
"""One cycle among the packages or parts that imported names, as those along it; empty where there is none."""
try:
graphlib.TopologicalSorter(imported).prepare()
except graphlib.CycleError as found:
@@ -135,6 +163,21 @@ class PackageCycles(unittest.TestCase):
})
self.assertEqual(package_imports(folder), {"a": {"b"}, "b": {"a"}, "c": set()})
def test_no_part_of_a_package_imports_one_that_imports_it_back(self):
self.assertEqual(part_cycles(ROOT / "bin"), {}, "move what both parts need into a module at the package's top that imports neither")
def test_reads_a_folder_of_a_package_as_one_part_and_a_module_at_its_top_as_another(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
tree(folder, {
"a/__init__.py": "", "a/main.py": "from a.kind.plant import x\nfrom a import shared\nimport b.kind\n",
"a/shared.py": "def f():\n\tfrom a.kind import plant\n",
"a/kind/__init__.py": "", "a/kind/plant.py": "import a.shared\nfrom a.kind.deep import other\n", "a/kind/deep/other.py": "import a.kind.plant\n",
"a/test_shared.py": "import a.main\n", "a/kind/test_plant.py": "import a.main\n",
})
self.assertEqual(part_imports(folder / "a"), {"__init__": set(), "main": {"kind", "shared"}, "shared": {"kind"}, "kind": {"shared"}})
self.assertEqual(sorted(cycle(part_imports(folder / "a"))[:2]), ["kind", "shared"])
def test_a_cycle_through_a_deferred_import_is_found(self):
self.assertEqual(sorted(cycle({"a": {"b"}, "b": {"a"}})[:2]), ["a", "b"])
self.assertEqual(cycle({"a": {"b"}, "b": set()}), [])
View File
@@ -7,7 +7,7 @@ import re
from failure import Failure
from mutate_changes import in_diff_tools
from mutate_changes.changed_lines import is_test
from task_bench.planted_mutant import Mutant
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
+104
View File
@@ -0,0 +1,104 @@
"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the two sources in its JSON log, and the message
PHPUnit prints when a test fails on one."""
import json
import pathlib
import re
from mutate_changes.tool_process import failed, remove, Run
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.bugs.planted_mutant import Mutant
from task_bench.bugs.scratch_copy import scratch_copy
# Where Infection writes its JSON log, from the copy's top.
LOG = "infection-log.json"
# The heading of PHPUnit's list of the tests that failed, or of those that threw: `There were 3 failures:`.
LISTED = re.compile(r"^There (?:was|were) \d+ (?:error|failure)s?:$")
# The heading of another list PHPUnit prints in the same form: `There was 1 risky test:`, `1 test triggered 1 deprecation:`.
OTHER_LIST = re.compile(r"^(?:There (?:was|were) \d+ |\d+ tests? triggered \d+ ).+:$")
# A listed test, by its number in the list: `1) Probe\Tests\PickTest::testNamesOne`, or with ` with data set #0 (1, 'one')` after it.
TEST = re.compile(r"^\d+\) (\S+)")
# What ends a listed test's message: the file and line that failed, as `/w/tests/PickTest.php:12`, the line between the two
# lists, or the summary's heading.
AFTER_MESSAGE = re.compile(r"^(?:\S.*\.php:\d+|--|ERRORS!|FAILURES!)$")
TEST_FILE = re.compile(r"Test\.php\b")
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as Infection finds them in a copy of that tree.
Infection runs at the copy's top, with the Infection config there. It ends without an error whatever score that config
asks for, since the files' score is not the project's."""
copied = scratch_copy(top)
if isinstance(copied, Failure):
return copied
scratch, copy = copied
try:
ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", "--min-msi=0", "--min-covered-msi=0", f"--logger-json={LOG}"], copy)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else failed("Infection", ran)
killed = [logged["mutator"] for logged in json.loads(pathlib.Path(copy, LOG).read_bytes())["killed"]]
return [mutant for mutator in killed if (mutant := planted(mutator, files))]
except (OSError, ValueError, KeyError, TypeError, AttributeError) as failure:
return Failure(f"could not read Infection's log, {LOG} in {copy}: {failure}")
finally:
remove(scratch)
def planted(mutator: dict, files: list[str]) -> Mutant | None:
"""A mutant of Infection's log as the lines it changes, or None where it is in none of `files` or doesn't change any line.
The log names a file by its whole path where Infection ran. That path ends with the file's path from the top, and where it
ends with more than one of `files`, the longest is the file."""
logged = mutator["originalFilePath"]
path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None)
if path is None:
return None
found = changed(mutator["originalSourceCode"], mutator["mutatedSourceCode"])
return Mutant(path, found[0], f"{path}:{mutator['originalStartLine']} {mutator['mutatorName']}", found[1], found[2]) if found else None
def changed(original: str, mutated: str) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes, from the file's source and the mutant's, both of which Infection 0.35.12 logs: the number of
the first line that differs, from 1, the file's lines from there to the last that differs, and what the mutant has in their
place. An unchanged line between two changed ones is in both. None where the two sources are the same."""
was, now = original.split("\n"), mutated.split("\n")
if was == now:
return None
shorter = min(len(was), len(now))
first = next((index for index in range(shorter) if was[index] != now[index]), shorter)
after = next((count for count in range(shorter - first) if was[-1 - count] != now[-1 - count]), shorter - first)
return first + 1, tuple(line.encode() for line in was[first:len(was) - after]), tuple(line.encode() for line in now[first:len(now) - after])
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the message of the first test that has a message in PHPUnit's list of the tests that
threw or failed, without the test's name, class or file, so it says what goes wrong and not which test shows it. A test in
another of PHPUnit's lists, such as the risky tests, did not fail.
None where PHPUnit lists no such test, as on a passing run, a file that fails to parse or a run with --testdox, or where each
message only names its test."""
messages: list[tuple[str, list[str]]] = []
listing = within = False
for line in output.splitlines():
if LISTED.match(line):
listing, within = True, False
elif OTHER_LIST.match(line):
listing = within = False
elif listing and (test := TEST.match(line)):
messages.append((test[1], []))
within = True
elif AFTER_MESSAGE.match(line):
within = False
elif within:
messages[-1][1].append(line)
kept = (kept_lines(test, message) for test, message in messages)
return next(("\n".join(lines) for lines in kept if lines), None)
def kept_lines(test: str, message: list[str]) -> list[str]:
"""A message's lines, without the empty ones and those that name the test: the whole of `Probe\\Tests\\PickTest::testNamesOne`,
its class with or without the namespace, its method, or a test's file."""
of_class, _, method = test.partition("::")
names = {test, of_class, of_class.rpartition("\\")[2], method} - {""}
return [text for text in message if text and not TEST_FILE.search(text) and not any(name in text for name in names)]
@@ -6,9 +6,9 @@ import re
import typing
from failure import Failure
from task_bench import go_bugs, python_bugs, rust_bugs
from mutate_changes.changed_lines import is_test
from task_bench.planted_mutant import Mutant
from task_bench.bugs import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs
from mutate_changes.changed_lines import is_test, STRYKER
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# A place as `larv-review places` prints it: `<path>:<line>` in backticks.
@@ -28,8 +28,11 @@ class Language(typing.NamedTuple):
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text),
Language("PHP", (".php",), php_bugs.killed_mutants, php_bugs.task_text),
Language("Python", (".py",), python_bugs.killed_mutants, python_bugs.task_text),
Language("Rust", (".rs",), rust_bugs.killed_mutants, rust_bugs.task_text),
# Stryker mutates JavaScript as it does TypeScript, and `node --test` reports both alike.
Language("TypeScript", STRYKER, typescript_bugs.killed_mutants, typescript_bugs.task_text),
)
@@ -2,7 +2,7 @@
import re
import typing
from task_bench.figures import Side
from task_bench.tasks import Side
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
@@ -11,7 +11,8 @@ class Mutant(typing.NamedTuple):
"""A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1,
those lines as the tree has them, and what the mutant has in their place. Where it only adds lines, the number is that of the
line they go in before. name is what the report calls the bug it becomes: the path and line, then what the tool tells the
mutant by, which is Gremlins' column and mutator, or mutmut's name. cargo-mutants' own name for a mutant holds all of it."""
mutant by, which is Gremlins' or Stryker's column and mutator, Infection's mutator, or mutmut's name. cargo-mutants' own name for a mutant
holds all of it."""
path: str
line: int
@@ -4,7 +4,7 @@ import re
from failure import Failure
from mutate_changes.mutmut_tool import killed_by_mutmut
from task_bench.planted_mutant import Mutant
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# pytest's report of the failed tests, in its default form or with --tb=short: under this heading, a section per test.
@@ -5,7 +5,7 @@ import re
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import remove, Run, scratch_folder
# What cargo-mutants 27.1.0 writes after the code it put in, as in `sum -= /* ~ changed by cargo-mutants ~ */ item;`. A planted
+24
View File
@@ -0,0 +1,24 @@
"""A copy of a tree for a mutation tool to run in, so that what the tool writes there goes with the copy."""
import os
import shutil
from failure import Failure
from mutate_changes.tool_process import remove, scratch_folder
def scratch_copy(top: str) -> tuple[str, str] | Failure:
"""A new scratch folder in top, and in it a copy of top's other entries, links kept as links: the two folders' paths. The
caller removes the scratch folder.
A mutation tool leaves files where it runs: its cache, and each log the project's config asks for, which tells where every
mutant is. A bug's tree is a copy of top, so the tool runs in this copy and top stays as it was."""
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
copy = os.path.join(scratch, "copy")
try:
shutil.copytree(top, copy, symlinks=True, ignore=shutil.ignore_patterns(os.path.basename(scratch)))
except OSError as failure:
remove(scratch)
return Failure(f"could not copy {top} into {scratch}: {failure}")
return scratch, copy
@@ -5,12 +5,12 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.go_bugs import go_files, killed_mutants, reapplied, task_text
from task_bench.bugs.go_bugs import go_files, killed_mutants, reapplied, task_text
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Ran
# go test's report of an assertion that failed in a subtest, then of one whose message runs over two lines.
+275
View File
@@ -0,0 +1,275 @@
"""task-bench's PHP planter: which files Infection mutates, how its log's mutants become lines and what PHPUnit's output tells Haiku.
The four mutants of PICK and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13. Each
logged mutant is cut down to the keys the planter reads. The other mutants and outputs are made up in the same form."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.bugs.php_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.bugs.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = """<?php
namespace Probe;
final class Pick
{
/** @param list<int> $items */
public static function sum(array $items, int $floor): int
{
$sum = 0;
foreach ($items as $item) {
if ($item >= $floor) {
$sum += $item;
}
}
return $sum;
}
public static function label(int $count): string
{
return $count === 1
? 'one item'
: $count . ' items';
}
}
"""
LINES = PICK.split("\n")
def with_lines(first: int, count: int, *now: str) -> str:
"""PICK with `count` lines from line `first` on replaced by `now`: the mutated source Infection logged for such a mutant."""
return "\n".join([*LINES[:first - 1], *now, *LINES[first - 1 + count:]])
OPERATOR = with_lines(12, 1, "\t\t\tif ($item > $floor) {")
# Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were.
FOREACH = with_lines(11, 5, "\t\tforeach ([] as $item) {", " if ($item >= $floor) {", "\t\t\t\t$sum += $item;", "\t\t\t}", " }")
TERNARY = with_lines(21, 3, "\t\treturn $count === 1 ? $count . ' items' : 'one item';")
VISIBILITY = with_lines(19, 1, "\tprotected static function label(int $count): string")
OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",)
def logged(mutator: str, line: int, mutated_source: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict:
return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "mutatedSourceCode": mutated_source, "originalFilePath": path, "originalStartLine": line}}
FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.13
Configuration: /w/phpunit.xml
FFF 3 / 3 (100%)
Time: 00:00.002, Memory: 18.00 MB
There were 3 failures:
1) Probe\\Tests\\PickTest::testAddsTheItemsAtOrAboveTheFloor
Failed asserting that 3 is identical to 5.
/w/tests/PickTest.php:12
2) Probe\\Tests\\PickTest::testNamesOne
one is singular
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
-'one item'
+''
/w/tests/PickTest.php:17
3) Probe\\Tests\\PickTest::testNamesMany
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 'text' => '3 items'
+ 'text' => '3'
)
/w/tests/PickTest.php:22
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
"""
PASSING = "PHPUnit 12.5.45 by Sebastian Bergmann and contributors.\n\n... 3 / 3 (100%)\n\nOK (3 tests, 3 assertions)\n"
def failing(test: str, *lines: str) -> str:
return "\n".join(["F 1 / 1 (100%)", "", "There was 1 failure:", "", f"1) {test}", *lines, "", "FAILURES!", "Tests: 1, Assertions: 1, Failures: 1.", ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_an_operator_mutant_changes(self):
self.assertEqual(changed(PICK, OPERATOR), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW))
def test_is_every_line_from_the_first_changed_one_to_the_last(self):
was = tuple(line.encode() for line in LINES[10:15])
now = (b"\t\tforeach ([] as $item) {", b" if ($item >= $floor) {", b"\t\t\t\t$sum += $item;", b"\t\t\t}", b" }")
self.assertEqual(changed(PICK, FOREACH), (11, was, now))
def test_a_mutant_may_have_fewer_lines_than_it_replaces(self):
was = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';")
self.assertEqual(changed(PICK, TERNARY), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)))
def test_a_mutant_may_only_remove_a_line_or_only_add_one(self):
self.assertEqual(changed("a\nb\nc", "a\nc"), (2, (b"b",), ()))
self.assertEqual(changed("a\nc", "a\nb\nc"), (2, (), (b"b",)))
def test_a_line_counts_as_unchanged_before_the_change_or_after_it_never_both(self):
self.assertEqual(changed("a\nb\nb", "a\nb"), (3, (b"b",), ()))
self.assertEqual(changed("b\nb\nc", "b\nc"), (2, (b"b",), ()))
def test_reaches_the_first_line_and_the_last(self):
self.assertEqual(changed("a\nb", "c\nb"), (1, (b"a",), (b"c",)))
self.assertEqual(changed("a\nb", "a\nc"), (2, (b"b",), (b"c",)))
def test_is_none_where_the_mutant_changes_no_line(self):
self.assertIsNone(changed(PICK, PICK))
def test_what_it_returns_plants_as_the_mutant(self):
for source in (OPERATOR, FOREACH, TERNARY, VISIBILITY):
line, was, now = changed(PICK, source)
self.assertEqual(mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)), source.encode())
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/Pick.php").write_text(PICK, encoding="utf-8")
self.ran: list[tuple[list[str], str, str]] = []
def infection(self, log: dict | str | None, code: int = 0):
"""A run that writes Infection's log where its --logger-json names, or none where log is None, and another log beside it."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, pathlib.Path(cwd, "src/Pick.php").read_text(encoding="utf-8")))
pathlib.Path(cwd, "infection.html").write_text("every mutant", encoding="utf-8")
if log is not None:
path = next(argument.partition("=")[2] for argument in argv if argument.startswith("--logger-json="))
pathlib.Path(cwd, path).write_text(log if isinstance(log, str) else json.dumps(log), encoding="utf-8")
return Ran(code, "the tool's last words\n")
return run
def test_runs_infection_over_the_files_in_a_copy_of_the_tree_with_a_json_log_and_no_score_to_reach(self):
killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3)
(argv, cwd, source), = self.ran
self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$")
self.assertEqual(source, PICK)
self.assertEqual(argv, ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress", "--min-msi=0", "--min-covered-msi=0", "--logger-json=infection-log.json"])
def test_is_each_killed_mutant_as_the_lines_it_changes(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR), logged("Ternary", 21, TERNARY)], "escaped": [logged("PublicVisibility", 19, VISIBILITY)]}
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1)
ternary = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';")
self.assertEqual(found, [
Mutant("src/Pick.php", 12, "src/Pick.php:12 GreaterThanOrEqualTo", (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW),
Mutant("src/Pick.php", 21, "src/Pick.php:21 Ternary", ternary, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)),
])
def test_names_a_mutant_by_the_line_infection_logs_for_it(self):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": [logged("Foreach_", 11, FOREACH), logged("Ternary", 20, TERNARY)]}), 1)
self.assertEqual([(mutant.line, mutant.name) for mutant in found], [(11, "src/Pick.php:11 Foreach_"), (21, "src/Pick.php:20 Ternary")])
def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]}
found = killed_mutants(str(self.top), ["src/Pick.php", "lib/src/Pick.php", "Pick.php"], self.infection(log), 1)
self.assertEqual([mutant.path for mutant in found], ["src/Pick.php", "src/Pick.php", "lib/src/Pick.php"])
def test_leaves_out_a_mutant_that_changes_no_line(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, PICK)]}
self.assertEqual(killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1), [])
def test_leaves_the_tree_as_it_was_whatever_infection_wrote(self):
for code in (0, 1):
killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code), 1)
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/Pick.php"])
def test_fails_where_infection_exits_nonzero(self):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code=1), 1)
self.assertEqual(found, Failure("Infection exited 1:\nthe tool's last words"))
def test_passes_on_a_run_that_could_not_start(self):
failure = Failure("vendor/bin/infection could not start: No such file or directory")
self.assertIs(killed_mutants(str(self.top), ["src/Pick.php"], lambda argv, cwd: failure, 1), failure)
def test_fails_where_infection_wrote_no_log_or_one_it_cannot_read(self):
unreadable = (None, "not json", "{}", '{"killed": [{}]}', '{"killed": [7]}', json.dumps({"killed": [{"mutator": {**logged("Ternary", 21, TERNARY)["mutator"], "mutatedSourceCode": 7}}]}))
for log in unreadable:
with self.subTest(log=log):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1)
self.assertIsInstance(found, Failure)
self.assertIn("could not read Infection's log, infection-log.json in ", found.reason)
def test_fails_where_the_tree_cannot_be_copied(self):
found = killed_mutants(str(self.top / "missing"), ["src/Pick.php"], self.infection({"killed": []}), 1)
self.assertIsInstance(found, Failure)
self.assertEqual(self.ran, [])
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_or_file(self):
self.assertEqual(task_text(FAILING), "Failed asserting that 3 is identical to 5.")
def test_is_every_line_of_a_message_up_to_the_file_and_line_that_failed(self):
second = FAILING[FAILING.index("2) "):]
expected = "one is singular\nFailed asserting that two strings are identical.\n--- Expected\n+++ Actual\n@@ @@\n-'one item'\n+''"
self.assertEqual(task_text("There was 1 failure:\n\n" + second), expected)
def test_is_none_on_a_passing_run_or_output_that_lists_no_failure(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("PHP Parse error: syntax error, unexpected token \"}\" in /w/src/Pick.php on line 12\n"))
self.assertIsNone(task_text("1) a line that only looks like a listed test\nits message\n"))
self.assertIsNone(task_text(""))
def test_reads_an_error_as_it_reads_a_failure(self):
output = "E\n\nThere was 1 error:\n\n1) Probe\\Tests\\PickTest::testNamesOne\nTypeError: label(): Argument #1 ($count) must be of type int, string given\n\n/w/src/Pick.php:19\n/w/tests/PickTest.php:17\n\nERRORS!\n"
self.assertEqual(task_text(output), "TypeError: label(): Argument #1 ($count) must be of type int, string given")
def test_leaves_out_each_line_that_names_the_test_its_class_or_its_file(self):
lines = ("testNamesOne went wrong", "PickTest saw it", "see tests/LabelTest.php", "got 3, want 5", "", "/w/tests/PickTest.php:17")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", *lines)), "got 3, want 5")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne with data set #0 (1, 'one')", *lines)), "got 3, want 5")
def test_reads_a_listed_test_that_names_no_class(self):
self.assertEqual(task_text(failing("testNamesOne", "got 3, want 5")), "got 3, want 5")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", "testNamesOne failed", "", "/w/tests/PickTest.php:17")))
def test_reads_no_test_of_another_list_as_a_failed_one(self):
named = failing("Probe\\Tests\\PickTest::testSum", "PickTest failed", "", "/w/tests/PickTest.php:9").partition("FAILURES!")[0]
for heading in ("There was 1 risky test:", "There were 2 risky tests:", "1 test triggered 1 deprecation:", "2 tests triggered 3 PHPUnit warnings:"):
with self.subTest(heading=heading):
output = "\n".join([named, "--", "", heading, "", "1) Probe\\Tests\\LastTest::testLabels", "This test did not perform any assertions", "", "/w/tests/LastTest.php:20", "", "FAILURES!"])
self.assertIsNone(task_text(output))
def test_reads_the_failures_listed_after_another_list(self):
output = "\n".join(["There was 1 risky test:", "", "1) LastTest::testLabels", "This test did not perform any assertions", "", "--", "", "There was 1 failure:", "", "1) PickTest::testSum", "Failed asserting that 3 is identical to 5.", "", "/w/tests/PickTest.php:9", "", "FAILURES!"])
self.assertEqual(task_text(output), "Failed asserting that 3 is identical to 5.")
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "There were 2 failures:\n\n1) PickTest::testAdds\ntestAdds\n\n/w/tests/PickTest.php:12\n\n2) PickTest::testLabels\nno label\n\n/w/tests/PickTest.php:17\n\nFAILURES!\n"
self.assertEqual(task_text(output), "no label")
def test_a_message_without_a_file_and_line_ends_at_the_next_test_or_the_summary(self):
self.assertEqual(task_text("There were 2 failures:\n\n1) PickTest::testAdds\ngot 3\n\n2) PickTest::testLabels\nno label\n"), "got 3")
self.assertEqual(task_text(failing("PickTest::testAdds", "got 3")), "got 3")
self.assertEqual(task_text("There was 1 error:\n\n1) PickTest::testAdds\ngot 3\n\n--\n\nThere was 1 failure:\n\n1) PickTest::testLabels\nno label\n"), "got 3")
if __name__ == "__main__":
unittest.main()
@@ -3,11 +3,11 @@ import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
from task_bench.bugs.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
from failure import Failure
from task_bench.planted_mutant import Mutant
from task_bench.bugs.planted_mutant import Mutant
PLACES = """## 2026-11-19T22:33:15Z, PR #646 at a357cc7b
@@ -85,9 +85,11 @@ class LanguagesTest(unittest.TestCase):
class ShippedLanguagesTest(unittest.TestCase):
def test_each_language_reads_its_own_test_runners_output(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",)), ("Rust", (".rs",))])
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("PHP", (".php",)), ("Python", (".py",)), ("Rust", (".rs",)), ("TypeScript", (".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"))])
self.assertEqual(task_text("calc.go", "--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
self.assertEqual(task_text("calc.py", "==== FAILURES ====\n___ test_pick ___\nE assert 3 == 4\n"), "assert 3 == 4")
self.assertEqual(task_text("Calc.php", "There was 1 failure:\n\n1) CalcTest::testPicks\ngot 3, want 4\n\n/w/tests/CalcTest.php:9\n"), "got 3, want 4")
self.assertEqual(task_text("calc.ts", "✖ failing tests:\n\ntest at calc.test.ts:5:1\n✖ picks (1.2ms)\n Error: got 3, want 4\n at pick (file:///w/calc.ts:9:5)\n"), "Error: got 3, want 4")
self.assertEqual(task_text("calc.rs", "---- picks stdout ----\nthread 'picks' (7) panicked at src/calc.rs:9:5:\ngot 3, want 4\n"), "got 3, want 4")
@@ -3,9 +3,9 @@ import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
from task_bench.bugs.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
class MutatedTest(unittest.TestCase):
@@ -4,11 +4,11 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.python_bugs import killed_mutants, task_text
from task_bench.planted_mutant import Mutant, mutated
from task_bench.bugs.python_bugs import killed_mutants, task_text
from task_bench.bugs.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
CALC = "def double(n):\n\treturn n * 2\n\n\ndef triple(n):\n\treturn (\n\t\tn * 3\n\t)\n"
@@ -8,11 +8,11 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.rust_bugs import changed, killed_mutants, task_text
from task_bench.bugs.rust_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.planted_mutant import Mutant, mutated
from task_bench.bugs.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = b"""pub fn first(items: &[i32]) -> Option<i32> {
+49
View File
@@ -0,0 +1,49 @@
"""The copy of a tree that a mutation tool runs in."""
import os
import pathlib
import socket
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.bugs.scratch_copy import scratch_copy
class ScratchCopyTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/pick.ts").write_text("code", encoding="utf-8")
(self.top / ".hidden").write_text("kept", encoding="utf-8")
def test_copies_every_entry_of_the_tree_into_a_scratch_folder_in_it(self):
scratch, copy = scratch_copy(str(self.top))
self.assertRegex(scratch, rf"^{self.top}/\.mutate-changes-[^/]+$")
self.assertEqual(copy, f"{scratch}/copy")
self.assertEqual(sorted(str(path.relative_to(copy)) for path in pathlib.Path(copy).rglob("*")), [".hidden", "src", "src/pick.ts"])
self.assertEqual(pathlib.Path(copy, "src/pick.ts").read_text(encoding="utf-8"), "code")
def test_keeps_a_link_as_a_link(self):
(self.top / "linked").symlink_to("src/missing.ts")
_, copy = scratch_copy(str(self.top))
self.assertEqual(os.readlink(os.path.join(copy, "linked")), "src/missing.ts")
def test_fails_without_a_scratch_folder_left_where_the_tree_cannot_be_copied(self):
# A socket is an entry that no copy can read.
held = socket.socket(socket.AF_UNIX)
self.addCleanup(held.close)
held.bind(str(self.top / "held"))
found = scratch_copy(str(self.top))
self.assertIsInstance(found, Failure)
self.assertRegex(found.reason, rf"^could not copy {self.top} into {self.top}/\.mutate-changes-[^/]+: ")
self.assertEqual(sorted(path.name for path in self.top.iterdir()), [".hidden", "held", "src"])
def test_passes_on_that_no_scratch_folder_could_be_made(self):
found = scratch_copy(str(self.top / "missing"))
self.assertIsInstance(found, Failure)
self.assertIn("could not make a scratch folder in ", found.reason)
+273
View File
@@ -0,0 +1,273 @@
"""task-bench's TypeScript planter: which files Stryker mutates, how its report's mutants become lines and what `node --test`'s
output tells Haiku.
PICK's mutants and FAILING are what Stryker 10.1.1 and Node.js 24.19.0 wrote for a small project, each mutant cut down to the keys
the planter reads. The other mutants and outputs are made up in the same form."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.bugs.typescript_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.bugs.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = """export function pick(items: number[], floor: number): number {
let sum = 0;
for (const item of items) {
if (item >= floor) {
sum += item;
}
}
return sum;
}
export const tag = (n: number): string => "é😀" + (n > 1 ? "s" : "");
""".encode()
LINES = PICK.split(b"\n")
def reported(mutator: str, replacement: str, start: tuple[int, int], end: tuple[int, int], status: str = "Killed") -> dict:
return {"mutatorName": mutator, "replacement": replacement, "status": status, "location": {"start": {"line": start[0], "column": start[1]}, "end": {"line": end[0], "column": end[1]}}}
OPERATOR = reported("EqualityOperator", "item > floor", (4, 7), (4, 20))
BLOCK = reported("BlockStatement", "{}", (4, 22), (6, 4))
# Stryker counts a column in UTF-16 code units: the string before this condition holds one character of two units.
AFTER_WIDE_TEXT = reported("ConditionalExpression", "true", (11, 52), (11, 57))
# Three failed tests, the last two in a suite.
FAILING = """
> test
> node --test "src/**/*.test.ts"
✖ adds the items at or above the floor (1.654962ms)
▶ label
✖ names one (0.432991ms)
✖ names many (1.398742ms)
✖ label (2.262912ms)
ℹ tests 3
ℹ suites 1
ℹ pass 0
ℹ fail 3
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 164.424758
✖ failing tests:
test at src/pick.test.ts:5:1
✖ adds the items at or above the floor (1.654962ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
3 !== 5
at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)
at Test.runInAsyncScope (node:async_hooks:227:14)
at startSubtestAfterBootstrap (node:internal/test_runner/harness:387:17) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 3,
expected: 5,
operator: 'strictEqual',
diff: 'simple'
}
test at src/pick.test.ts:10:2
✖ names one (0.432991ms)
AssertionError [ERR_ASSERTION]: one is singular
'' !== 'one item'
at TestContext.<anonymous> (file:///w/src/pick.test.ts:11:10)
at Array.map (<anonymous>) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: '',
expected: 'one item',
operator: 'strictEqual',
diff: 'simple'
}
test at src/pick.test.ts:13:2
✖ names many (1.398742ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
+ text: ''
- text: '3 items'
}
at TestContext.<anonymous> (file:///w/src/pick.test.ts:14:10) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [Object],
expected: [Object],
operator: 'deepStrictEqual',
diff: 'simple'
}
"""
PASSING = "✔ adds the items at or above the floor (1.3494ms)\nℹ tests 1\nℹ pass 1\nℹ fail 0\n"
def failing(test: str, *lines: str) -> str:
return "\n".join([f"✖ {test} (1.2ms)", "ℹ fail 1", "", "✖ failing tests:", "", "test at src/pick.test.ts:5:1", f"✖ {test} (1.2ms)", *lines, ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_with_the_replacement_between_the_mutants_columns(self):
self.assertEqual(changed(OPERATOR["location"], "item > floor", LINES), (4, (b"\t\tif (item >= floor) {",), (b"\t\tif (item > floor) {",)))
def test_is_every_line_a_mutant_spans(self):
was = (b"\t\tif (item >= floor) {", b"\t\t\tsum += item;", b"\t\t}")
self.assertEqual(changed(BLOCK["location"], "{}", LINES), (4, was, (b"\t\tif (item >= floor) {}",)))
def test_a_replacement_of_more_lines_is_as_many_lines(self):
self.assertEqual(changed(OPERATOR["location"], "item >\n\t\t\tfloor", LINES), (4, (LINES[3],), (b"\t\tif (item >", b"\t\t\tfloor) {")))
def test_reaches_the_files_first_column_and_its_last_line(self):
self.assertEqual(changed(reported("M", "", (1, 1), (1, 8))["location"], "", LINES[:2]), (1, (LINES[0],), (LINES[0][7:],)))
self.assertEqual(changed(reported("M", "0", (2, 12), (2, 13))["location"], "0", LINES[:2]), (2, (LINES[1],), (LINES[1],)))
def test_a_mutant_that_replaces_no_code_adds_its_own(self):
self.assertEqual(changed(reported("M", "!", (4, 7), (4, 7))["location"], "!", LINES), (4, (LINES[3],), (b"\t\tif (!item >= floor) {",)))
def test_counts_a_column_in_utf_16_code_units(self):
now = 'export const tag = (n: number): string => "é😀" + (true ? "s" : "");'.encode()
self.assertEqual(changed(AFTER_WIDE_TEXT["location"], "true", LINES), (11, (LINES[10],), (now,)))
def test_is_none_where_the_file_holds_no_such_line_or_column(self):
for start, end in (((0, 1), (1, 2)), ((12, 1), (13, 1)), ((4, 7), (99, 1)), ((4, 40), (4, 41)), ((4, 0), (4, 3)), ((4, 9), (4, 7)), ((5, 1), (4, 3))):
with self.subTest(start=start, end=end):
self.assertIsNone(changed(reported("M", "x", start, end)["location"], "x", LINES))
def test_what_it_returns_plants_as_the_mutant(self):
line, was, now = changed(BLOCK["location"], "{}", LINES)
planted = mutated(PICK, Mutant("src/pick.ts", line, "a name", was, now))
self.assertEqual(planted, PICK.replace(b" {\n\t\t\tsum += item;\n\t\t}", b" {}"))
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/pick.ts").write_bytes(PICK)
self.ran: list[tuple[list[str], str, bytes]] = []
def stryker(self, files: dict[str, list[dict]] | None, code: int = 0, text: str | None = None):
"""A run that writes Stryker's report of these files' mutants where it runs, or none where files is None, and Stryker's
incremental file beside it."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, pathlib.Path(cwd, "src/pick.ts").read_bytes()))
report = pathlib.Path(cwd, "reports/mutation/mutation.json")
report.parent.mkdir(parents=True, exist_ok=True)
pathlib.Path(cwd, "reports/stryker-incremental.json").write_text("every mutant", encoding="utf-8")
if files is not None:
report.write_text(text if text is not None else json.dumps({"files": {path: {"source": PICK.decode(), "mutants": mutants} for path, mutants in files.items()}}), encoding="utf-8")
return Ran(code, "the tool's last words\n")
return run
def test_runs_stryker_over_the_files_in_a_copy_of_the_tree_with_its_json_reporter(self):
killed_mutants(str(self.top), ["src/pick.ts", "src/last.ts"], self.stryker({}), 3)
(argv, cwd, source), = self.ran
self.assertEqual(argv, ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"])
self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$")
self.assertEqual(source, PICK)
def test_names_a_file_whose_path_holds_a_globs_characters_by_a_glob_that_matches_it(self):
killed_mutants(str(self.top), ["app/[slug]/page.tsx", "src/pick.ts"], self.stryker({}), 1)
self.assertEqual(self.ran[0][0][6], "app/?slug?/page.tsx,src/pick.ts")
def test_is_each_killed_mutant_as_the_lines_it_changes(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR, BLOCK]}), 1)
self.assertEqual(found, [
Mutant("src/pick.ts", 4, "src/pick.ts:4:7 EqualityOperator", (LINES[3],), (b"\t\tif (item > floor) {",)),
Mutant("src/pick.ts", 4, "src/pick.ts:4:22 BlockStatement", tuple(LINES[3:6]), (b"\t\tif (item >= floor) {}",)),
])
def test_leaves_out_a_mutant_no_test_killed(self):
others = [reported("EqualityOperator", "item < floor", (4, 7), (4, 20), status) for status in ("Survived", "NoCoverage", "Timeout", "CompileError", "RuntimeError", "Ignored")]
self.assertEqual(killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": others}), 1), [])
def test_leaves_out_a_mutant_in_another_file_or_at_a_place_the_file_does_not_hold(self):
files = {"src/other.ts": [OPERATOR], "src/pick.ts": [reported("EqualityOperator", "x", (40, 1), (40, 2)), OPERATOR]}
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files), 1)
self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"])
def test_leaves_the_tree_as_it_was_whatever_stryker_wrote(self):
for files in ({"src/pick.ts": [OPERATOR]}, None):
killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, code=1), 1)
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/pick.ts"])
def test_reads_the_report_of_a_run_that_finished_under_the_score_its_config_asks_for(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}, code=1), 1)
self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"])
def test_fails_where_stryker_exits_nonzero_without_a_report(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1)
self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words"))
def test_reads_no_report_that_the_tree_held_before_the_run(self):
(self.top / "reports/mutation").mkdir(parents=True)
(self.top / "reports/mutation/mutation.json").write_text(json.dumps({"files": {"src/pick.ts": {"source": PICK.decode(), "mutants": [OPERATOR]}}}), encoding="utf-8")
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1)
self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words"))
def test_passes_on_a_run_that_could_not_start(self):
failure = Failure("npx could not start: No such file or directory")
self.assertIs(killed_mutants(str(self.top), ["src/pick.ts"], lambda argv, cwd: failure, 1), failure)
def test_fails_where_stryker_wrote_no_report_or_one_it_cannot_read(self):
for files, text in ((None, None), ({}, "not json"), ({}, '{"files": {"src/pick.ts": {"source": ""}}}'), ({}, '{"files": {"src/pick.ts": {"source": "", "mutants": [{"status": "Killed"}]}}}')):
with self.subTest(text=text):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, text=text), 1)
self.assertIsInstance(found, Failure)
self.assertIn("could not read Stryker's report, reports/mutation/mutation.json in ", found.reason)
def test_fails_where_the_tree_cannot_be_copied(self):
found = killed_mutants(str(self.top / "missing"), ["src/pick.ts"], self.stryker({}), 1)
self.assertIsInstance(found, Failure)
self.assertEqual(self.ran, [])
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_error_without_the_tests_name_file_or_stack(self):
self.assertEqual(task_text(FAILING), "AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n3 !== 5")
def test_is_none_on_a_passing_run_or_output_that_lists_no_failing_test(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("SyntaxError: Unexpected token\n at node:internal/modules/esm/loader:1:1\n"))
self.assertIsNone(task_text(""))
def test_leaves_out_each_line_that_names_the_test_or_its_file(self):
output = failing("adds the items", " Error: adds the items failed", " got 3 in src/pick.test.ts", " want 5", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")
self.assertEqual(task_text(output), "want 5")
def test_is_none_where_the_error_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(failing("adds the items", " Error: adds the items failed", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")))
def test_takes_the_first_failed_test_that_has_an_error(self):
first = failing("adds", " Error: adds", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")
second = "\n".join(["test at src/pick.test.ts:9:1", "✖ labels (0.4ms)", " Error: no label", " at label (file:///w/src/pick.ts:12:9)", ""])
self.assertEqual(task_text(first + "\n" + second), "Error: no label")
def test_an_error_without_a_stack_ends_at_its_test(self):
output = failing("adds", " 'a string was thrown'") + "\ntest at src/pick.test.ts:9:1\n✖ labels (0.4ms)\n Error: no label\n"
self.assertEqual(task_text(output), "'a string was thrown'")
def test_an_error_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n Error: got 3\n want 5"), "Error: got 3\nwant 5")
def test_a_line_before_the_list_of_failing_tests_is_no_error(self):
self.assertIsNone(task_text("✖ adds (1ms)\n Error: printed by the test itself\nℹ fail 1\n\n✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n"))
if __name__ == "__main__":
unittest.main()
+113
View File
@@ -0,0 +1,113 @@
"""The bugs task-bench plants in TypeScript and JavaScript: Stryker's killed mutants, re-applied from its JSON report, and the error
`node --test` prints when a test fails on one."""
import json
import pathlib
import re
from mutate_changes.tool_process import failed, remove, Run
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.bugs.planted_mutant import Mutant
from task_bench.bugs.scratch_copy import scratch_copy
# Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another
# path, so the planter reads this one.
REPORT = "reports/mutation/mutation.json"
# The heading of the list of failed tests that `node --test`'s spec reporter prints. Each test in it has its error.
FAILING_TESTS = "✖ failing tests:"
# Where a listed test stands, the line before its name: `test at src/pick.test.ts:5:1`.
TEST_PLACE = re.compile(r"^test at \S+:\d+:\d+$")
# A listed test's name and how long it ran: `✖ adds the items (1.654962ms)`.
TEST = re.compile(r"^✖ (.+) \(\d+(?:\.\d+)?ms\)$")
# A line of the error's stack, which follows its message: ` at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)`.
STACK = re.compile(r"^\s+at ")
TEST_FILE = re.compile(r"\.(?:spec|test)\.[cm]?[jt]sx?\b")
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as Stryker finds them in a copy of that tree. One at a place
its file doesn't hold is left out.
Stryker runs at the copy's top, with the Stryker config and the package.json there."""
copied = scratch_copy(top)
if isinstance(copied, Failure):
return copied
scratch, copy = copied
try:
mutate = ",".join(in_diff_tools.glob_escaped(path) for path in files)
report = pathlib.Path(copy, REPORT)
# A report the project tracks would otherwise stand for this run's.
report.unlink(missing_ok=True)
ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy)
# Stryker exits 1 too where it finished under the score the project's config sets as `thresholds.break`, which the files'
# score may be. Only a run that finished writes the report.
if isinstance(ran, Failure) or ran.code and not report.is_file():
return ran if isinstance(ran, Failure) else failed("Stryker", ran)
reported = json.loads(report.read_bytes())["files"]
return [mutant for path in files if path in reported for mutant in file_mutants(path, reported[path])]
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read Stryker's report, {REPORT} in {copy}: {failure}")
finally:
remove(scratch)
def file_mutants(path: str, reported: dict) -> list[Mutant]:
"""The killed mutants of the file at path, from what Stryker's report holds of it: the source Stryker read, and each mutant."""
lines = reported["source"].encode().split(b"\n")
killed = [mutant for mutant in reported["mutants"] if mutant["status"] == "Killed"]
found = [(mutant, changed(mutant["location"], mutant["replacement"], lines)) for mutant in killed]
return [Mutant(path, lines_changed[0], f"{path}:{mutant['location']['start']['line']}:{mutant['location']['start']['column']} {mutant['mutatorName']}", lines_changed[1], lines_changed[2]) for mutant, lines_changed in found if lines_changed]
def changed(location: dict, replacement: str, lines: list[bytes]) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes; `lines` are its file's. Stryker's report gives the code the mutant puts in, and where the code it
replaces starts and ends: each a line and a column, both from 1, the end's column the first one after that code. Returned are
the number of the first line, those lines as the file has them, and what the mutant has in their place. None where the file
holds no such lines or columns."""
start, end = location["start"], location["end"]
if not 1 <= start["line"] <= end["line"] <= len(lines) or (start["line"], start["column"]) > (end["line"], end["column"]):
return None
before, after = cut(lines[start["line"] - 1], start["column"]), cut(lines[end["line"] - 1], end["column"])
if before is None or after is None:
return None
now = before[0] + replacement.encode() + after[1]
return start["line"], tuple(lines[start["line"] - 1:end["line"]]), tuple(now.split(b"\n"))
def cut(line: bytes, column: int) -> tuple[bytes, bytes] | None:
"""A line's bytes before a column and from it on. Stryker counts a column in UTF-16 code units, as JavaScript counts a string's
length, so a character outside the Basic Multilingual Plane is two columns. None where the line holds no such column, or is not
UTF-8."""
try:
units = line.decode().encode("utf-16-le")
at = 2 * (column - 1)
if not 0 <= at <= len(units):
return None
return units[:at].decode("utf-16-le").encode(), units[at:].decode("utf-16-le").encode()
except UnicodeError:
return None
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the error of the first test that has an error in `node --test`'s list of failing
tests, without the test's name or file and without the stack, so it says what goes wrong and not which test shows it.
None where the output lists no failing test with an error, as on a passing run, a file that fails to load or a reporter other
than spec, or where each error only names its test."""
listed = f"\n{output}".partition(f"\n{FAILING_TESTS}\n")[2]
errors: list[tuple[str, list[str]]] = []
within = False
for line in listed.splitlines():
if test := TEST.match(line):
errors.append((test[1], []))
within = True
elif TEST_PLACE.match(line) or STACK.match(line):
within = False
elif within:
errors[-1][1].append(line.strip())
kept = (kept_lines(test, error) for test, error in errors)
return next(("\n".join(lines) for lines in kept if lines), None)
def kept_lines(test: str, error: list[str]) -> list[str]:
return [text for text in error if text and test not in text and not TEST_FILE.search(text)]
View File
@@ -3,21 +3,20 @@ that builds it, and acceptance tests Haiku never sees. A feature counts at the t
at both before it is built, and pass at both with the reference patch.
A data source Haiku adds is such a folder too, with a `generate-register` beside the three parts: the script that writes the
register Haiku imports, as task_bench.registers runs it. It counts as a feature does, in trees that hold its register."""
register Haiku imports, as task_bench.features.registers runs it. It counts as a feature does, in trees that hold its register."""
import itertools
import os
import pathlib
import shutil
import typing
from task_bench.tasks import Bench, check_made, committed, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Task
from task_bench.tasks import Bench, check_made, committed, DATA_SOURCE, FEATURE, Kind, on_disk, Planned, Side, SIDES, Task
from project_config.settings import BENCH_TASKS, CONFIG
from failure import Failure
from task_bench.registers import GENERATE, NotGenerated, registered_trees
from task_bench.features.registers import GENERATE, NotGenerated, registered_trees
from project_config.main import located
from mutate_changes.tool_process import Ran
from task_bench.runs import ran_tests, TimedOut
from task_bench.figures import Side, SIDES
SPEC = "spec.md"
PATCH = "reference.patch"
@@ -5,10 +5,9 @@ import os
import pathlib
import shutil
from task_bench.tasks import Bench, committed, on_disk
from task_bench.tasks import Bench, committed, on_disk, Side, SIDES
from task_bench.runs import Containers, entries, in_tree, NotStarted, run_in_image, TimedOut
from failure import Failure
from task_bench.figures import Side, SIDES
# A panel of three readers, seated as the README's audience, picked the name on 2026-11-23: each had it first or second, over
# `register`, which reads as a data file, and `generate-source`, which two read as generating source code.
@@ -1,6 +1,6 @@
"""The features task-bench has Haiku rebuild: those the project shipped, read from its history. A shipped feature is a chunk on
the base's first-parent line that took an item out of the plan, as branch_chunks cuts that line. Once its change is out of each
side's tree, it is a feature as task_bench.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
side's tree, it is a feature as task_bench.features.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
is checked."""
import functools
import os
@@ -9,8 +9,8 @@ import re
import shutil
import typing
from task_bench.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
from task_bench.tasks import Bench, committed, on_disk, Planned, Task
from task_bench.features.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
from task_bench.tasks import Bench, committed, on_disk, Planned, Side, SIDES, Task
from branch_chunks.read import cut_with_shipped, unsupported
from failure import Failure
from git_cli.git_repo import Git
@@ -18,7 +18,6 @@ from plan.todo_table import Item, tagline_text
from project_config.main import located
from task_bench.runs import of_tests
from project_config.settings import RECORDS
from task_bench.figures import Side, SIDES
# Why a feature that landed by fast-forward is passed over: no earlier chunk says where its commits start, or its branch merged
# the default branch into itself, so its commits hold what other features built.
@@ -12,13 +12,13 @@ import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.tasks import Asked, Bench, FEATURE
from task_bench.test_task_bench import BASE_CODE, DOCKER, HEAD_CODE, InTurn, TESTS
from task_bench.runs import Containers, TimedOut
from failure import Failure
from task_bench.feature_tasks import Feature, features, why_passed_over
from task_bench.features.feature_tasks import Feature, features, why_passed_over
from test_env import isolated_env
from task_bench import main
from mutate_changes.tool_process import Ran
@@ -121,7 +121,7 @@ class BenchOfTasksCase(unittest.TestCase):
def bench(self, **given: str):
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home)
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home, "task-bench-0123456789ab", "1234:5678")
class FeatureBenchTest(BenchOfTasksCase):
@@ -8,14 +8,14 @@ import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.test_feature_tasks import added, BenchOfTasksCase, feature
from task_bench.features.test_feature_tasks import added, BenchOfTasksCase, feature
from task_bench.tasks import Asked, Bench, DATA_SOURCE
from task_bench.runs import Containers, TimedOut
from failure import Failure
from task_bench.feature_tasks import features
from task_bench.registers import generated, NotGenerated, registered_trees
from task_bench.features.feature_tasks import features
from task_bench.features.registers import generated, NotGenerated, registered_trees
from task_bench import main
from mutate_changes.tool_process import Ran
@@ -10,14 +10,14 @@ import subprocess
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
from task_bench.features.test_feature_tasks import ACCEPTANCE, BenchOfTasksCase
from task_bench.test_task_bench import BASE_CODE, HEAD_CODE
from failure import Failure
from git_cli.git_repo import git
from task_bench import main
from task_bench.shipped_features import MERGED_IN, read_shipped
from task_bench.features.shipped_features import MERGED_IN, read_shipped
from branch_chunks.read import READ_AT
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
View File
@@ -8,7 +8,7 @@ import typing
from claude_code.entries import AssistantTurn, Entry, Text, tool_calls, ToolCall, ToolResult, ToolResults
from task_bench.runs import HOME, WORK
from reading_cost.measure import reads_of
from task_bench.figures import Side
from task_bench.tasks import Side
# A trace keeps the first TEXT_LINES lines of the model's text between two calls, and the first TEXT_WIDTH characters of each.
TEXT_LINES = 3
@@ -5,7 +5,7 @@ import typing
from review_rules.comprehension_history import appended
from task_bench.tasks import BUG, KINDS
from task_bench.gather import DIGEST
from task_bench.figures.gather import DIGEST
from failure import Failure
from git_cli.git_repo import Git
from record_store.held import Held
@@ -13,12 +13,12 @@ from larv_review.history_commands import held_history
from record_store.stores import RecordStore
from text_files.utc_stamp import utc
# The digest's line that names the commits, as task_bench.digest.digest writes it.
# The digest's line that names the commits, as task_bench.figures.digest.digest writes it.
SIDES = re.compile(r"^Base ([0-9a-f]{7,40}), head ([0-9a-f]{7,40})\.", re.M)
# How the table's three rows over every task open, as task_bench.figures.table writes them: the base, the head and the head's change.
# How the table's three rows over every task open, as task_bench.figures.run_figures.table writes them: the base, the head and the head's change.
OVER_ALL = "| All |"
COMMIT_LENGTH = 8
# What a bench's name says its tasks are, by how its table's header opens, as task_bench.figures.table writes it. A bench of
# What a bench's name says its tasks are, by how its table's header opens, as task_bench.figures.run_figures.table writes it. A bench of
# bugs has the bare name.
TASKS_NAMED = {f"| {kind.noun.capitalize()} |": f" {tasks}" for tasks, kind in KINDS.items() if kind is not BUG}
@@ -7,13 +7,11 @@ from claude_code.entries import Entry, entry_from, tool_calls, ToolCall
from failure import Failure
from task_bench.runs import HOME, WORK
from reading_cost.measure import reads_of
from task_bench.tasks import Side, SIDES
from claude_code.tokens import Tokens, tokens_of
# The tools that read or search without a shell. A Bash call counts where `reads_of` finds a file it reads.
READING_TOOLS = frozenset({"Glob", "Grep", "Read"})
# A bench's two sides: the commit before the change and the one after it.
Side = typing.Literal["base", "head"]
SIDES: tuple[Side, Side] = ("base", "head")
@dataclasses.dataclass(frozen=True)
@@ -4,9 +4,9 @@ import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.digest import decoys, digest, Run, TaskRuns, trace
from task_bench.figures.digest import decoys, digest, Run, TaskRuns, trace
from claude_code.entries import entries_of, Entry
@@ -9,10 +9,10 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.gather import gather, PROMPT
from task_bench.figures.gather import gather, PROMPT
from test_env import isolated_env
from task_bench import main
@@ -6,9 +6,9 @@ import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.record_figures import bench_appended, bench_entry, recorded_bench
from task_bench.figures.record_figures import bench_appended, bench_entry, recorded_bench
from review_rules.comprehension_history import entries
from failure import Failure
from record_store.held import Held
@@ -4,11 +4,11 @@ import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench import figures as bench_figures
from task_bench.figures import run_figures as bench_figures
from failure import Failure
from task_bench.figures import Figures, Result, table
from task_bench.figures.run_figures import Figures, Result, table
from claude_code.entries import json_objects
from claude_code.tokens import Tokens
+197 -97
View File
@@ -14,14 +14,20 @@ origin's as last fetched, else main or master. Where --base names the head's own
No model judges anything: the bench runs programs, and reads Haiku's own stream.
- Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places`
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over
the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. No other language is planted
in so far. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where,
planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message
from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must
run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short, and
`cargo test` without --nocapture. Any other mutant is passed over, so a change to the very lines of a bug is not benched.
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, Infection over the
PHP files, as `vendor/bin/infection`, mutmut 3 over the Python files, as `mutmut run`, cargo-mutants over the Rust files, as
`cargo mutants`, and Stryker over the TypeScript and JavaScript files, as `npx --no --package=@stryker-mutator/core stryker
run`, which runs the Stryker the project installs and downloads none. No other language is planted in so far. Infection and
Stryker each run at the top of a copy of that tree, with the project's config for the tool there, and the copy is removed
with all the tool wrote. Stryker's json reporter must write where it does by default, `reports/mutation/mutation.json`.
The bench takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of them, 5 by default, have
become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where, planted at each side,
a test fails and prints a message that says more than the test's name. The bench reads that message from `go test`'s output
for a Go file, from PHPUnit's for a PHP file, from pytest's for a Python file, from `cargo test`'s for a Rust file and from
`node --test`'s for a TypeScript or JavaScript file. So --test must run the tests of each language the places name, with
that runner: PHPUnit as it prints by default, pytest as it prints by default or with --tb=short, `cargo test` without
--nocapture, and `node --test --test-reporter=spec`. Any other mutant is passed over, so a change to the very lines of a
bug is not benched.
- Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's
tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p
--strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every
@@ -29,7 +35,10 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
Claude home is new and empty, so the project's own CLAUDE.md, or AGENTS.md, in the copy is all the setup that loads. Its network
reaches api.anthropic.com and nothing else. A fix ends after 30 minutes.
- Check. The test command runs over the planted tree with each file that is no test as Haiku left it; a fix passes where it exits 0.
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. In a Rust file, each
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. The bench
tells a test by its path: a folder named `test`, `tests` or `__tests__`, or a file named `test_*.py`, `*_test.py`,
`*_test.go`, `*.test.*` or `*.spec.*`. A test of any other name counts as code, such as `src/PickTest.php` or
`src/pick-test.js`, so Haiku's change to it stands. In a Rust file, each
inline `#[cfg(test)]` module stands as the planted file has it, and the rest is as Haiku left it. Where the planted file has such
modules and Haiku's file lacks one of them, or its modules cannot be told apart, the planted file stands whole; where the planted
file has none, or its modules cannot be told apart, Haiku's stands. A Rust mutant whose file's modules cannot be told apart, as where two share a name or a brace, string or comment
@@ -40,10 +49,13 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at
the copy's top, with no network, so the image must hold what the tests would otherwise download.
--prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` with
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and
cargo-mutants run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; $PWD is the folder
the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut` or the `cargo` on the host's PATH. For example,
for Go, for Python and then for Rust:
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and cargo-mutants
run in the copy of the base, Infection and Stryker in a copy of that copy, and mutmut in a copy of the folder there that holds
its settings; $PWD is the folder the tool runs in. That folder holds the files git tracks and no others, so for Infection and
Stryker the prefix first installs the project's dependencies there, as `composer install` and `npm ci` do. Infection also
needs PHP with a coverage driver, pcov or Xdebug. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo`
or the `npx` on the host's PATH, or the tree's own `vendor/bin/infection`, which only a project that tracks `vendor` has.
For example, for Go, for Python, for Rust and then for TypeScript:
docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
sh -c 'shift; exec go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@"' sh
@@ -53,8 +65,12 @@ for Go, for Python and then for Rust:
docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e CARGO_HOME=/tmp/cargo -v "$PWD:$PWD" -w "$PWD" \
rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh
docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD:$PWD" -w "$PWD" \
node:24.19.0-alpine3.24 sh -c 'npm ci --silent && exec "$@"' sh
Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and
cargo-mutants' last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `mutmut` or `cargo`, as here for Go
Stryker's last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`,
`vendor/bin/infection`, `mutmut`, `cargo` or `npx`, as here for Go
and Python:
sh -c 'case "$1" in
@@ -143,7 +159,7 @@ features the heading reads `task-bench features of <branch>: ...` instead, for o
of <branch>: ...`, and for one of shipped features `task-bench shipped-features of <branch>: ...`. No tool reads the entry as a ruling or a scoring run. The bench's last line says where the entry went. A bench that fails or stops doesn't record anything.
`task-bench gather`, run in the same checkout, turns the digest into plan items. It starts a claude on the project's rung, the
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in gather-prompt.md beside this file.
cheapest rung of the model loop-claude runs the project on, with the digest and the prompt in bin/task_bench/figures/gather-prompt.md.
That claude files an item with `todo-item add` for each place the runs show to be hard, and leaves the plan's file uncommitted.
gather prints that claude's answer and removes the bench's folder. Where claude fails, the folder stays, for another try.
@@ -152,7 +168,7 @@ not, unless a bench or a gather is using it. So gather a bench before the next o
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is none of bugs, features, data-sources and shipped-features, or no token; and where git, docker or a mutation tool
fails, the seats' places don't name any Go, Python or Rust file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
fails, the seats' places don't name any file in a language the bench plants bugs in, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts.
@@ -180,26 +196,26 @@ import time
import typing
import uuid
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, SHIPPED, Task, tests_in_copy
from task_bench.planted_mutant import bug_at_sides, Mutant
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, DATA_SOURCE, FEATURE, Kind, KINDS, on_disk, Planned, SHIPPED, Side, SIDES, Task, tests_in_copy
from task_bench.bugs.planted_mutant import bug_at_sides, Mutant
from claude_code.reply import Claude
from task_bench.bench_folder import clear_left, held
from task_bench.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK
from task_bench.digest import counted, digest, Run, TaskRuns
from task_bench.figures.digest import counted, digest, Run, TaskRuns
from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, Git, top
from task_bench.gather import DIGEST, gather, run_claude
from task_bench.plant import drawn, killed_mutants, place_files, task_text
from claude_code.entries import entry_from, json_objects
from task_bench.figures.gather import DIGEST, gather, run_claude
from task_bench.bugs.plant import drawn, killed_mutants, place_files, task_text
from claude_code.entries import Entry, entry_from, json_objects
from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure
from task_bench.feature_tasks import feature_tasks, Features, read_features
from task_bench.figures import figures, Result, Side, SIDES, table
from task_bench.features.feature_tasks import feature_tasks, Features, read_features
from task_bench.figures.run_figures import Figures, figures, Result, table
from git_cli import git_repo
from review_rules.review_folder import made_review_folder, REPORTS
from larv_review.history_commands import read_places
from task_bench.shipped_features import read_shipped, shipped_tasks, ShippedFeatures
from task_bench.record_figures import recorded_bench
from task_bench.features.shipped_features import read_shipped, shipped_tasks
from task_bench.figures.record_figures import recorded_bench
from run_heavy.capped_docker import SHARE_VARIABLE
from task_bench.rust_test_modules import tells_apart
@@ -218,15 +234,43 @@ KEPT = "The digest, and each run's result and stream, until `task-bench gather`
ONLY_FOR = {"--seed": BUG, "--bugs": BUG, "--prefix": BUG, "--shipped": SHIPPED}
# What plans a bench's tasks, once the bench has opened its containers.
Planner = typing.Callable[[Bench], Planned | Failure]
# What makes a kind's planner from each side's tree, once the trees stand.
Planning = typing.Callable[[dict[Side, str]], Planner | Failure]
# What reads a kind's tasks once the bench knows its checkout and its sides' commits, with git to read them by.
Source = typing.Callable[[str, dict[Side, str], Git], Planning | Failure]
class Fixes(typing.NamedTuple):
"""The runs that finished, in the order they ran, and the failure that stopped the bench before the rest, if one did."""
results: list[Result]
stopped: Failure | None
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude) -> int:
class Call(typing.NamedTuple):
"""What a bench was called with: its options, the environment its tools run in, what reads what `larv-review places` prints,
and the home folder."""
given: dict[str, str]
env: typing.Mapping[str, str]
read: typing.Callable[[pathlib.Path], str | Failure]
home: pathlib.Path
def new_name() -> str:
"""A name no other bench's containers have."""
return f"task-bench-{uuid.uuid4().hex[:12]}"
def host_user() -> str:
"""The user and group this process runs as, as docker's --user takes them."""
return f"{os.getuid()}:{os.getgid()}"
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int:
"""Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers."""
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers. `name` names a bench's containers,
and `user` is the user they run as."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
@@ -238,7 +282,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
report = bench(given, env, read, home)
report = bench(given, env, read, home, name(), user())
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
@@ -247,6 +291,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""The options argv gives, with each default filled in; a Failure where argv cannot be read, or asks what no bench does."""
given = parsed(argv)
return given if isinstance(given, Failure) else checked(given, env)
def parsed(argv: list[str]) -> dict[str, str] | Failure:
"""Each option argv names, with its value, given as `--name value` or `--name=value`."""
given: dict[str, str] = {}
rest = list(argv)
while rest:
@@ -263,23 +314,36 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] |
if not equals and not rest:
return Failure(f"{name} needs a value")
given[name] = value if equals else rest.pop(0)
return given
def checked(given: dict[str, str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""given with each default filled in, where it holds what a bench of its kind needs and env holds the token."""
for name in ("--image", "--test"):
if not given.get(name):
return Failure(f"{name} is missing")
if given.setdefault(TASKS, "bugs") not in KINDS:
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {given[TASKS]}")
kind = KINDS[given[TASKS]]
tasks = given.get(TASKS, "bugs")
if tasks not in KINDS:
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {tasks}")
kind = KINDS[tasks]
for name, only in ONLY_FOR.items():
if only is not kind and name in given:
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {given[TASKS]}")
for name, default in COUNTS.items():
if ONLY_FOR.get(name, kind) is not kind:
continue
if not given.setdefault(name, default).isdecimal() or int(given[name]) < 1:
return Failure(f"{name} takes a whole number from 1, not {given[name]}")
if not env.get(TOKEN):
return Failure(f"{TOKEN} holds no token")
return given
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {tasks}")
filled = {TASKS: tasks, **count_defaults(kind), **given}
return counts_failure(filled) or (filled if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
def count_defaults(kind: Kind) -> dict[str, str]:
"""The default of each count a bench of kind takes."""
return {name: default for name, default in COUNTS.items() if ONLY_FOR.get(name, kind) is kind}
def counts_failure(filled: dict[str, str]) -> Failure | None:
"""A Failure where a count filled holds is no whole number from 1."""
for name in COUNTS:
if name in filled and (not filled[name].isdecimal() or int(filled[name]) < 1):
return Failure(f"{name} takes a whole number from 1, not {filled[name]}")
return None
def progress(line: str) -> None:
@@ -287,16 +351,14 @@ def progress(line: str) -> None:
print(line, file=sys.stderr)
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. It tells
its progress on stderr."""
# Only bugs are planted at the seats' places; features and data sources come from the project's folder, and shipped features from its history. Each kind reads what it makes its tasks from before anything is copied or built,
# so a fault there stops the bench at once.
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. Its
containers are named name and run as user. It tells its progress on stderr."""
kind = KINDS[given[TASKS]]
# Shipped features are read from the base's history, once the base is known.
tasks_from: str | Features | ShippedFeatures | Failure | None = None if kind is SHIPPED else read(home) if kind is BUG else read_features(home, kind)
if isinstance(tasks_from, Failure):
return tasks_from
# Each kind reads what it makes its tasks from before anything is copied or built, so a fault there stops the bench at once.
source = SOURCES[kind](Call(given, env, read, home), kind)
if isinstance(source, Failure):
return source
git = functools.partial(git_repo.git, env=env)
checkout = top(git)
if isinstance(checkout, Failure):
@@ -304,10 +366,9 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
sides = commits(given, checkout, git)
if isinstance(sides, Failure):
return sides
if tasks_from is None:
tasks_from = read_shipped(home, checkout, sides["base"], git)
if isinstance(tasks_from, Failure):
return tasks_from
planning = source(checkout, sides, git)
if isinstance(planning, Failure):
return planning
progress(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.")
review = made_review_folder(checkout, home)
if isinstance(review, Failure):
@@ -316,15 +377,14 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
if isinstance(folder, Failure):
return folder
clear_left(home / REPORTS)
run = functools.partial(bench_in, folder, given, env, tasks_from, checkout, sides, git)
containers = Containers(docker_cli(env), name, given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), user)
run = functools.partial(bench_in, folder, given["--image"], containers, Asked(kind, int(given["--runs"])), planning, checkout, sides, git)
return recorded_bench(run, folder, git, home, time.time) if RECORD in given else run()
def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], tasks_from: str | Features | ShippedFeatures, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, which empties folder and keeps its runs there. Where tasks_from is what
`larv-review places` prints, the bench plants bugs at the places it names. Where tasks_from holds features, data sources or
shipped features, the bench has Haiku build, add or rebuild them."""
containers = Containers(docker_cli(env), f"task-bench-{uuid.uuid4().hex[:12]}", given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), f"{os.getuid()}:{os.getgid()}")
def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: Asked, planning: Planning, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, in containers of image, which empties folder and keeps its runs there.
planning makes what plans the tasks of the kind asked."""
shutil.rmtree(folder, ignore_errors=True)
trees: dict[Side, str] = {}
for side, commit in sides.items():
@@ -332,23 +392,47 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st
if isinstance(tree, Failure):
return tree
trees[side] = tree
planned: typing.Callable[[Bench], Planned | Failure] | Failure
if isinstance(tasks_from, Features):
asked, planned = Asked(KINDS[given[TASKS]], int(given["--runs"])), features_planner(tasks_from, checkout, trees)
elif isinstance(tasks_from, ShippedFeatures):
asked, planned = Asked(SHIPPED, int(given["--runs"])), functools.partial(shipped_tasks, shipped=tasks_from, count=int(given["--shipped"]))
else:
asked, planned = Asked(BUG, int(given["--runs"])), bugs_planner(given, env, tasks_from, trees["base"])
planned = planning(trees)
if isinstance(planned, Failure):
return planned
try:
found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
found = opened(containers, image) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
finally:
closed(containers)
return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"]
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> typing.Callable[[Bench], Planned | Failure]:
def bugs_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the seats' places, the only places bugs are planted."""
places = call.read(call.home)
if isinstance(places, Failure):
return places
return lambda checkout, sides, git: functools.partial(bugs_planner, call.given, call.env, places)
def features_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the features, or the data sources where kind is DATA_SOURCE, from the project's folder."""
features = read_features(call.home, kind)
if isinstance(features, Failure):
return features
return lambda checkout, sides, git: functools.partial(features_planner, features, checkout)
def shipped_source(call: Call, kind: Kind) -> Source:
"""Shipped features are read from the base's history, so only once the base is known."""
def source(checkout: str, sides: dict[Side, str], git: Git) -> Planning | Failure:
shipped = read_shipped(call.home, checkout, sides["base"], git)
if isinstance(shipped, Failure):
return shipped
return lambda trees: functools.partial(shipped_tasks, shipped=shipped, count=int(call.given["--shipped"]))
return source
# What reads each kind's tasks. A kind without an entry stops the bench before it reads anything.
SOURCES: dict[Kind, typing.Callable[[Call, Kind], Source | Failure]] = {BUG: bugs_source, FEATURE: features_source, DATA_SOURCE: features_source, SHIPPED: shipped_source}
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> Planner:
"""What plans a bench of features in trees, each side's. It takes the features' folder, with its acceptance tests and
reference patches, out of trees first, so Haiku's copy leaves it out."""
if features.folder.is_relative_to(checkout):
@@ -358,12 +442,14 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
return functools.partial(feature_tasks, found=features.found, folder=features.folder)
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs: of the mutants the tests kill in the Go, Python and Rust files of the tree at base that hold a place
in places, those --seed draws first become bugs, until --bugs of them have."""
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, trees: dict[Side, str]) -> Planner | Failure:
"""What plans a bench of bugs. The bugs' files are those of the base's tree in trees that hold a place in places and are in a
language of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until
--bugs of them have."""
base = trees["base"]
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.")
return Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(base, files, run, CPUS_PER_SLOT)
return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"]))
@@ -400,7 +486,7 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str |
return removed if isinstance(removed, Failure) else str(into)
def benched(bench: Bench, planned: typing.Callable[[Bench], Planned | Failure]) -> list[str] | Failure:
def benched(bench: Bench, planned: Planner) -> list[str] | Failure:
"""Makes the tasks that planned plans, runs each, writes the results into the bench's folder and returns the report."""
if failure := baseline_failure(bench):
return failure
@@ -540,34 +626,48 @@ def fixed(task: Task, side: Side, number: int, containers: Containers, folder: p
stream = stream_of(Result(task.number, side, number, False, None), folder, kind.key)
copy, check = folder / "copy", folder / "check"
try:
try:
stream.parent.mkdir(exist_ok=True)
shutil.copytree(task.trees[side], copy, symlinks=True)
except OSError as failure:
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
if isinstance(attempted, Failure):
return attempted
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
entries = [entry_from(event) for event in events]
found = figures(events, task.file and os.path.join(WORK, task.file))
if isinstance(found, Failure):
return found
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found, tuple(entries))
worked = attempt(task, side, containers, copy, stream, kind)
if isinstance(worked, Failure):
return worked
passed = verdict(task, side, containers, copy, check, kind)
if isinstance(passed, Failure):
return passed
return Result(task.number, side, number, passed, *worked)
finally:
shutil.rmtree(copy, ignore_errors=True)
shutil.rmtree(check, ignore_errors=True)
def attempt(task: Task, side: Side, containers: Containers, copy: pathlib.Path, stream: pathlib.Path, kind: Kind) -> tuple[Figures | None, tuple[Entry, ...]] | Failure:
"""Haiku's work on task in copy, made a copy of the side's tree: the figures of its run, None where it didn't finish, and
the entries of its stream, which it writes to the file stream."""
try:
stream.parent.mkdir(exist_ok=True)
shutil.copytree(task.trees[side], copy, symlinks=True)
except OSError as failure:
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
if isinstance(attempted, Failure):
return attempted
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
found = figures(events, task.file and os.path.join(WORK, task.file))
return found if isinstance(found, Failure) else (found, tuple(entry_from(event) for event in events))
def verdict(task: Task, side: Side, containers: Containers, copy: pathlib.Path, check: pathlib.Path, kind: Kind) -> bool | Failure:
"""Whether the tests pass over check, made the side's tree with what Haiku changed in copy. Tests that run out of time don't."""
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return isinstance(ran, Ran) and ran.code == 0
def stream_of(result: Result, folder: pathlib.Path, key: str) -> pathlib.Path:
"""The file that holds the stream of the run result names, of a task whose kind has that key. Its name without the suffix is
the run's id in the digest."""
+3 -1
View File
@@ -9,8 +9,10 @@ from task_bench.runs import checked_tree, Containers, ran_tests
from failure import Failure
from git_cli.git_repo import Git
from mutate_changes.tool_process import Ran
from task_bench.figures import Side
# A bench's two sides: the commit before the change and the one after it.
Side = typing.Literal["base", "head"]
SIDES: tuple[Side, Side] = ("base", "head")
# The one commit of a task's tree doesn't name anyone, and neither a hook nor a signing key of the caller's reaches it.
COMMIT = ["-c", "user.name=task-bench", "-c", "user.email=task-bench@localhost", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null", "commit", "--quiet", "--message", "Import"]
+39 -9
View File
@@ -18,11 +18,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import api_proxy, bench_folder, main, runs
from test_env import assert_not_root, isolated_env
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut
from task_bench.plant import drawn
from task_bench.bugs.plant import drawn
from claude_code.entries import Entry, entry_from
from failure import Failure
from task_bench.figures import Figures, Result
from task_bench.planted_mutant import Mutant
from task_bench.figures.run_figures import Figures, Result
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Ran
from claude_code.tokens import Tokens
@@ -90,6 +90,8 @@ CLAUDE = textwrap.dedent("""\
usage = {"input_tokens": 40, "cache_creation_input_tokens": 9000, "cache_read_input_tokens": 52000, "output_tokens": 800}
print(json.dumps({"type": "result", "subtype": "success", "is_error": False, "num_turns": 3, "duration_ms": 61500, "usage": usage, "result": "Fixed."}))
""")
# The name of a bench's containers and the user they run as, where a test fixes them.
NAME, USER = "task-bench-0123456789ab", "1234:5678"
PLACES = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\nJunior A, hardest first:\n\n- `calc.go:3` `Add`: long\n- `gone.go:1` `Gone`: removed since\n- `README.md:1` `Calc`: thin\n"
@@ -131,7 +133,7 @@ class BenchTest(unittest.TestCase):
def bench(self, **given: str):
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home)
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home, NAME, USER)
def calls(self) -> list[list[str]]:
return [json.loads(line) for line in self.log.read_text().splitlines()]
@@ -223,6 +225,20 @@ class BenchTest(unittest.TestCase):
self.assertTrue((reports / "crashed/task-bench.lock").exists())
self.assertTrue((reports / "running/task-bench/trees/task-bench").exists())
def test_the_command_line_names_its_containers_afresh_and_runs_them_as_the_hosts_user(self):
self.assertRegex(main.new_name(), r"^task-bench-[0-9a-f]{12}$")
self.assertNotEqual(main.new_name(), main.new_name())
self.assertEqual(main.host_user(), f"{os.getuid()}:{os.getgid()}")
argv = [part for name, value in {**self.given, "--runs": "1"}.items() for part in (name, value)]
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(main.main(argv, self.env, lambda home: PLACES, name=lambda: "task-bench-other", user=lambda: "7:8"), 0)
calls = self.calls()
self.assertEqual(calls[1], ["network", "create", "--internal", "task-bench-other"])
self.assertIn(["--user", "7:8"], [call[at:at + 2] for call in calls if "claude" in call for at in range(len(call))])
def test_each_kind_of_task_has_what_reads_its_tasks(self):
self.assertEqual(set(main.SOURCES), set(main.KINDS.values()))
def test_the_command_line_runs_the_bench_on_the_seats_places_and_prints_its_report(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
homes = []
@@ -236,7 +252,7 @@ class BenchTest(unittest.TestCase):
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.\n")):
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.\n")):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors:
self.assertEqual(main.main(argv, self.env, lambda home: places), 1)
self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said))
@@ -282,11 +298,11 @@ class BenchTest(unittest.TestCase):
fixes = [call for call in calls if "claude" in call]
self.assertEqual(len(fixes), 2)
name = fixes[0][fixes[0].index("--network") + 1]
self.assertRegex(name, r"^task-bench-[0-9a-f]{12}$")
self.assertEqual(name, NAME)
image = fixes[0].index(f"{name}:throwaway")
self.assertEqual(fixes[0][image + 1:], ["claude", "-p", "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence", "--model", "claude-haiku-5-5", "--effort", "low", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions", "A test of this project fails with the message below. Find the bug in the code and fix it. Change no test.\n\nAdd(1, 2) = -1, want 3"])
options = fixes[0][:image]
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", f"{os.getuid()}:{os.getgid()}"], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", USER], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
self.assertIn(expected, [options[at:at + 2] for at in range(len(options))])
self.assertNotIn("sk-secret-token", self.log.read_text())
self.assertEqual(calls[0][:1] + calls[0][-3:], ["build", "--tag", f"{name}:throwaway", "-"])
@@ -308,8 +324,8 @@ class BenchTest(unittest.TestCase):
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
self.assertEqual(found, Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug."))
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home, NAME, USER)
self.assertEqual(found, Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):
@@ -441,6 +457,12 @@ class MainTest(unittest.TestCase):
self.assertEqual(self.run_main("--test", "go test ./...")[1].partition(";")[0], "--image is missing")
self.assertEqual(self.run_main("--image", "golang:1.27.4")[1].partition(";")[0], "--test is missing")
def test_fills_in_each_default_of_the_kind_and_leaves_what_it_was_given_as_it_was(self):
given = {"--image": "i", "--test": "t", "--runs": "7"}
filled = main.checked(given, {"CLAUDE_CODE_OAUTH_TOKEN": "t"})
self.assertEqual(given, {"--image": "i", "--test": "t", "--runs": "7"})
self.assertEqual(filled, {"--image": "i", "--test": "t", "--tasks": "bugs", "--runs": "7", "--bugs": "5", "--seed": "1"})
def test_refuses_a_count_that_is_no_whole_number_from_1(self):
for name, value in (("--bugs", "0"), ("--runs", "-1"), ("--seed", "x")):
self.assertEqual(self.run_main("--image", "i", "--test", "t", name, value)[1].partition(";")[0], f"{name} takes a whole number from 1, not {value}")
@@ -538,6 +560,14 @@ class RunOutcomesTest(unittest.TestCase):
task = dataclasses.replace(self.task, trees={"base": str(self.folder / "gone"), "head": str(self.tree)})
self.assertFailsWith(main.fixed(task, "base", 1, self.containers(), self.folder, main.BUG), "could not copy bug 1's tree at the base: ")
def test_a_stream_that_cannot_be_read_after_the_fix_fails_the_bench_naming_the_stream(self):
stream = self.folder / "runs" / "bug-1-base-1.jsonl"
def removing_the_stream(args, *, seconds, stdin=None, stdout=None, stderr=None):
stream.unlink(missing_ok=True)
return Ran(0, "")
containers = dataclasses.replace(self.containers(), docker=removing_the_stream)
self.assertFailsWith(main.fixed(self.task, "base", 1, containers, self.folder, main.BUG), f"could not read {stream}: ")
def test_failing_to_make_the_tree_that_checks_a_fix_fails_the_bench_naming_the_bug_and_side(self):
(self.folder / "check").mkdir()
self.assertFailsWith(main.fixed(self.task, "base", 1, self.containers(Ran(0, "")), self.folder, main.BUG), "could not make the tree that checks bug 1's fix at the base: ")
+2 -1
View File
@@ -9,7 +9,8 @@ cd "$(dirname "$0")"
socket=/var/run/docker.sock
# An untagged image, which docker image prune removes, since a cancelled run skips any cleanup.
image=$(printf 'FROM docker:29.1.3-cli AS docker\nFROM python:3.14.8\nCOPY --from=docker /usr/local/bin/docker /usr/local/bin/docker\n' | docker build --quiet --memory 1g --memory-swap 1g -)
git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
# deploy-release names the container in CI_CONTAINER, to remove it where it stops a run that hangs: stopping this script and its docker client leaves the container running. CI gives no name.
git bundle create - HEAD | docker run --rm -i ${CI_CONTAINER:+--name "$CI_CONTAINER"} --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
cat >/tmp/head.bundle
git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle /tmp/repo
cd /tmp/repo
+141
View File
@@ -4372,3 +4372,144 @@ Inherited architect, decided by:
- Navigation, Shape: `bin/do_epic/epic_run.py:21` `EpicRun`: the shared run record has one named place both main.py and parking.py import
- Locality: `bin/claude_code/entries.py:87` `json_objects`: stream parsing done once in one module
- Shape: `bin/task_bench/main.py:199` `on_disk`: sits beside hand-written try/except OSError blocks, two ways for one job; plant.py imports `Side` from the measuring module
## 2026-11-26T15:04:52Z, PR #731 at 68611733
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 5.5 | 6 | 5.5 | 6 |
| Mid A | 7.5 | 6 | 6.5 | 6.5 | 6.5 |
| Maintainability senior | 7.5 | 5.5 | 6.5 | 6 | 6 |
| Inherited architect | 6.5 | 6.5 | 5.5 | 6 | 6 |
| Mean | 7.13 | 5.88 | 6.13 | 6.00 | 6.13 |
Junior A, hardest first:
- Locality, Overall: `bin/chunk_pr/main.py:448` `merged`: a polling loop with approval waits, a flock turn queue and a hidden call to larv-review; the module docstring must stay open beside it
- Self-sufficiency: `bin/project_config/settings.py:205` `load`: some 22 unnamed cross-setting checks in one comprehension, none pointing to its README bullet
- Locality: `bin/agent_cycle/routing.py:115` `unfinished_route`: rung, floor, cap, mark and unfinished count worked through by hand
- Shape: `bin/do_epic/main.py:236` `chunk_run`: threads `news` through `parked_through`, with a nested `Landed` conditional read three times
- Shape: `bin/agent_cycle/run.py:160` `rule`: runs the judge, annotates, steps the route and archives, beside four similarly named archive helpers
- Self-sufficiency: `bin/plan/ranking.py:144` `weigh`: every stage branches on an old and a new item shape, and nothing says which is current
- Self-sufficiency: `bin/rule_hook/rules.py:27` `RULES`: long legal-sounding strings that are slow to check against the code
- Shape: `bin/larv_review/main.py:228` `COMMANDS`: rows hold long nested lambdas, under a 167-line docstring that is the real spec
Mid A, hardest first:
- Locality, Shape, Overall: `bin/do_epic/scheduler.py:172` `start_chunks`: four sets built from tmux window names, a five-way elif over two limits, and a nested flock
- Locality: `bin/chunk_pr/main.py:448` `merged`: one function decides between human merge, waits, parks, the epic and a flock queue whose order lives outside the process
- Locality: `bin/agent_cycle/routing.py:115` `unfinished_route`: five rung notions at once, settled only by the module's verdict table
- Self-sufficiency: `bin/project_config/settings.py:205` `load`: which combinations of settings are legal takes reading all 22 faults
- Locality: `bin/agent_cycle/judge.py:300` `judge_prompt`: budget arithmetic, and a heading that judge_replay parses back
- Shape: `bin/do_epic/main.py:236` `chunk_run`: a long loop mixing parked news, a reopened epic and the Landed choice
- Shape: `bin/chunk_pr/main.py:398` `epic_opened`: a chain of `isinstance(x, Failure)` conditionals, then a truthiness test on what may be a Failure
- Shape: `bin/rule_hook/env_file.py:41` `reaching`: relies on `and` binding tighter than `or`
Maintainability senior, hardest first:
- Locality, Shape, Overall: `bin/do_epic/scheduler.py:172` `start_chunks`: six sets and a five-branch elif, each branch depending on how the sets were built
- Locality: `bin/do_epic/parking.py:18` `parked_through`: parked state lives in a state file, a tmux window name and Jira, and only the docstring states the order
- Locality: `bin/agent_cycle/routing.py:115` `unfinished_route`: five rung notions plus the unfinished count and the mark, read three times beside the table
- Locality, Shape: `bin/chunk_pr/main.py:448` `merged`: each mode is documented alone, and nothing says how they combine
- Locality: `bin/agent_cycle/escalation_mark.py:1` module docstring: the mark is written in judge.py, read in run.py and turned into a rung in routing.py
- Shape: `bin/release_plan/release_standing.py:206` `next_release`: an algebra of tags, dated headings and named releases, decoded through a field comment
- Shape: `bin/do_epic/main.py:236` `chunk_run`: `news` is a `str | Stop` that also stands for parked
- Self-sufficiency: `bin/larv_review/scoring_due.py:23` `Emptied`: a `str` subclass as a type tag, with its reason in the decision log
Inherited architect, would restructure first:
- Shape, Overall: `bin/do_epic/main.py:378` `issue_move`: the 563-line module imports some 30 modules and holds parsing, status, the chunk loop, issue moves and premises
- Locality: `bin/review_rules/round_titles.py:73` `cap`: the round cap is counted twice, restated in SKILL.md and enforced at two of three moments
- Locality: `bin/larv_review/reviewer_header.py:75` `unanswered_round`: counts rounds unguarded, beside rule-hook's guarded count
- Locality: `bin/rule_hook/round_cap.py:28` `earlier_titles`: fails open where git is slow or no default ref exists
- Shape: `bin/chunk_driver/this_loop.py:12` `Loop`: do-epic builds it too, so the name points the wrong way
- Shape: `bin/agent_cycle/hand_over.py:1` module: "hand over" names four different things across loop_claude and do_epic
- Navigation: `README.md:244` "Packages under bin/": the only grouping of 86 flat entries in `bin/`
- Self-sufficiency: `bin/agent_cycle/run.py:33` `Cycle`: the why behind caps and limits sits behind decision-log citations
## 2026-11-26T15:10:22Z, PR #731 rerun at 68611733
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 7 | 5.5 | 6 | 5.5 | 6 |
| Mid A | 7 | 6 | 6 | 5.5 | 6 |
| Maintainability senior | 7.5 | 6 | 6.5 | 6 | 6.5 |
| Inherited architect | 7 | 7 | 6 | 6.5 | 6.5 |
| Mean | 7.13 | 6.13 | 6.13 | 5.88 | 6.25 |
Junior A, hardest first:
- Locality, Overall: `bin/do_epic/scheduler.py:172` `start_chunks`: five branches over seven sets and three limits under one lock, with part of the parked state read from tmux window names
- Locality: `bin/do_epic/parking.py:105` `resumed_news`: an endless poll loop whose `awaits`, `stays`, `shown` and `said` mix display state with control state
- Shape: `bin/chunk_pr/main.py:448` `merged`: one merge path carries four flags and two sentinels across a loop of turns and a flock queue
- Shape: `bin/do_epic/main.py:236` `chunk_run`: a loop over `news` that computes `Landed` inline, with a near-twin `handed_on` in loop_claude to compare by hand
- Locality: `bin/agent_cycle/judge.py:300` `judge_prompt`: the prompt's wording is coupled to judge_replay's parsing of archived prompts
- Shape: `bin/project_config/settings.py:205` `load`: about 20 conditional checks in one list, with the table they depend on 175 lines below
- Self-sufficiency: `bin/plan/ranking.py:144` `weigh`: an old and a new item shape branch through the module, and nothing says which is current
- Shape: `bin/rule_hook/folder_search.py:89` `skips`: models the flag clusters of rg and ag, hard because the problem is
Mid A, hardest first:
- Locality, Overall: `bin/chunk_pr/main.py:516` `merge_turn`: four merge settings, the flock queue and the approval wait held at once, with the success path hidden in chained `isinstance` checks
- Self-sufficiency: `skills/larv-review/SKILL.md:102` `Re-entry`: a rule table with exceptions to its own rows, each bullet pointing at another section by name
- Locality: `bin/agent_cycle/routing.py:115` `unfinished_route`: five rungs, a step count, the escalation mark and a cap, with the mark's meaning split over four modules
- Self-sufficiency: `bin/agent_cycle/judge.py:88` `Reply`: the field names don't say what each verdict means to the loop
- Self-sufficiency: `bin/rule_hook/folder_search.py:89` `skips`: flag semantics of rg and ag that can't be checked without the tools' manuals
- Locality: `bin/do_epic/main.py:485` `next_cycle`: picks the prompt by comparing a tmux window name with the epic's key, without saying the name is an identity
- Shape: `bin/agent_cycle/run.py:250` `close`: one long conditional expression decides the archived outcome, beside three similarly named archive helpers
Maintainability senior, hardest first:
- Locality, Overall: `bin/chunk_pr/main.py:448` `merged`: one queue loop holds eight concerns whose order matters, rebuilt only with the 109-line help docstring beside it
- Self-sufficiency: `skills/larv-review/SKILL.md:102` `Re-entry`: exceptions to exceptions, read three times to know which passes a fix reruns
- Shape: `bin/do_epic/main.py:236` `chunk_run`: the loop variable `news` is a `str` or a `Stop`, and a nested conditional picks the `Landed` value
- Self-sufficiency: `bin/do_epic/main.py:402` `handed_on`: retries through an intermediate status and polls with no stated bound
- Shape: `bin/chunk_pr/main.py:398` `epic_opened`: a chain of `x = prev if isinstance(prev, Failure) else f(prev)` hides the success path in the else arms
- Self-sufficiency: `bin/plan/ranking.py:239` `score`: branches on goal term and on an old and a new shape, and the reason sits in a plan item
- Shape: `bin/project_config/settings.py:205` `load`: about twenty conditional entries encode the cross-setting rules
- Shape: `bin/rule_hook/rules.py:27` `RULES`: each rule's prose is one very long string, which hides the table's structure
Inherited architect, would restructure first:
- Shape, Overall: `README.md:244` `Packages under bin/`: one flat list of about 40 bullets carries a level of some 82 entries, with no grouping into families
- Navigation: `bin/agent_cycle/routing.py:115` `unfinished_route`: routing has about nine homes, and no file says which parts make it up
- Self-sufficiency: `bin/review_rules/round_titles.py:39` `named_counts`: the round cap's whole contract lives in SKILL.md prose, and no code counts reviewer launches
- Self-sufficiency: `bin/rule_hook/round_cap.py:28` `earlier_titles`: fails open to an empty list on a slow git, and nothing at the cap says so
- Shape: `bin/chunk_driver/this_loop.py:12` `Loop`: built per chunk and used by do-epic too, as the `loop_`-prefixed packages are
- Shape: `bin/chunk_driver/cycle_start.py:96` `cycle_of`: ten keyword arguments on one line
- Shape: `bin/agent_cycle/run.py:33` `Cycle`: 17 fields, allowed by a decision the reader must open the log to read
- Locality: `bin/loop_claude/loop/reload.py:85` `fingerprint`: an edit to any `.py` under `bin/` reloads the running loop, through a handover format that already carries history
## 2026-11-27T13:55:16Z, PR #732 at 4a35c74f, against 606cf25e
Ruling: better
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Mid A | better | better | better | same | better |
| Inherited architect | better | better | better | same | better |
Mid A, decided by:
- Locality: `bin/deploy_release/cut.py:38` `cut`: each step reports through a `say` argument decided once in main, where the base's module-level `said` printed to stderr as a hidden side effect
- Locality, Shape: `bin/deploy_release/cut.py:144` `ready_release`: one function answers one question, where the base's `review` flag switched a match case; each caller decides what an unreviewed release means
- Locality, Navigation: `bin/deploy_release/patch.py:221` `run_ci`: the timeout, kill and container clean-up have their own file, ci_script.py, where the base ran ci.sh inline; `CI_CONTAINER` links to ci.sh through the environment
- Navigation, Shape: `bin/task_bench/main.py:1` task_bench split into bugs/, features/ and figures/: a symptom picks a subfolder first, where the base held about 22 modules side by side
- Locality, Shape: `bin/task_bench/main.py:432` `SOURCES`: the kind is settled once in one table, where the base checked it twice with isinstance; the Source, Planning, Planner chain of lambdas and near-synonym names holds the gain back
- Shape, Locality: `bin/task_bench/main.py:320` `checked`: parsing, checking and defaults are separate functions without in-place mutation, where the base's `options` filled `given` with setdefault
- Shape: `bin/do_epic/parking.py:127` `Told`: loop-local mutable state became a small object, and the loop body reads as three cases
- Locality: `bin/plan/release.py:16` `REVIEW_TITLE`: one constant shared by four modules, where the base hard-coded the title
- Shape: `bin/task_bench/tasks.py:14` `Side`: the shared type moved from the figures module to the module of shared task types
- Navigation: `bin/do_epic/backend/protocol.py:13` `REVIEW_LABEL`: one of do-epic's labels now sits apart from the other two, and its copied comment fits its new spot less well
- Self-sufficiency: `bin/task_bench/figures/record_figures.py:16` `SIDES`: its comment names a path the move made stale, offset by the new docstrings on the trace and the ci.sh limit
Inherited architect, decided by:
- Locality, Shape: `bin/task_bench/main.py:432` `SOURCES`: each kind's reading stays in one function, where the base's `tasks_from` union and its isinstance checks had to be edited in two functions in step
- Shape: `bin/task_bench/main.py:237` `Planner`: the most expensive read of the change; three nested callables per kind, unwound through functools.partial, and `kind` parameters two sources never use
- Navigation, Shape: `bin/task_bench/main.py:1` task_bench split into bugs/, features/ and figures/: nine files and three named folders at the top, where the base had about 38 files flat; figures/gather.py filing plan items isn't "figures"
- Locality: `bin/deploy_release/patch.py:52` `cut_patch`: `say` and `ci` come in from the caller, where the base printed from module level and ran ci.sh inline without a timeout or a record
- Navigation: `bin/deploy_release/ci_script.py:27` `ci_runner`: a hung ci.sh or a dead cut leads to files named for it, ci_script.py and trace.py; `CI_CONTAINER` couples to ci.sh, commented at both ends
- Locality: `bin/task_bench/main.py:293` `options`: each step is a pure function, where the base's single loop changed `given` as it went and made checks order-dependent
- Shape: `bin/task_bench/tasks.py:14` `Side`: the core type sits with what the task kinds share, not in the report module
- Shape: `bin/release_plan/release_standing.py:138` `reviewed_releases`: returns the reviewed releases, where the base's bool said only that some review landed
+4 -2
View File
@@ -154,7 +154,9 @@ Valid while `~/.claude` is a checkout of this repo.
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_plan/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
2026-11-24, lilleman, todo item 536. `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, holding only the commits named, for a fix that must ship before `main`'s other unreleased work. Before it, 0.15.1 was cut by those steps by hand. The patch's commit has the tag as its parent, not `main`'s head, so no pull request into `main` can merge it, and CI runs only on pull requests: the tool runs `ci.sh` on it, as CI does, before it tags. Then it merges the tag back into `main` with `-s ours` through a pull request, so the tag is in `main`'s history, where the next cut and `chunk-preflight` read it, and a release review on `main` counts only for a release later than the last cut. GitHub's rebase merge would drop that merge commit, so the tool refuses a GitHub origin. A patch skips the release review: `chunk-preflight` still calls it due until the patch is cut, so cut a patch as soon as its fix merges. Plain `--cut` refuses a patch of the newest tag, since it would ship all of `main` under a patch number. A panel of three readers seated as the owner picked the spelling `--cut-patch` over `--cut --patch` and `--hotfix`: one flag that names the action, which can't be read as a plain `--cut`.
2026-11-24, lilleman, todo item 536. `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, holding only the commits named, for a fix that must ship before `main`'s other unreleased work. Before it, 0.15.1 was cut by those steps by hand. The patch's commit has the tag as its parent, not `main`'s head, so no pull request into `main` can merge it, and CI runs only on pull requests: the tool runs `ci.sh` on it, as CI does, before it tags. Then it merges the tag back into `main` with `-s ours` through a pull request, so the tag is in `main`'s history, where the next cut and `chunk-preflight` read it. GitHub's rebase merge would drop that merge commit, so the tool refuses a GitHub origin. A patch skips the release review: `chunk-preflight` still calls it due until the patch is cut, so cut a patch as soon as its fix merges. Plain `--cut` refuses a patch of the newest tag, since it would ship all of `main` under a patch number. A panel of three readers seated as the owner picked the spelling `--cut-patch` over `--cut --patch` and `--hotfix`: one flag that names the action, which can't be read as a plain `--cut`.
2026-11-27, lilleman, the release review of 0.16.0. A release review on `main` counts only for the release its title names, which must be exactly the next release, as `chunk-preflight --help` states. So the patch's own review, which the merge leaves on `main` after the tag, doesn't review any later release, and neither does a review opened under a release name todo.md has since changed. Where todo.md names no next release, a review of any release after the last cut counts.
## do-epic: drives one Jira epic whose items span repos, or have none, ranked by the epic's goals, then code health, then each repo's goals, and closes the epic only once the human confirms every goal
@@ -533,7 +535,7 @@ The base is the last measured commit: the default branch's newest merged change
## review: the architecture and principles passes run only in the release review, a release's last chunk, which must land before the release is ready to cut; between releases the product-owner pass reviews changes to what consumers rely on
2026-10-29, lilleman. Serves goals 1.4 and 1.5, and code health. The principles audit read the whole project on every chunk that changed code, because small changes had let a project drift; it was the costliest reviewer after the worker, and it filed findings unrelated to the chunk. A per-chunk architecture trigger needs judgment about what a change carries, which a worker knows only after the work, and a planner or worker asking for the review would pile up agents. So both passes run once, over the whole project, in the release review: the chunk that runs once a release holds no item and changes are unreleased. They may refactor boldly, five rounds each, and their fixes take the stability, security, overrides and prose passes, two rounds each. The human sets how much drift a review must catch through how big a release is. Between releases, the product-owner pass reviews changes to what consumers rely on, such as routes, file formats and CLI flags, which the architecture trigger used to cover. `chunk-preflight` reports a release review due until a commit titled `Release review of <release>` follows the newest `v*` tag, and only then the release ready to cut. A project that deploys every merge, as this repo does, carries drift into production until its release review; lilleman means to move such projects onto releases. Valid while drift a release's chunks leave stays small enough for one review to fix.
2026-10-29, lilleman. Serves goals 1.4 and 1.5, and code health. The principles audit read the whole project on every chunk that changed code, because small changes had let a project drift; it was the costliest reviewer after the worker, and it filed findings unrelated to the chunk. A per-chunk architecture trigger needs judgment about what a change carries, which a worker knows only after the work, and a planner or worker asking for the review would pile up agents. So both passes run once, over the whole project, in the release review: the chunk that runs once a release holds no item and changes are unreleased. They may refactor boldly, five rounds each, and their fixes take the stability, security, overrides and prose passes, two rounds each. The human sets how much drift a review must catch through how big a release is. Between releases, the product-owner pass reviews changes to what consumers rely on, such as routes, file formats and CLI flags, which the architecture trigger used to cover. `chunk-preflight` reports a release review due until that review has landed, and only then the release ready to cut; `chunk-preflight --help` says which commit counts. A project that deploys every merge, as this repo does, carries drift into production until its release review; lilleman means to move such projects onto releases. Valid while drift a release's chunks leave stays small enough for one review to fix.
## review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies
+99
View File
@@ -3601,3 +3601,102 @@ Read most (opens and searches):
- `bin/task_bench/shipped_features.py` 2
- `bin/branch_chunks/read.py` 1
- `docs/decisions.md` 1
## Reading cost, chunk 5cd159e9e122, finished 2026-11-25T23:21:23Z
49613 new input tokens before the first commit.
Read most (opens and searches):
- `skills/larv-review/SKILL.md` 8
- `docs/decisions.md` 6
- `agents/prose-reviewer.md` 2
- `bin/rule_hook/round_cap.py` 2
- `bin/review_rules/round_titles.py` 1
- `ci.sh` 1
## Reading cost, chunk d82aef4bfe70, finished 2026-11-26T00:36:30Z
77343 new input tokens before the first commit.
Read most (opens and searches):
- `bin/agent_cycle/test_run.py` 9
- `bin/agent_cycle/run.py` 5
- `bin/claude_code/test_claude_code.py` 4
- `bin/loop_claude/loop/test_chunk_start.py` 3
- `README.md` 2
- `bin/loop_claude/test_black_box.py` 2
- `bin/agent_cycle/retry.py` 1
- `bin/agent_cycle/worker.py` 1
- `bin/claude_code/session.py` 1
- `bin/loop_claude/loop/chunk_start.py` 1
## Reading cost, chunk 899c59a72db0, finished 2026-11-26T02:02:41Z
88725 new input tokens before the first commit.
Read most (opens and searches):
- `bin/task_bench/test_task_bench.py` 5
- `bin/task_bench/main.py` 4
- `bin/task_bench/planted_mutant.py` 4
- `README.md` 3
- `bin/task_bench/rust_bugs.py` 3
- `CHANGELOG.md` 2
- `bin/mutate_changes/changed_lines.py` 2
- `bin/task_bench/plant.py` 2
- `bin/task_bench/runs.py` 2
- `docs/decisions.md` 2
## Reading cost, chunk d1dab3385426, finished 2026-11-26T09:20:19Z
581672 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 5
- `bin/project_config/main.py` 2
- `bin/project_config/settings.py` 2
- `bin/task_bench/bench_folder.py` 2
- `bin/task_bench/feature_tasks.py` 2
- `docs/decisions.md` 2
## Reading cost, chunk a2b51a47f8f9, finished 2026-11-26T09:29:04Z
51817 new input tokens before the first commit.
Read most (opens and searches):
- `principles/technical-principles.md` 2
## Reading cost, chunk 3ffee0d362c0, finished 2026-11-26T11:46:13Z
140289 new input tokens before the first commit.
Read most (opens and searches):
- `bin/task_bench/main.py` 9
- `README.md` 6
- `bin/mutate_changes/in_diff_tools.py` 3
- `bin/task_bench/planted_mutant.py` 3
- `bin/task_bench/test_rust_bugs.py` 3
- `bin/mutate_changes/changed_lines.py` 2
- `bin/mutate_changes/tool_process.py` 2
- `bin/task_bench/go_bugs.py` 2
- `bin/task_bench/tasks.py` 2
- `bin/task_bench/test_go_bugs.py` 2
## Reading cost, chunk f6f944a18249, finished 2026-11-26T15:21:17Z
215178 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 4
- `bin/task_bench/registers.py` 3
- `docs/decisions.md` 2
- `CHANGELOG.md` 1
- `bin/task_bench/feature_tasks.py` 1
- `bin/task_bench/tasks.py` 1
- `todo.md` 1
+2
View File
@@ -30,6 +30,7 @@
* Make invalid states unrepresentable.
- Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors.
- A function's inputs too: take only inputs that cannot disagree, instead of checking that they agree. BANNED: a test helper that takes a token and a message, and checks that the message holds the token. GOOD: the helper makes the token and builds the message. When a review finds a second edge case in a check, change the signature so the input can't occur.
- A data importer's filter on a field never drops a row the importer's own fixups complete. A fixup is a hand-written correction to one source row. Filter after applying the fixups, and exempt a row whose fixup leaves the field empty on purpose. BANNED: dropping source rows with an empty `population` before a fixup fills in `population` for one of them. GOOD: apply the fixups, then filter.
* Always store timestamps as full ISO datetime in UTC.
- Always communicate timestamps as full ISO datetime in UTC from APIs with database access.
* Always grant explicit access to data, both read and write.
@@ -55,6 +56,7 @@
- Pin wording only where the wording is the contract: a message a consumer parses, a published format. For prompts, help and error text, assert the facts the text must carry — an item ID, a model argument, an error code — not the sentence. BANNED: `assertIn("<a 600-character prompt sentence>", prompt)`. GOOD: `assertIn("model opus, effort high", prompt)`.
- One behaviour per test, named for it, tested once, at the lowest level that reproduces it. No loops or branches in a test body; parametrize the cases.
- A test doesn't decide at run time whether to check anything: no conditional skip, early return, or catch around its assertions. A test that needs a state creates it, or fails and names what is missing. BANNED: `test.skip(created.every((count) => count === 0))` after the payroll run under test, since a broken payroll also creates zero rows. GOOD: before running the payroll, check each precondition and fail naming the one that is missing; after it, `expect(created).toEqual([1, 2, 1])`.
- A test that scans rows for the one row that breaks a pattern also asserts that the row exists, or it passes when the row is missing. BANNED: looping over every row and asserting that only the row named `X` has an empty cell. GOOD: collect the names of the rows with an empty cell, then `assertEqual(["X"], names)`.
- Every escaped bug becomes a test that fails without its fix.
- Write no test that no real bug could fail: a constant's value, a list's length, the framework's own behaviour.
- A test neither sleeps nor asserts on the wall clock, and seeds any randomness.
+25 -13
View File
@@ -99,20 +99,32 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. A stability pass whose round's fixes skip the next round per "Re-entry" → "Mechanical answers" is done once that rule's run is clean. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most two rounds per chunk, and the release review's architecture and principles passes five; don't ask the user for more. Answer its last round's findings per "Findings": those fixes merge once the gate passes, unreviewed by that pass. rule-hook's `round-cap` refuses a round commit that would take a pass past its cap, and no override waives it. A review the auto-reviewer posts after its second isn't a round: fix none of it and rerun no pass for it, but file a security finding it raises per `~/.claude/CLAUDE.md` → "Working loop", and any other 🔴 in `todo.md`.
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟢 or a ❓ doesn't rerun any pass, whatever it changes. A fix for a 🟡 of a pass other than prose meets only the 🟡 row below, and a fix for a prose finding, of any severity, only the last row. A round's fixes for 🔴 findings, its 🟡 fixes that meet that row, and its prose fixes that meet the last row, re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4; "Mechanical answers" below names the one exception. A pass at its cap doesn't run again ("Round cap" → "Cap").
**Re-entry.** A fix is a change no pass has seen. It reruns the pass of every row below that it fits in both columns:
| The fix | Reruns |
|---------|--------|
| answers a 🔴 of a pass other than prose | that pass |
| answers a 🟡 of a pass other than prose, and removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test or assertion with a condition or a catch, unless it only kills a named mutant or makes a named failing test pass | that pass |
| carries an architectural decision, in the release review | Architecture |
| changes code, config or tests, in the release review | Principles |
| opens an untrusted-input boundary or touches authn/authz, secrets or crypto | Security, unless the full scan reruns on it |
| made rule-hook log an override | Overrides |
| changes behaviour: what the code or its tests do | Stability |
| answers a prose finding by rewriting what a claim says, where a command or a source file can check the claim, such as what generated output holds, a number or a licence term; rewording that keeps what it says doesn't count | Prose, as its second and last round |
| The fix answers | and | Reruns |
|-----------------|-----|--------|
| a 🔴 of a pass other than prose | changes anything | that pass |
| a 🔴 of a pass other than prose | carries an architectural decision, in the release review | Architecture |
| a 🔴 of a pass other than prose | changes code, config or tests, in the release review | Principles |
| a 🔴 of a pass other than prose | opens an untrusted-input boundary or touches authn/authz, secrets or crypto | Security, unless the full scan reruns on it |
| a 🔴 of a pass other than prose | made rule-hook log an override | Overrides |
| a 🔴 of a pass other than prose | changes behaviour: what the code or its tests do | Stability |
| a 🟡 of a pass other than prose | removes or loosens an assertion, changes an expected value, or skips, deletes or guards a test or assertion with a condition or a catch | that pass |
| a prose finding, of any severity | rewrites what a claim says, where a command or a source file can check the claim, such as what generated output holds, a number or a licence term | Prose, as its second and last round |
A fix meets every row it fits, except the two fixes named above, each of which meets only its one row. Such a fix meets no row once §2's tests and mutation command run clean on it and the named failing test is unedited ("Mechanical answers"); a skipped test kills no mutant. A comment or doc edit inside a fix for another pass's finding doesn't rerun any pass. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
Example: in the release review, a fix for a stability 🔴 that changes code and a comment reruns Stability and Principles.
A fix that fits no row doesn't rerun any pass. So none of these does:
- a fix for a 🟢 or a ❓, whatever it changes;
- a fix for a 🟡 that does none of what the 🟡 row lists;
- a fix for a prose finding that rewords a claim and keeps what it says.
A comment or doc edit inside a fix for another pass's finding adds no pass: no row reruns Prose for it.
One fix fits the 🟡 row and still doesn't rerun the pass: a fix that only kills a named mutant or makes a named failing test pass, once §2's tests and mutation command run clean on it and the named failing test is unedited ("Mechanical answers"). A skipped test kills no mutant.
A round's fixes re-enter together: run every pass the table names for any of them, a done pass included, in the waves of "Waves", then §4. "Mechanical answers" below names the one case where the fixes for a 🔴 don't rerun its pass. A pass at its cap doesn't run again ("Round cap" → "Cap").
**Mechanical answers.** A stability round's fixes may skip the next stability round. That holds where the round reported a 🔴, and each of its 🔴 and 🟡 findings asked only that a named mutant be killed or a named failing test pass. Run §2's tests and mutation command on the fixes, and fix again per §2 until they leave no failing test and no surviving mutant that changes behaviour. Each named failing test must pass as the round found it, not edited or deleted. Then the stability pass doesn't run again, and the round's answer commit title ends `; tests and mutants clean at <commit>`. The fixes still rerun each other pass whose row they meet. Where the run can't be made clean, or a fix edits a named failing test, the stability pass runs again as the table says.
@@ -140,7 +152,7 @@ A fix meets every row it fits, except the two fixes named above, each of which m
The release review is a release's last chunk, run once the release holds no item and changes are unreleased, before it is ready to cut. It looks for the drift the release's small changes left, and fixes it.
- **When.** `chunk-preflight` reports a release review due. It counts one as landed once a commit titled `Release review of <release>` follows the newest `v*` tag on the default branch.
- **When.** `chunk-preflight` reports a release review due. `chunk-preflight --help` says which commit counts as the review having landed.
- **Branch.** `release-review-<release>`, off the default branch. Open it with `git commit --allow-empty -m "Release review of <release>"`.
- **Passes.** Architecture, then Principles, each over the whole project, per "Waves". Tell both to refactor boldly where the code needs it. Each takes up to five rounds.
- **Their fixes** re-enter Stability, Security, Overrides and Prose per "Re-entry", each at most two rounds.
+120 -102
View File
@@ -6,26 +6,28 @@
`Bar = 0.1`
`Next ID = 545`
`Next ID = 553`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 543 | 0.16.0 | | | **Add to the testing principles that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete.** | 1 | 2 | 3 | 4 | 2 | 1.1 by 3 | 1.2 |
| 544 | 0.16.0 | | owner | **Have stability-reviewer check, for each input shape a change starts to handle, its neighbours: each part alone, the parts in another order, and a part missing, each compared with what the base made of the same input.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 524 | 0.16.0 | | owner | **Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 6 | 1.1 by 3 | 0.5 |
| 527 | 0.16.0 | | owner | **Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 528 | 0.16.0 | | owner | **Plant bugs for `task-bench` in PHP, from the mutants Infection kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 |
| 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 |
| 478 | 0.17.0 | | question | **Name the project, its repo and its two commands, today proposed as `do-release` and `do-epic`.** | 1 | 1 | 2 | 2 | 1 | | 0.0 |
| 548 | 0.17.0 | | defect | **Treat a chunk whose recorded base is origin's default branch as merging into that branch, so `chunk-pr merge` honours `merge = "human"` and `wait-for-approval` there.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 3 | 1.3 |
| 546 | 0.17.0 | | | **Have stability-reviewer check a change's setup steps for an outside service against the service's current documentation, and each command against the service against every state the service may be in.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 3 | 1.2 |
| 552 | 0.17.0 | | defect | **Ask for a review on `chunk-pr push` once the forge shows the pushed head on the pull request, and fail where no open pull request takes it, so a push never skips the review request without saying so.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 3 | 1.2 |
| 542 | 0.17.0 | | | **Make chunk-preflight report a project whose code is space-indented with no `.editorconfig` or formatter setting that says so, and narrow the tabs principle to explicit overrides.** | 2 | 2 | 3 | 5 | 4 | 1.1 by 4 | 1.2 |
| 523 | 0.17.0 | | | **Make the security pass and stability-reviewer check that a new secret's docs name its scope and its reach, such as the other repositories its account can use.** | 1 | 1 | 2 | 2 | 1 | 1.1 by 2 | 0.9 |
| 537 | 0.17.0 | | | **Flag regexes that use `$` to validate a whole input, since `$` also matches before a final newline.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 538 | 0.17.0 | | | **Flag validation that checks a value other than the one the code goes on to use, such as before trimming, stripping or converting it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 547 | 0.17.0 | | | **Add a technical principle: tell a failure's cause from a status code or a typed error, never from a tool's message text unless the tool documents that text as unique to the cause.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 549 | 0.17.0 | | | **Run each claimed output from the state a fresh checkout leaves, without the ignored files earlier runs wrote, and check each claim about what a command writes.** | 1 | 1 | 2 | 2 | 1 | 1.1 by 2 | 0.9 |
| 550 | 0.17.0 | | | **Have stability-reviewer check a guard that tests where a thing is against every place the thing passes through in its life.** | 1 | 1 | 2 | 2 | 1 | 1.1 by 2 | 0.9 |
| 541 | 0.17.0 | | | **Find a Gitea pull request by its branch and head however many pull requests are newer, so `chunk-pr clean`, `chunk-pr merge` and `chunk-preflight` see an older one.** | 2 | 2 | 3 | 5 | 2 | 1 by 2 | 0.8 |
| 545 | 0.17.0 | | | **Have chunk-preflight name each next-release item with no `Touches:` list while others wait, and have loop-claude launch a subagent that writes the lists before it starts the next chunk.** | 3 | 2 | 3 | 6 | 6 | 1.1 by 4 | 0.6 |
| 539 | 0.17.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a Rust test kept in a file of its own.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 |
| 544 | 0.17.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 |
| 480 | 0.18.0 | | owner | **Resolve every path the tools use in one module: the release root (the folder the running code ships in), the config folder, the state folder and the Claude home. Then only that module names `~/.claude`, and the loop still runs from `~/.claude`.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 3, code health by 3 | 2.4 |
| 481 | 0.18.0 | 480 | owner | **Put the release's tools on `PATH` for every session the loop starts and every hook it runs, name them bare in the prose in place of `~/.claude/bin/<tool>`, and refuse the old spelling in new prose.** | 3 | 2 | 3 | 6 | 6 | 1.4 by 2, code health by 2 | 1.6 |
| 482 | 0.19.0 | 478, 481 | owner | **Install the setup with `uv tool install` from a release tag, with `do-release` and `do-epic` on `PATH`, and replace `deploy-release` with `do-release self-update`.** | 3 | 2 | 3 | 6 | 7 | 1.6 by 4, 1.3 by 3 | 1.3 |
@@ -57,7 +59,7 @@
| 499 | 0.23.0 | | defect | **Stop `todo-item add` and `edit` from waiting on a stdin that stays open without data, so a call without a heredoc ends at once.** | 2 | 2 | 2 | 4 | 2 | 1.5 by 3, 1.4 by 2 | 1.9 |
| 445 | 0.23.0 | | | **Refuse a plan that holds an item a `Finish item <ID>` commit already removed, so a merge resolution cannot bring a finished item back.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3, 1.1 by 2 | 1.8 |
| 171 | 0.23.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 1.8 |
| 300 | 0.23.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality, Shape and Self-sufficiency first; today the second scoring run at 6322c6e1 scored Navigation 6.75, Locality 5.75, Shape 5.75, Self-sufficiency 5.75 and Overall 6.00.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
| 300 | 0.23.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Self-sufficiency, Locality and Shape first; today the second scoring run at 68611733 scored Navigation 7.13, Locality 6.13, Shape 6.13, Self-sufficiency 5.88 and Overall 6.25.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
| 264 | 0.23.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 1.7 |
| 323 | 0.23.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
| 342 | 0.23.0 | | | **Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
@@ -105,6 +107,7 @@
| 395 | 0.23.0 | | decision | **Keep each block a save didn't change, with its localId, and the spacing paragraphs beside it as Jira or Confluence holds them.** | 3 | 2 | 2 | 5 | 5 | 1.6 by 4 | 0.8 |
| 425 | 0.23.0 | | | **Show on loop-claude's terminal why it doesn't start a chunk beside the next item, as chunk-preflight prints it.** | 1 | 1 | 2 | 2 | 2 | 1.5 by 2 | 0.7 |
| 169 | 0.23.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.7 |
| 551 | 0.23.0 | | | **Run each mutation tool of `mutate-changes` in the folder that holds its module file, so a repo with `go.mod` below the top gets its Go lines mutated.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 2 | 0.7 |
| 447 | 0.23.0 | | | **Stop a headless claude call that runs past a time limit, and report it as a failure, so a hung judge or stuck check can't hold the loop.** | 2 | 2 | 2 | 4 | 3 | 1.5 by 2 | 0.7 |
| 367 | 0.23.0 | | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
| 520 | 0.23.0 | | | **Mutate the shell lines a branch changes in `mutate-changes`, so a change to a shell script gets the same check as one in Python, Go or PHP.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 2 | 0.5 |
@@ -115,80 +118,6 @@
## Details
### 543. Add to the testing principles that a test scanning rows for an exception asserts the exception exists, and that a data importer does not drop a row its own fixups complete.
Two findings an outside reviewer raised on a data change that our review missed:
- A test scanned every row of a shipped table and asserted that exactly one named row held an empty cell. It passed when the table had no such row at all, since the loop never met it. A test that scans for an exception must also fail when the exception is absent.
- An importer filtered source rows on a field before applying its fixups for that field, so a fixup that blanked the field on one row could not keep the row once the source left it empty. A filter on a field reads the value after the fixups, or exempts the fixed-up rows.
Put the first in `principles/technical-principles.md` under tests ("each test earns its keep"), and the second beside the rule on inputs that cannot disagree or in stability-reviewer's checks. Where a deterministic check can find the first, such as a mutant that deletes the exception's row, prefer that over prose.
### 544. Have stability-reviewer check, for each input shape a change starts to handle, its neighbours: each part alone, the parts in another order, and a part missing, each compared with what the base made of the same input.
An outside reviewer found two defects our review passed, in a parser change that read a party's address from structured fields beside free-text lines:
- The change handled "both structured fields present" and "both missing", and the ticket said to split the free text only when both were missing. With only one present, the new code lost a value the base had filled. The stability reviewer saw the case, since tests pinned it, but checked it against the ticket's words, not against the base's output.
- A rule that left out a free-text line repeating the structured fields matched only the one order seen in the data, not either field alone or the other order.
Add to `agents/stability-reviewer.md`: for each input shape a change starts to handle, list its neighbours (each part alone, the parts in another order, a part missing or blank) and compare what the change makes of each with what the base made. A field the base filled and the change leaves empty is a 🟡 unless the ticket names that input, and a 🔴 where it loses data users relied on. Before acting, a ticket's acceptance criterion "everything else stays as before" outranks its proposed rule's literal wording.
Touches:
- `agents/stability-reviewer.md`: `### 5. Edge Cases & Input Validation` (small)
### 524. Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names.
The second part of item 504, which says what a bench feature is and when a run counts. A stronger model than the project's writes the six, once. Each breaks one of fejkdata's goals while it would suit another audience:
1. `{p!}` picks the name `p` again (4.3, a name keeps one pick); it exercises `pick.go`, the seats' hardest place.
2. `{frist}` renders as `{first}`, with a warning on stderr (4.7, fejkdata does not guess at mistakes).
3. `--typos 0.1` misspells one value in ten, for testing deduplication (3.3, values look real).
4. `{@define full = {first} {last}}` defines a macro that `{@full}` prints (4, more syntax).
5. `--table` prints a boxed, aligned table (the bulk author, who pipes CSV).
6. `--unique-forever` keeps a state file, so no value repeats across runs (seeded output reproduces).
Done when `task-bench` counts a run of each: its acceptance tests fail at fejkdata's base and head and pass with its reference patch. The six land in fejkdata's checkout or its config folder, wherever its `bench-tasks` setting points, so the item changes no file of this repo and carries no `Touches:` list. About 1,000 lines of Go and specs.
### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.
Stryker runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON report. Tell Haiku the failure the project's test runner prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no TypeScript.
Touches:
- `bin/task_bench/typescript_bugs.py`
- `bin/task_bench/test_typescript_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_stryker`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
### 528. Plant bugs for `task-bench` in PHP, from the mutants Infection kills.
Infection runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON log. Tell Haiku the failure PHPUnit prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no PHP.
Touches:
- `bin/task_bench/php_bugs.py`
- `bin/task_bench/test_php_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_infection`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
### 525. Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.
The second part of item 505, which says what a source-data task is and when a run counts. The country code of each comes from ISO 3166-1's user-assigned range (AA, QM–QZ, XA–XZ, ZZ), leaving out XK, which the EU and others use for Kosovo, so no task meets real data. Each register has the quirks real ones publish.
Each checker runs a template such as `{/person[QZ]}` with a fixed seed, fejkdata's full test suite with the data-licence tests, and the importer again, which must reproduce the committed data.
- D1: names weighted by frequency, from a semicolon CSV in Latin-1.
- D2: addresses, with postcodes mapped to towns, from nested JSON; values that belong together come from one pick.
- D3: a valid national id, from a spec page giving the checksum; the checker validates every id the template prints.
- D4: companies with legal-form suffixes, from an XML register.
- D5: D1's register in its next edition, with a renamed column and a new code list, so Haiku updates an importer that exists.
Done when `task-bench` counts a run of each. The five land wherever fejkdata's `bench-tasks` setting points, which its config must first set, so the item changes no file of this repo and carries no `Touches:` list. About 1,500 lines of Python, Go, data and specs.
### 477. Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.
Part of the standalone-install plan lilleman approved on 2026-11-20. `do-release` and `do-epic` stand for the names item 478 picks. Goal 2, "Make my claude setup shareable between computers", and an audience of lilleman, with client teams as readers of what the loop writes, no longer fit. The goals and the audience are the human's to write; propose a wording and ask.
@@ -197,6 +126,39 @@ Part of the standalone-install plan lilleman approved on 2026-11-20. `do-release
Part of the standalone-install plan lilleman approved on 2026-11-20. Later items say `do-release` and `do-epic` for the names this item picks. The names set the install folders, such as `~/.config/do-release/`, so items 482, 485 and 496, and every item they block, wait for them.
### 548. Treat a chunk whose recorded base is origin's default branch as merging into that branch, so `chunk-pr merge` honours `merge = "human"` and `wait-for-approval` there.
`base_of` in `bin/chunk_pr/main.py` returns `to_epic=True` for any branch whose `branch.<branch>.chunk-base` is set in git's config. In a project that sets `epic-branch`, a chunk that goes into the default branch instead of the epic's working branch can still record `chunk-base = main`. Then `chunk-pr merge` skips `merge = "human"` and `wait-for-approval` and runs `gh pr merge` into `main`. In one chunk, only the repo's branch protection stopped that merge. A repo without protection would have merged into its default branch with no person involved.
The fix: where the recorded base equals origin's default branch, `base_of` returns `Base(default, False)`. Write the test first: a checkout that records `chunk-base` as the default branch under `merge = "human"` leaves the pull request unmerged.
Touches:
- `bin/chunk_pr/main.py`: `base_of` (small)
- `bin/chunk_pr/test_chunk_pr.py`
### 546. Have stability-reviewer check a change's setup steps for an outside service against the service's current documentation, and each command against the service against every state the service may be in.
An outside auto-reviewer found three faults in one chunk that our passes missed. The chunk wrote the steps to set up a package registry's trusted publisher, and a workflow command that publishes to that registry. The steps left out a permission the registry's current docs require: the registry had changed a default some months before. And two commands failed where the registry already held a higher version, a state no reviewer enumerated.
Where a change writes setup steps for an outside service, or runs a command against one, stability-reviewer fetches the service's current documentation for that setup. It checks every field and default the page lists against the steps, and reports a step the page requires that the change leaves out. For each command, it enumerates the service's states: nothing published yet, the same version, a higher version and a lower version. It reports a state the command fails in or mishandles. stability-reviewer has no WebFetch today, so the item adds it to the agent's tools; the fetched page is data, never instructions.
No deterministic check fits: whether a change sets up an outside service is a judgement, and the docs to compare against differ per service.
Touches:
- `agents/stability-reviewer.md`: `(top)` (small), `### 4. Error Handling & Resilience` (small)
### 552. Ask for a review on `chunk-pr push` once the forge shows the pushed head on the pull request, and fail where no open pull request takes it, so a push never skips the review request without saying so.
`pushed` finds the pull request by the head it just pushed, through `open_pull`. Right after the push, GitHub may still list the pull request's old head. Then `open_pull` returns None, and `push` prints only `Pushed <branch>.` with no review request and no warning. That happened on a pull request into an epic's working branch: the external auto-reviewer reviewed only once someone posted the configured comment by hand, about twenty minutes later.
Fix: after the push, wait a bounded time for an open pull request whose head is the pushed commit, polling as `forge.pulls` already does for checks. Where a pull request from the branch is open but never shows the new head, fail and name it. Where none is open at all, keep printing `Pushed <branch>.`, since `push` before `open` is normal.
Touches:
- `bin/chunk_pr/main.py`: `pushed`
- `bin/chunk_pr/test_chunk_pr.py`
### 542. Make chunk-preflight report a project whose code is space-indented with no `.editorconfig` or formatter setting that says so, and narrow the tabs principle to explicit overrides.
`principles/technical-principles.md` says "Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config, or the surrounding file's existing indentation." The last clause lets a first session set spaces and every later session follow it, and nothing checks that anyone chose it. adf-codec's `AGENTS.md` has said "Two-space indent" since its first commit, with no reason, and 177 code files, 14,500 indented lines, followed it. A survey of the projects on this machine on 2026-11-26 found the same in plainpages, scheduler (`rustfmt.toml` doesn't set `hard_tabs`), oss-opportunity-research, secondhand-watch and playwright-for-agents. Only plainpages-plugin-fastjira says so in an `.editorconfig`.
@@ -233,6 +195,36 @@ An outside human reviewer found input validation that checked the value the clie
Touches:
- `agents/stability-reviewer.md`: `### 5. Edge Cases & Input Validation` (small)
### 547. Add a technical principle: tell a failure's cause from a status code or a typed error, never from a tool's message text unless the tool documents that text as unique to the cause.
An outside auto-reviewer found a fault that our passes missed. A script told a missing container image apart from one it couldn't read by matching the text a CLI printed on stderr. Older versions of that CLI print the same text for a missing image, a refused credential and a failed request. So the script read "no access" as "missing" and went on as if the image didn't exist. The stability and security passes both read the code and took the message at its word.
The fix asked the registry's HTTP API for the status instead: 404 is missing, and any other failure stops the run. The principle makes that the rule. Where code branches on why a call failed, it reads a status code, an exit code the tool documents, or a typed error. It reads message text only where the tool documents that text as unique to one cause, and it treats every other failure as unknown, which stops the run rather than guessing.
No deterministic check fits: a linter can't tell whether a string match on output decides a failure's cause. Reviewers apply the principles, so a principle is the first place that fits.
Touches:
- `principles/technical-principles.md`: `Handle errors explicitly, as values — avoid the exception path.` (small)
### 549. Run each claimed output from the state a fresh checkout leaves, without the ignored files earlier runs wrote, and check each claim about what a command writes.
Found when an outside reviewer raised two findings that our review had missed:
- A documented local command failed on a fresh checkout. It needed a cache file that earlier writable runs had left in an ignored folder. The implementer's claimed-output runs reused that file, so the claimed-output step showed the command working.
- A README sentence said what a regenerated file's diff holds. The claim was about the file the command writes, not what it prints, so the step never ran it, and the sentence was wrong.
Change `larv-review` §3 → "Claimed output" so that:
- each claim runs from a state like a fresh checkout's, with the ignored build and cache files that earlier runs wrote moved aside;
- a claim about what a command writes, such as a file or a diff, is run like a claim about what it prints.
Touches:
- `skills/larv-review/SKILL.md`: `**Claimed output.**` (small)
### 550. Have stability-reviewer check a guard that tests where a thing is against every place the thing passes through in its life.
A forge's auto-reviewer raised what two stability rounds missed: a fix added a guard that refused a file by looking for its original in the folders where a finished file ends, but not in the folder where a file waits before it is handled, so the guard let the refused case through during a retry. The reviewer read the guard and its tests and checked no other state. Add to `agents/stability-reviewer.md`: for a guard that tests whether a file, row or record exists, list every place or state the thing passes through from arrival to its end, and report each one the guard doesn't look at.
### 541. Find a Gitea pull request by its branch and head however many pull requests are newer, so `chunk-pr clean`, `chunk-pr merge` and `chunk-preflight` see an older one.
Today `pull_at` in `bin/forge/pulls.py` reads only Gitea's first page of 50 pull requests, open or closed, and looks for the branch among them. A pull request with 50 newer ones in that state is missed. PR #652 here merged after 50+ newer PRs had closed, and `chunk-pr clean` then said "no merged pull request from filing-prose-reentry", leaving the worktree and branch to remove by hand. The same lookup serves `open_pull`, so `ready` and `merge` miss an old open one too, and `chunk-preflight` misses a merged chunk's worktree.
@@ -244,6 +236,18 @@ Touches:
- `bin/forge/pulls.py`: `pull_at`
- `bin/forge/test_forge.py`
### 545. Have chunk-preflight name each next-release item with no `Touches:` list while others wait, and have loop-claude launch a subagent that writes the lists before it starts the next chunk.
In fejkdata on 2026-11-27 the loop ran one chunk for hours beside seven waiting items, because five items of the next release (one filed by the reading-cost report, four older) had no `Touches:` list, and `chunk-preflight` says only "No item may start a chunk beside item X's: its detail has no `Touches:` list". Nothing makes a session write the lists, and `rank_todo.py --check` refuses only a list it cannot read.
Three changes:
- `chunk-preflight` prints one fact where an item of the next release has no `Touches:` list and at least one other item of that release waits, naming the items. A release with one item left prints nothing.
- `loop-claude` acts on the fact before it starts the next chunk: it launches one subagent, on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items, to read the code and write each missing list with `todo-item edit --detail`. Where the subagent can't name a part, it lists the whole file and says in the detail that the change is not predictable. The plan edit ships as its own pull request with `chunk-pr`, as plan-only changes do. A list is written once per item and not again until the item is edited.
- `rank_todo.py --check` warns, without failing, on an item of the next release with no `Touches:` list.
Test each with a fake plan: all lists present, one missing with other items waiting, one missing alone in its release, and a list the item's edit made stale is left alone.
### 539. Leave out of a `task-bench` fix a change Haiku makes to a Rust test kept in a file of its own.
Rust may keep its unit tests out of line: `#[cfg(test)] mod tests;` in `src/lib.rs`, the tests in `src/tests.rs`. `mutate_changes.changed_lines.is_test` tells a test by a folder named `test`, `tests` or `__tests__`, or by a file name such as `test_*.py` or `*_test.go`, so `src/tests.rs` counts as code, and `checked_tree` in `bin/task_bench/runs.py` takes it as Haiku left it. A fix that edits or deletes the failing test there passes. The help's Check paragraph says so. It holds at the base and at the head alike.
@@ -256,6 +260,12 @@ Touches:
- `bin/task_bench/test_task_bench.py`
- `bin/task_bench/main.py`: lines 30-37
### 544. Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know.
PHPUnit finds a test by `*Test.php`, wherever it stands, and `node --test` also by `*-test.js`, `*_test.js`, `test-*.js` and `test.js`, with `.ts`, `.mjs` and `.cjs` alike. `mutate_changes.changed_lines.is_test` tells a test by a folder named `test`, `tests` or `__tests__`, or by a name such as `*.test.*`, so `src/PickTest.php` and `src/pick-test.js` count as code. `checked_tree` in `bin/task_bench/runs.py` then takes such a file as Haiku left it, so a fix that edits or deletes the failing test passes, at both sides alike, and `place_files` in `bin/task_bench/bugs/plant.py` may hand the file to the mutation tool as code. The help's Check paragraph says so.
Recommended: tell these names as tests inside task-bench, for a `.php` file and for the suffixes Stryker covers, and keep `is_test` as it is, since changing it would change what `mutate-changes` skips; item 539 does the same for Rust. A product-owner finding on item 527's chunk raised this.
### 480. Resolve every path the tools use in one module: the release root (the folder the running code ships in), the config folder, the state folder and the Claude home. Then only that module names `~/.claude`, and the loop still runs from `~/.claude`.
Part of the standalone-install plan lilleman approved on 2026-11-20. `do-release` and `do-epic` stand for the names item 478 picks. Today about 160 references in some 40 modules name `~/.claude`; `bin/loop_state/paths.py` holds a few. This item changes no behaviour.
@@ -423,30 +433,34 @@ Have the gate, or `rank_todo.py --check` where it runs in a checkout, refuse a p
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality, Shape and Self-sufficiency first; today the second scoring run at 6322c6e1 scored Navigation 6.75, Locality 5.75, Shape 5.75, Self-sufficiency 5.75 and Overall 6.00.
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Self-sufficiency, Locality and Shape first; today the second scoring run at 68611733 scored Navigation 7.13, Locality 6.13, Shape 6.13, Self-sufficiency 5.88 and Overall 6.25.
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the two runs of item 515's chunk at 6322c6e1. The lowest means are Locality, Shape and Self-sufficiency, all at 5.75 in the second run; the first run put Locality at 5.63 and the other two at 5.88. Locality: do-epic and chunk-pr run order-dependent steps and carry state between loop passes (`handed_on`, `parked_through`, `merged`, `levelled_and_finished`), and no code enforces the order. Shape: `bin/do_epic/main.py` and `bin/chunk_pr/main.py` are hubs of about 700 and 764 lines, `bin/` holds about 95 entries at one level, and the OLD_SHAPE fork in `bin/plan/ranking.py` doubles the paths through ranking. Self-sufficiency: the why behind code sits in `docs/decisions.md`, the README or help prose, not beside the unit. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the two runs of item 525's chunk at 68611733. The lowest mean of the second run is Self-sufficiency at 5.88, with Locality and Shape at 6.13; the first run put Locality lowest at 5.88, Self-sufficiency at 6.00 and Shape at 6.13. Self-sufficiency: the why behind code sits in `docs/decisions.md`, cited by title from about 120 places, and the review loop's rules live in `skills/larv-review/SKILL.md`, not beside the unit that enforces them. Locality: do-epic and chunk-pr run order-dependent steps and keep state in tmux window names and between loop passes (`start_chunks`, `resumed_news`, `merged`, `merge_turn`), and no code enforces the order. Shape: `bin/` holds about 82 entries at one level, long functions carry several flags at once, and the OLD_SHAPE fork in `bin/plan/ranking.py` doubles the paths through ranking. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
Aim: one ambitious refactor of the areas below, sized so every mean reaches 7.0 on the chunk's own scoring run. Where a place is already easier to read when the chunk starts, drop it.
Places the seats named, hardest first (`larv-review places`), Locality first:
Places the seats named in the second run, hardest first (`larv-review places`), Self-sufficiency first:
- Locality, Shape, Self-sufficiency: `bin/do_epic/main.py:538` `handed_on`: five branches over the landing, the automation and two statuses, with no table of the cases; it needs the README's do-epic settings beside it. Seven of eight seats named it over the two runs.
- Locality: `bin/do_epic/main.py:379` `parked_through`, with `:455` `resumed_news`: seven flags to hold over park, resume and a human's merge; park must come before resume, and no code enforces it. Six seats named it.
- Locality: `bin/chunk_pr/main.py:448` `merged`, with `:587` `levelled_and_finished`: one loop interleaves the queue turn, approval waits and parking, and the steps' order is load-bearing and unexplained. Four seats named it.
- Locality: `bin/rule_hook/round_cap.py:28` `earlier_titles`: three callers count rounds from titles fetched three ways.
- Locality: `bin/do_epic/scheduler.py:172` `start_chunks`: chunk state is rebuilt from tmux window names.
- Locality: `bin/agent_cycle/routing.py:115` `unfinished_route`: the route depends on state three modules write.
- Shape: `bin/do_epic/main.py:301` `chunk_run`: argument parsing, status, dry run, windows and parking in one 47 KB module.
- Shape: `bin/plan/ranking.py:239` `score`, with `:144` `weigh`: every change is made twice, for OLD_SHAPE and SHAPE. Two seats named it.
- Navigation, Shape: `README.md:234` "Packages under bin/": about 95 entries at one level, tool and shared packages side by side. Both architects named it.
- Shape: `bin/larv_review/plan.py:1` module: decides whether a scoring run is due, not anything about the plan.
- Self-sufficiency: `skills/larv-review/SKILL.md:94` "Round cap": the review loop's rules live only in the skill's text. Two seats named it.
- Self-sufficiency: `bin/larv_review/main.py:33` module docstring: when a scoring run is due is stated only in help prose.
- Self-sufficiency: `bin/agent_cycle/judge.py:25` `INTERRUPT_RULES`: behaviour lives in prompt text no code shows the effect of.
- Self-sufficiency: `bin/project_config/settings.py:201` `load`: the settings' meaning sits in the help text.
- Self-sufficiency: `bin/agent_cycle/verdicts.py:41` `Verdict`: cites `cycle.judge.re_ask_checked`, which doesn't exist.
- Navigation: `bin/agent_cycle/run.py:103` `archived`: cites a `close.py` that doesn't exist.
- Self-sufficiency: `skills/larv-review/SKILL.md:102` "Re-entry", with `:94` "Round cap": a rule table with exceptions to its own rows, read three times to know which passes a fix reruns. Two seats named it.
- Self-sufficiency: `bin/review_rules/round_titles.py:39` `named_counts`, with `bin/rule_hook/round_cap.py:28` `earlier_titles`: the round cap's whole contract lives in the skill's text, no code counts reviewer launches, and `earlier_titles` fails open to an empty list on a slow git.
- Self-sufficiency: `bin/plan/ranking.py:144` `weigh`, with `:239` `score`: an old and a new item shape branch through the module, and nothing says which is current. Two seats named it.
- Self-sufficiency: `bin/do_epic/main.py:402` `handed_on`: retries through an intermediate status and polls with no stated bound.
- Self-sufficiency: `bin/agent_cycle/judge.py:88` `Reply`: the field names don't say what each verdict means to the loop.
- Self-sufficiency: `bin/rule_hook/folder_search.py:89` `skips`: flag semantics of rg and ag that can't be checked without the tools' manuals. Two seats named it.
- Locality, Shape: `bin/chunk_pr/main.py:448` `merged`, with `:516` `merge_turn` and `:587` `levelled_and_finished`: one queue loop holds the merge settings, the flock queue and the approval wait, in an order that matters and that only the help docstring states. Three seats named it.
- Locality: `bin/do_epic/scheduler.py:172` `start_chunks`: five branches over seven sets and three limits under one lock, with part of the parked state read from tmux window names.
- Locality: `bin/do_epic/parking.py:105` `resumed_news`: an endless poll loop whose `awaits`, `stays`, `shown` and `said` mix display state with control state.
- Locality, Navigation: `bin/agent_cycle/routing.py:115` `unfinished_route`: routing has about nine homes, the escalation mark's meaning is split over four modules, and no file says which parts make routing up. Two seats named it.
- Locality: `bin/agent_cycle/judge.py:300` `judge_prompt`: the prompt's wording is coupled to judge_replay's parsing of archived prompts.
- Locality: `bin/do_epic/main.py:485` `next_cycle`: picks the prompt by comparing a tmux window name with the epic's key.
- Locality: `bin/loop_claude/loop/reload.py:85` `fingerprint`: an edit to any `.py` under `bin/` reloads the running loop, through a handover format that already carries history.
- Shape: `README.md:244` "Packages under bin/": one flat list of about 40 bullets carries a level of some 82 entries, with no grouping into families.
- Shape: `bin/do_epic/main.py:236` `chunk_run`: the loop variable `news` is a `str` or a `Stop`, and a nested conditional picks the `Landed` value. Two seats named it.
- Shape: `bin/project_config/settings.py:205` `load`: about twenty conditional entries encode the cross-setting rules, with the table they depend on 175 lines below. Two seats named it.
- Shape: `bin/chunk_pr/main.py:398` `epic_opened`: a chain of `x = prev if isinstance(prev, Failure) else f(prev)` hides the success path.
- Shape: `bin/agent_cycle/run.py:250` `close`, with `:33` `Cycle`: one long conditional decides the archived outcome, and the dataclass has 17 fields.
- Shape: `bin/chunk_driver/this_loop.py:12` `Loop`, with `bin/chunk_driver/cycle_start.py:96` `cycle_of`: `Loop` is built per chunk and serves do-epic too, as the `loop_`-prefixed packages do; `cycle_of` takes ten keyword arguments.
- Shape: `bin/rule_hook/rules.py:27` `RULES`: each rule's prose is one very long string, which hides the table's structure.
### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.
@@ -454,7 +468,7 @@ Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the
### 323. Count a release review as landed once its pull request has merged, whatever its commits are titled.
`release_reviewed` in `bin/release_plan/release_standing.py` counts a release review only by a commit titled `Release review of <release>` on the default branch. In a replay of archived interrupts (`judge-field-trials/`), in two projects whose release review had merged, the default branch held no such commit, so `chunk-preflight` and routing read ReviewDue, and the next loop would run the release review again. `skills/larv-review/SKILL.md` opens the review's branch with an empty commit of that title, but a worker may skip it, and a rebase or squash merge, which `chunk-pr` uses where the forge allows no merge commit, may drop it. Detect the review by something every merge method keeps, and check the fix against both projects' histories. Until then the judge keeps `release_ready` (docs/decisions.md → `routing: loop-claude reads the items a chunk takes …`).
`reviewed_releases` in `bin/release_plan/release_standing.py` counts a release review only by a commit titled `Release review of <release>` on the default branch. In a replay of archived interrupts (`judge-field-trials/`), in two projects whose release review had merged, the default branch held no such commit, so `chunk-preflight` and routing read ReviewDue, and the next loop would run the release review again. `skills/larv-review/SKILL.md` opens the review's branch with an empty commit of that title, but a worker may skip it, and a rebase or squash merge, which `chunk-pr` uses where the forge allows no merge commit, may drop it. Detect the review by something every merge method keeps, and check the fix against both projects' histories. Until then the judge keeps `release_ready` (docs/decisions.md → `routing: loop-claude reads the items a chunk takes …`).
### 342. Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.
@@ -805,6 +819,10 @@ Today a Jira detail edited in one line, or a Confluence record with one entry ap
The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file.
### 551. Run each mutation tool of `mutate-changes` in the folder that holds its module file, so a repo with `go.mod` below the top gets its Go lines mutated.
In a repo whose `go.mod` is in a subfolder, `mutate-changes` reported 0 Go mutants for a branch that changed Go code, and ran mutmut on a folder of integration tests whose tests reach no code in the repo. It also left root-owned `.mutate-changes-*` folders in the checkout. By hand, Gremlins v0.6.0 worked when run in the module's folder with `git config --global diff.relative true` and `gremlins unleash --diff <base>` without a path. Find each module file (`go.mod`, `pyproject.toml`, `composer.json`) and run the tool there with the diff made relative, skip a Python folder no test imports from, and remove the scratch folders as the user who owns the checkout.
### 447. Stop a headless claude call that runs past a time limit, and report it as a failure, so a hung judge or stuck check can't hold the loop.
Every headless claude that `claude_reply` runs, the judge's and the stuck check's included, runs without a time limit, and the stuck check runs while the worker's own claude waits for its output to be read. A call that hangs holds the loop, and the worker with it, until a person notices. Found by item 422's stability review.