Merge remote-tracking branch 'origin/main' into item-531
CI / tests (pull_request) Has been cancelled

# Conflicts:
#	CHANGELOG.md
#	README.md
#	docs/reading-cost.md
This commit is contained in:
2026-11-25 23:46:16 +01:00
28 changed files with 1175 additions and 101 deletions
+7 -1
View File
@@ -2,6 +2,8 @@
## Unreleased
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for a release later than the last cut.
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself.
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
- This repo documents its own `task-bench` command in the README → Test, with `task-bench-image/Dockerfile`, an image that holds pytest, git and tmux, so each scoring run in `larv-review` benches claude-config and records its figures.
@@ -11,11 +13,15 @@
- `task-bench --tasks data-sources` benches adding a data source: Haiku gets a made-up register that the task's seeded `generate-register` writes, and acceptance tests check the importer, the data and whatever else the spec asks.
- `task-bench --tasks features` has Haiku build features instead of fixing planted bugs: each folder in the folder the project's config names as the new optional `bench-tasks` holds a `spec.md`, a `reference.patch` and acceptance tests Haiku never sees. A feature counts only where those tests fail before it is built and pass with the reference patch, at the base and at the head; the report names each feature passed over and why.
- A bench started with `task-bench --record-figures` appends its figures over every bug to the comprehension history once it finishes, and a scoring run in `larv-review` starts the project's bench that way where its README documents a `task-bench` command. The figures are a report beside the panel's scores: none blocks a merge.
- `task-bench`'s table prints the mean of the bugs' own head/base changes as its All change, in place of the change of the two All rows' medians, which swung up to three times as far in tokens. The All rows per side stay, so the change row is no longer their difference, and a change from before 0.15.1 can't be compared with one from after it.
- `task-bench`'s table prints the mean of the bugs' own head/base changes as its All change, in place of the change of the two All rows' medians, which swung up to three times as far in tokens. The All rows per side stay, so the change row is no longer their difference, and a change from before 0.16.0 can't be compared with one from after it.
- `task-bench` now stops with a Failure on a run whose final result says `terminal_reason: "api_error"`, even where it holds no `api_error_status`, so a token the API refuses no longer lets the bench run on for hours with empty runs.
- `task-bench`'s `--help` now says how far a bench of a commit against itself swings, in 19 cases of 20, with the default 5 bugs and 5 runs, and that a Gremlins run on a large project needs 16 GB of memory.
- When `task-bench` can't copy, read or write a file in the middle of a bench, it now names that file and still prints the table of the runs that finished, where 0.15.0 lost them all behind `could not write under <folder>`.
## 0.15.1
- `do-epic` and `todo-item edit` save an issue's scores in a Jira epic again. Jira refuses an edit that holds only issue properties, so 0.15.0 posted the comment with the scores but lost the scores themselves, and scored the issue again on the next run; each score now goes through the issue property's own endpoint.
## 0.15.0
- `task-bench` writes `digest.md`, with each bug's decoys and up to two traces of its runs, and `task-bench gather` starts a claude on the project's rung that files a plan item for each place the digest shows to be hard, then removes the bench's folder. Each bench removes the folders earlier benches left, and `compress-archives` leaves lock files alone.
+11 -3
View File
@@ -198,6 +198,14 @@ bin/deploy-release --cut
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first:
```sh
bin/deploy-release --cut-patch 794ce37..1aa2367
```
It applies only those commits on the newest tag, tests them with `ci.sh`, tags and pushes the release, then merges the tag back into `main` through a pull request and moves `~/.claude` to it. A patch skips the release review. Until it is cut, `chunk-preflight` calls the patch's release review due, and loop-claude would run it. `deploy-release --help` lists the steps.
## Tools
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. The tools are listed in alphabetical order, and the packages under `bin/` follow under their own heading.
@@ -206,7 +214,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
- `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily.
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
- `deploy-release [--cut | --cut-patch <commits>] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, and with `--cut-patch`, a patch release of only the commits named, as Release says.
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. It plans no issue your team filed a sub-task under: those sub-tasks run instead, each under a label of its own, and your team closes the issue. Then, where two or more issues may start, it scores each of them that holds no scores, and moves the issues that do-epic itself filed into order of score on the board. An open issue runs once a label names its repo or marks it as Claude's, in order of score, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. `do-epic <EPIC-KEY> --dry-run` prints what `do-epic <EPIC-KEY>` would write to Jira and which chunks it would start, and does neither; run it before the first real run on a team's epic. `--help` lists what it prints and leaves out. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
- `do-epic-e2e` runs `do-epic` against a sandbox epic on a real Jira site, as Test says.
- `judge-replay <model> [--offline]` replays loop-claude's judge on archived verdicts of the projects run on the model. It prints what each rung a review climbs to misses, and the lowest rung below those that returns every verdict, as each candidate above it does. With `--offline` it doesn't call a judge: it counts what a "?" rule, a decision table and a classifier trained on the archive decide of each verdict's kind from the worker's final message, and how many interrupts each misses. `judge-replay --help` states both replays.
@@ -228,7 +236,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go and Python 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, 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.
- `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.
@@ -278,7 +286,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go and Python 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.
- `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.
- `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.
+12
View File
@@ -154,6 +154,18 @@ def project_of(key: str) -> str:
return key.rpartition("-")[0]
def edit_issue(site: str, key: str, body: dict[str, typing.Any], authorization: str, http: Http) -> None | Failure:
"""Sends body, an edit of the issue named key, and returns None, or the Failure of the request that failed. An edit that holds fields or update goes in one request, with its properties. Jira refuses an edit that holds neither, so such an edit sets each property through the property's own endpoint, one request each, and stops at the first that fails."""
if "fields" in body or "update" in body:
answer = http("PUT", f"{site}/rest/api/3/issue/{key}", authorization, body)
return answer if isinstance(answer, Failure) else None
for entry in body.get("properties", []):
answer = http("PUT", f"{site}/rest/api/3/issue/{key}/properties/{entry['key']}", authorization, entry["value"])
if isinstance(answer, Failure):
return answer
return None
def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> str | None:
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
+40
View File
@@ -107,5 +107,45 @@ class TheRefusalOfAnIssueType(unittest.TestCase):
self.assertEqual(self.refusal("Bug", wrong), "Jira answered ABC's issue types in a shape its REST API version 3 doesn't document")
class AnIssueEdit(unittest.TestCase):
def setUp(self) -> None:
self.calls: list[tuple[str, str, object]] = []
self.answer: object = None
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, body))
return self.answer
def edit(self, body: dict[str, object]) -> None | Failure:
return jira.edit_issue("https://acme.atlassian.net", "ABC-1", body, "Basic x", self.http)
def test_sends_fields_update_and_properties_in_one_request(self):
body = {"fields": {"summary": "Count."}, "update": {"labels": [{"add": "security"}]}, "properties": [{"key": "plan", "value": {"L": 2}}]}
self.assertIsNone(self.edit(body))
self.assertEqual(self.calls, [("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1", body)])
def test_sets_each_property_of_an_edit_without_fields_or_update_through_the_property_endpoint(self):
# Jira's edit refuses such a body: "one of 'fields' or 'update' required".
self.assertIsNone(self.edit({"properties": [{"key": "plan", "value": {"L": 2}}, {"key": "seen", "value": True}]}))
self.assertEqual(self.calls, [
("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/plan", {"L": 2}),
("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/seen", True),
])
def test_an_answer_jira_sends_on_success_counts_as_success(self):
self.answer = {"id": "10001"}
self.assertIsNone(self.edit({"fields": {"summary": "Count."}}))
def test_an_empty_edit_doesnt_send_a_request(self):
self.assertIsNone(self.edit({}))
self.assertEqual(self.calls, [])
def test_a_request_jira_refuses_is_its_failure_and_stops_the_later_properties(self):
self.answer = Failure("Jira answered 503")
self.assertEqual(self.edit({"fields": {"summary": "Count."}}), Failure("Jira answered 503"))
self.assertEqual(self.edit({"properties": [{"key": "plan", "value": {}}, {"key": "seen", "value": True}]}), Failure("Jira answered 503"))
self.assertEqual(len(self.calls), 2)
if __name__ == "__main__":
unittest.main()
+56 -21
View File
@@ -2,6 +2,7 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import contextlib
import pathlib
import shutil
import sys
@@ -16,12 +17,15 @@ from failure import Failure
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from forge.commands import forge_of, runner
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
from plan.release import newest_tag, Release, tagged, UNRELEASED_HEADING, version
from forge import pulls
from deploy_release import release_pull
from project_config import templates
CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version."
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
if isinstance(same := same_origin(clone, checkout), Failure):
@@ -37,10 +41,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
if isinstance(release, Failure):
return release
named = version(release)
title, tag = f"Cut release {named}", f"v{named}"
if isinstance(patched := patch_refusal(clone, ref, release), Failure):
return patched
title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}"
merged = commit_titled(title, ref, clone)
if merged is None:
landed = land(clone, ref, named, title, sleep)
build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep)
if isinstance(landed, Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
@@ -58,13 +65,24 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
delete_release_branch(clone, f"release-{named}")
delete_release_branch(clone, branch)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None:
"""A Failure where release is a patch of the newest tag ref holds: a cut of all of ref would ship its other work under a patch number."""
tag = newest_tag(clone, merged_into=ref)
if isinstance(tag, Failure):
return tag
cut_release = tagged(tag)
if cut_release is not None and release[:2] == cut_release[:2]:
return Failure(f"{version(release)} is a patch of {tag}: cut it with --cut-patch <commits>, so it holds only the fix and not all of {ref}")
return None
def said(step: str) -> None:
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
print(f"deploy-release: {step}", file=sys.stderr)
@@ -100,13 +118,13 @@ def drop_unpushed_cut_tags(clone: str) -> Failure | None:
def same_origin(clone: str, checkout: str) -> Failure | None:
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so --cut never cuts another project."""
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so a cut never cuts another project."""
urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)]
failed = next((url for url in urls if isinstance(url, Failure)), None)
if failed is not None:
return failed
if urls[0] != urls[1]:
return Failure(f"run --cut in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
return Failure(f"run deploy-release in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
return None
@@ -116,8 +134,8 @@ def clone_plan(clone: str) -> FilePlan:
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased."""
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
if isinstance(plan.plan, Failure):
@@ -129,6 +147,8 @@ def ready_release(clone: str, ref: str) -> Release | Failure:
return Failure("todo.md names no release after the last one cut")
case Next(release=release) if release is not None:
return Failure(f"release {version(release)} still holds items in todo.md")
case ReviewDue(release=release) if not review and release is not None:
return release
case ReviewDue(release=release):
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
case Unplanned():
@@ -150,12 +170,14 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[float], None]) -> Failure | None:
"""Push the branch release-<named> with the cut commit and open its pull request, where an earlier run hasn't; then wait for its checks and merge it."""
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None]) -> Failure | None:
"""Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it.
build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet."""
url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure):
return url
on, run, branch, base = forge_of(url), runner(clone), f"release-{named}", ref.removeprefix("origin/")
on, run, base = forge_of(url), runner(clone), ref.removeprefix("origin/")
head = branch_head(branch, clone)
if isinstance(head, Failure):
return head
@@ -164,7 +186,7 @@ def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[f
return behind
if head is None or behind:
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure):
if isinstance(pushed := build(head), Failure):
return pushed
said(f"pushed the branch {branch}")
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
@@ -172,7 +194,7 @@ def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[f
return head
number = pulls.open_pull(on, branch, head, run)
if number is None:
if isinstance(created := release_pull.create_pull(on, branch, base, title, run), Failure):
if isinstance(created := release_pull.create_pull(on, branch, base, title, body, run), Failure):
return created
number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, str):
@@ -206,11 +228,10 @@ def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure:
def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, replacing: str | None) -> Failure | None:
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own so the clone's checkout stays as it is, and push it as branch: a new one, or in place of replacing, the commit origin's branch points at."""
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "cut"
try:
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
return added
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own, and push it as branch, replacing the commit origin's branch points at, where there is one."""
with scratch_worktree(clone, ref) as worktree:
if isinstance(worktree, Failure):
return worktree
changelog = worktree / "CHANGELOG.md"
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
@@ -218,9 +239,23 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
changelog.write_text(renamed)
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
return committed
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
return pushed if isinstance(pushed, Failure) else None
return push_branch(worktree, branch, replacing)
@contextlib.contextmanager
def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]:
"""A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it."""
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "worktree"
try:
added = git("worktree", "add", "--quiet", "--detach", str(worktree), at, cwd=clone)
yield added if isinstance(added, Failure) else worktree
finally:
git("worktree", "remove", "--force", str(worktree), cwd=clone)
shutil.rmtree(worktree.parent, ignore_errors=True)
def push_branch(worktree: pathlib.Path, branch: str, replacing: str | None) -> Failure | None:
"""Push worktree's HEAD to origin as branch: a new one, or in place of replacing, only while origin's branch still points at it."""
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
return pushed if isinstance(pushed, Failure) else None
+37 -8
View File
@@ -1,6 +1,6 @@
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release.
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release, and with --cut-patch, a patch release of only the commits named.
usage: deploy-release [--cut] [<checkout>]
usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]
<checkout> defaults to ~/.claude. The tool fetches origin's tags and checks out the newest v* tag,
detached, so the checkout holds only what a release holds. Development happens in another clone,
@@ -18,7 +18,9 @@ memory, stay as they are.
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
refuses without changing anything, unless that release holds no item in todo.md, its release review has
landed and changes are unreleased. The release names the version; the tool doesn't choose one.
landed and changes are unreleased. The release names the version; the tool doesn't choose one. It also refuses a
release that is a patch of the newest tag, such as 0.15.2 after v0.15.1, since it would ship all of main: cut that
with --cut-patch.
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
@@ -35,6 +37,28 @@ Where a step fails it stops, exit 1, with git's or the forge's reason, and leave
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
move stopped, fix what it names and run a bare deploy-release.
--cut-patch <commits> runs in the development clone too, for a fix that must ship before main's other unreleased work. It
cuts the newest tag's next patch release, holding only <commits> on top of the tag. <commits> is a range as git log reads
it, such as 794ce37..1aa2367, which leaves out 794ce37 as git's `..` does, or one commit, which it reads as that commit
alone. Name the commits the fix's chunk merged, including the one that finished its item: the entries that commit added
under ## Unreleased in CHANGELOG.md become the release's. Each commit must be on origin's main and not in the tag. Merge
commits are left out, and so are the commits a merge of main brought into the range. todo.md must name the release and
file no item under it; a patch skips the release review. Cut it as soon as the fix merges: until then chunk-preflight calls
the patch's release review due, and loop-claude would run it. It refuses without changing anything where any of that
doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from main's history.
1. It says on stderr which commits the release ships.
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
3. It runs ci.sh on that commit, and stops where it fails, before anything is tagged.
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
release-<version> and a pull request as --cut does. Then it checks main holds the tag.
6. It moves <checkout> to the tag as above, and ends stdout as --cut does.
A rerun takes a tag origin holds already, once it checks the tag lists the same changelog entries, and the merge-back's open
pull request. Once the merge-back has merged, the release is cut: where only the move stopped, run a bare deploy-release.
"""
import os
import pathlib
@@ -42,6 +66,7 @@ import sys
import time
from deploy_release.cut import cut
from deploy_release.patch import cut_patch
from deploy_release.deploy import deploy
from failure import Failure
@@ -50,13 +75,17 @@ def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
cutting = argv[:1] == ["--cut"]
rest = argv[1:] if cutting else argv
if len(rest) > 1 or rest[:1] and rest[0].startswith("-"):
print("deploy-release: usage: deploy-release [--cut] [<checkout>]", file=sys.stderr)
cutting, patching = argv[:1] == ["--cut"], argv[:1] == ["--cut-patch"]
commits = argv[1] if patching and len(argv) > 1 else None
rest = argv[2:] if patching else argv[1:] if cutting else argv
if len(rest) > 1 or rest[:1] and rest[0].startswith("-") or patching and (commits is None or commits.startswith("-")):
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
return 1
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
if commits is not None:
moved = cut_patch(os.getcwd(), checkout, commits, time.sleep)
else:
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
return 1
+235
View File
@@ -0,0 +1,235 @@
"""`deploy-release --cut-patch <commits>`: cut the newest tag's next patch release holding only the commits named, test it with ci.sh, tag it, merge the tag back into main through a pull request, then move ~/.claude to it.
A rerun takes the tag an earlier run pushed, once it checks the tag lists the same changelog entries, and the merge-back's open pull request.
"""
import dataclasses
import pathlib
import re
import subprocess
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
from deploy_release.deploy import deploy
from failure import Failure
from forge.commands import forge_of
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
LEFT_AS_TAGGED = ("CHANGELOG.md", "docs/comprehension-history.md", "docs/reading-cost.md", "todo.md")
MERGE_BACK_BODY = "Merge the patch release's tag into main, keeping main's files, and list its changelog entries under its version."
@dataclasses.dataclass(frozen=True)
class Patch:
"""A patch release ready to cut."""
# origin's default branch, as default_ref names it.
ref: str
# The newest tag ref holds, which the patch goes on top of.
base: str
# The patch's version, the base's next patch.
named: str
# The commits the patch ships, oldest first.
commits: list[str]
# The CHANGELOG.md entries the commits added under ref's ## Unreleased, in ref's order.
entries: list[str]
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit."""
patch = planned(clone, checkout, commits)
if isinstance(patch, Failure):
return patch
for commit in patch.commits:
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
tag, branch = f"v{patch.named}", f"release-{patch.named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
if isinstance(made, Failure):
return made
build = lambda replacing: push_merge_back(clone, patch, replacing)
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
return fetched
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
delete_release_branch(clone, branch)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
return f"{moved}\n\nDone: {tag} is cut and pushed, and {checkout} is on it."
def planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
"""The patch commits names, once the clone, the plan and the commits allow it; a Failure saying why not, before anything changes on origin."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
url = git("config", "--get", "remote.origin.url", cwd=clone)
if isinstance(url, Failure):
return url
if forge_of(url) == "gh":
return Failure("--cut-patch merges the tag back fast-forward, which GitHub can't, since its rebase merge drops the merge commit: cut the patch by hand there")
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
return fetched
if isinstance(dropped := drop_unpushed_cut_tags(clone), Failure):
return dropped
ref = default_ref(cwd=clone)
if isinstance(ref, Failure):
return ref
base = newest_tag(clone, merged_into=ref)
if isinstance(base, Failure):
return base
cut = tagged(base)
if base is None or cut is None:
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
named = version((cut[0], cut[1], cut[2] + 1))
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
if version(release) != named:
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
picked = patch_commits(clone, ref, base, commits)
if isinstance(picked, Failure):
return picked
entries = changelog_entries(clone, ref, picked)
return entries if isinstance(entries, Failure) else Patch(ref, base, named, picked, entries)
def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | Failure:
"""The commits commits names, oldest first: merge commits, and the commits a merge brought into a range, are left out. A Failure where one is missing from ref or the tag base already holds it."""
listed = git("rev-list", "--reverse", "--no-merges", "--first-parent", commits if ".." in commits else f"{commits}^!", "--", cwd=clone)
if isinstance(listed, Failure):
return listed
picked = listed.split()
if not picked:
return Failure(f"{commits} names no commit that isn't a merge: write a range as <older>..<newer>")
for commit in picked:
if isinstance(git("merge-base", "--is-ancestor", commit, ref, cwd=clone), Failure):
return Failure(f"{commit[:12]} isn't on {ref}: merge it there first")
if not isinstance(git("merge-base", "--is-ancestor", commit, base, cwd=clone), Failure):
return Failure(f"{commit[:12]} is in {base} already")
return picked
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
added: set[str] = set()
for commit in commits:
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
if isinstance(diff, Failure):
return diff
added |= {line[1:] for line in diff.splitlines() if line.startswith("+- ")}
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
def tagged_entries(clone: str, patch: Patch) -> Failure | None:
"""A Failure unless the tag an earlier run pushed lists patch's entries under its version, so a rerun with other commits doesn't merge back entries the tag doesn't ship."""
changelog = git("show", f"v{patch.named}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
listed = [line for line in section(changelog, re.escape(patch.named)) or [] if line.strip()]
if listed != patch.entries:
return Failure(f"origin's v{patch.named} lists other changelog entries under ## {patch.named} than the commits named added under ## Unreleased. The tag lists:\n" + "\n".join(listed) + "\nThe commits added:\n" + "\n".join(patch.entries))
return None
def tag_patch(clone: str, patch: Patch) -> Failure | None:
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
with scratch_worktree(clone, patch.base) as worktree:
if isinstance(worktree, Failure):
return worktree
for commit in patch.commits:
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref), Failure):
return tested
said("ci.sh passed")
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
return made
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
return None
def headed(changelog: str, entries: list[str], named: str) -> str:
"""changelog with a ## named section holding entries before its first ## section, or at its end where it has none."""
added = f"## {named}\n\n" + "\n".join(entries) + "\n"
first = re.search(r"^## ", changelog, flags=re.M)
if first is None:
return changelog.rstrip() + "\n\n" + added
return changelog[:first.start()] + added + "\n" + changelog[first.start():]
def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) -> Failure | None:
"""Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the base tag's files differ from commit's parent."""
diff = git("diff", "--binary", f"{commit}^", commit, "--", ".", *(f":(exclude){path}" for path in LEFT_AS_TAGGED), cwd=clone)
if isinstance(diff, Failure):
return diff
if not diff:
return None
patch_file = worktree.parent / "commit.patch"
patch_file.write_text(diff)
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), cwd=str(worktree)), Failure):
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
return Failure(
f"{commit[:12]} ({'' if isinstance(subject, Failure) else subject.strip()}) doesn't apply on {patch.base}: {applied.reason}. "
f"Cut the patch by hand: on {patch.base}, apply the fix and add a ## {patch.named} section to CHANGELOG.md, commit that titled `Cut release {patch.named}`, "
f"tag it v{patch.named}, annotated with that title, and push the tag. A rerun with the same commits then merges it back and deploys it, "
f"where the section holds exactly these lines:\n" + "\n".join(patch.entries)
)
return None
def run_ci(worktree: pathlib.Path, ref: str) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
if not (worktree / "ci.sh").exists():
return Failure("the patch holds no ci.sh to test it with")
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
if ran.returncode == 0:
return None
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
return Failure(f"ci.sh failed on the patch, so nothing is tagged. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure | None:
"""On origin's main, merge the patch's tag keeping main's files, move its entries from ## Unreleased to a ## <version> section below ## Unreleased, and push that as the branch release-<version>, replacing the commit origin's branch points at, where there is one."""
with scratch_worktree(clone, patch.ref) as worktree:
if isinstance(worktree, Failure):
return worktree
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, f"release-{patch.named}", replacing)
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section."""
lines = changelog.split("\n")
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
kept = [line for line in lines[start + 1:end] if line not in entries]
while kept and not kept[-1].strip():
kept.pop()
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])
+3 -3
View File
@@ -6,10 +6,10 @@ from failure import Failure
from forge.commands import Forge, gitea, Run
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
def create_pull(forge: Forge, branch: str, base: str, title: str, body: str, run: Run) -> Failure | None:
described = ["--body" if forge == "gh" else "--description", body]
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *described])
return created if isinstance(created, Failure) else None
+213 -2
View File
@@ -10,6 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from test_env import isolated_env
from deploy_release import patch
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
@@ -248,7 +249,7 @@ class Cut(unittest.TestCase):
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
self.clone = self.temp / "claude-config"
self.git(self.temp, "clone", "-q", str(self.origin), str(self.clone))
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Start")
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0"), "tool.txt": "broken\n", "ci.sh": "exit 0\n"}, "Start")
self.git(self.clone, "tag", "-a", "v0.1.0", "-m", "Cut release 0.1.0")
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0")}, "Ship item 1")
self.git(self.clone, "commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
@@ -469,7 +470,196 @@ class Cut(unittest.TestCase):
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
def test_takes_no_option_but_cut(self):
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
self.commit({"feature.txt": "new\n"}, "Add a feature")
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
base = self.git(self.clone, "rev-parse", "HEAD").strip()
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n", **(fix or {})}, "Fix item 3")
head = self.git(self.clone, "rev-parse", "HEAD").strip()
self.git(self.clone, "push", "-q", "origin", "main")
return f"{base}..{head}"
def cut_patch(self, *commits: str) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), "--cut-patch", *commits, str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
def test_cuts_a_patch_of_the_newest_tag_holding_only_the_named_commits_then_merges_the_tag_back_and_deploys_it(self):
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("cat-file", "-t", "v0.1.1").strip(), "tag", "the tag is annotated")
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.1.1").strip(), "Cut release 0.1.1")
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "v0.1.1").strip(), "Cut release 0.1.1")
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}~1"), self.origin_git("rev-parse", "v0.1.0^{commit}"))
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
self.assertEqual(self.origin_git("show", "v0.1.1:CHANGELOG.md"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(self.origin_git("show", "v0.1.1:todo.md"), self.origin_git("show", "v0.1.0:todo.md"))
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Merge release 0.1.1 into main")
self.assertEqual(self.origin_git("show", "main:CHANGELOG.md"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
self.assertEqual(self.origin_git("show", "main:feature.txt"), "new\n")
self.assertIn(["tea", "pulls", "create", "--head", "release-0.1.1", "--base", "main"], [call[:7] for call in self.forge_state()["calls"]])
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
self.assertIn("Done: v0.1.1 is cut and pushed", ran.stdout)
def test_takes_one_commit_as_the_patch(self):
head = self.plan_patch().split("..")[1]
ran = self.cut_patch(head)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
def test_refuses_before_any_change_where_the_plan_names_no_patch_release(self):
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix tool.txt")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("0.1.1", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
self.assertEqual(self.forge_state()["pulls"], [])
def test_refuses_before_any_change_while_the_patch_release_holds_an_item(self):
self.plan_patch()
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=4, release="0.1.1")}, "File item 4")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD~1")
self.assertEqual(ran.returncode, 1)
self.assertIn("still holds items", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_skips_the_release_review_a_patch_would_otherwise_wait_for(self):
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
self.git(self.clone, "push", "-q", "--force", "origin", "main")
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
def test_refuses_a_commit_the_tag_holds(self):
self.plan_patch()
ran = self.cut_patch("v0.1.0")
self.assertEqual(ran.returncode, 1)
self.assertIn(self.git(self.clone, "rev-parse", "v0.1.0^{commit}")[:12] + " is in v0.1.0 already", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_refuses_a_commit_origins_main_doesnt_hold(self):
self.plan_patch()
self.commit({"tool.txt": "local\n"}, "Unpushed")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn(self.git(self.clone, "rev-parse", "HEAD")[:12] + " isn't on origin/main", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_leaves_out_the_commits_a_merge_of_main_brought_into_the_chunk(self):
self.commit({"todo.md": TODO + ROW.format(id=2, release="0.3.0") + ROW.format(id=3, release="0.1.1")}, "File item 3")
base = self.git(self.clone, "rev-parse", "HEAD").strip()
self.commit({"feature.txt": "new\n"}, "Add a feature")
self.git(self.clone, "switch", "-q", "-c", "chunk", base)
self.git(self.clone, "merge", "-q", "--no-ff", "-m", "Sync with main", "main")
self.commit({"tool.txt": "fixed\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0"), "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3")
head = self.git(self.clone, "rev-parse", "HEAD").strip()
self.git(self.clone, "switch", "-q", "main")
self.git(self.clone, "merge", "-q", "--ff-only", "chunk")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch(f"{base}..{head}")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertNotIn("feature.txt", self.origin_git("ls-tree", "--name-only", "v0.1.1"))
self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n")
def test_says_which_commits_the_patch_ships_before_it_applies_them(self):
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("deploy-release: ships " + self.git(self.clone, "log", "-1", "--format=%h %s", "HEAD").strip(), ran.stderr)
self.assertNotIn("Add a feature", ran.stderr)
def test_refuses_on_a_github_origin_whose_merge_would_drop_the_tag_from_main(self):
commits = self.plan_patch()
self.use_github()
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 1)
self.assertIn("GitHub", ran.stderr)
self.assertEqual(self.forge_state()["calls"], [])
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_a_rerun_merges_back_and_deploys_a_patch_cut_by_hand_as_the_refusal_says(self):
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
commits = self.plan_patch()
refused = self.cut_patch(commits)
self.assertEqual(refused.returncode, 1)
self.assertIn("exactly these lines:\n- Fixed.", refused.stderr)
self.git(self.clone, "switch", "-q", "--detach", "v0.1.0")
self.commit({"tool.txt": "fixed\n", "CHANGELOG.md": "# Changelog\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}, "Cut release 0.1.1")
self.git(self.clone, "tag", "-a", "v0.1.1", "-m", "Cut release 0.1.1")
self.git(self.clone, "push", "-q", "origin", "v0.1.1")
self.git(self.clone, "switch", "-q", "main")
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.1.1")
def test_a_rerun_refuses_a_pushed_tag_cut_from_other_commits(self):
self.set_checks("failure")
commits = self.plan_patch()
self.assertEqual(self.cut_patch(commits).returncode, 1)
self.commit({"tool.txt": "fixed twice\n", "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n- Fixed twice.\n\n## 0.1.0\n\n- First.\n"}, "Fix item 3 again")
self.git(self.clone, "push", "-q", "origin", "main")
self.set_checks("success")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("The tag lists:\n- Fixed.\nThe commits added:\n- Fixed twice.", ran.stderr)
self.assertNotIn("Fixed twice", self.origin_git("show", "main:CHANGELOG.md").split("## 0.1.0")[0].split("## Unreleased")[0])
def test_refuses_commits_that_add_no_changelog_entry_under_unreleased(self):
self.plan_patch()
self.commit({"tool.txt": "fixed again\n"}, "Fix more")
self.git(self.clone, "push", "-q", "origin", "main")
ran = self.cut_patch("HEAD")
self.assertEqual(ran.returncode, 1)
self.assertIn("## Unreleased", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_stops_before_tagging_where_ci_fails_on_the_patch(self):
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite failed >&2\nexit 1\n"}))
self.assertEqual(ran.returncode, 1)
self.assertIn("ci.sh", ran.stderr)
self.assertIn("the suite failed", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.1.1"), "")
self.assertEqual(self.forge_state()["pulls"], [])
def test_stops_naming_the_commit_that_does_not_apply_on_the_tag(self):
self.commit({"tool.txt": "half fixed\n"}, "Change tool.txt on main")
ran = self.cut_patch(self.plan_patch())
self.assertEqual(ran.returncode, 1)
self.assertIn("Fix item 3", ran.stderr)
self.assertIn("v0.1.0", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_a_rerun_after_a_failed_merge_back_check_keeps_the_pushed_tag_and_merges_back(self):
self.set_checks("failure")
commits = self.plan_patch()
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 1)
tagged = self.origin_git("rev-parse", "v0.1.1^{commit}")
self.set_checks("success")
ran = self.cut_patch(commits)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertEqual(self.origin_git("rev-parse", "v0.1.1^{commit}"), tagged)
self.origin_git("merge-base", "--is-ancestor", "v0.1.1", "main")
def test_plain_cut_refuses_a_patch_release_and_names_cut_patch(self):
self.plan_patch()
ran = self.cut()
self.assertEqual(ran.returncode, 1)
self.assertIn("--cut-patch", ran.stderr)
self.assertEqual(self.forge_state()["pulls"], [])
def test_cut_patch_needs_its_commits(self):
ran = subprocess.run([sys.executable, str(TOOL), "--cut-patch"], capture_output=True, cwd=self.clone, env=self.env, text=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("usage", ran.stderr)
self.assertEqual(self.forge_state()["calls"], [])
def test_refuses_an_option_it_does_not_know(self):
ran = subprocess.run([sys.executable, str(TOOL), "--cut", "--force"], capture_output=True, cwd=self.clone, env=self.env, text=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("usage", ran.stderr)
@@ -488,5 +678,26 @@ class Cut(unittest.TestCase):
class PatchChangelog(unittest.TestCase):
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
def test_heads_the_tags_changelog_with_the_patchs_section(self):
self.assertEqual(patch.headed("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed.", "- Also."], "0.1.1"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n- Also.\n\n## 0.1.0\n\n- First.\n")
def test_appends_the_patchs_section_to_a_changelog_without_sections(self):
self.assertEqual(patch.headed("# Changelog\n\nFor Linux and macOS X\n\n", ["- Fixed."], "0.1.1"), "# Changelog\n\nFor Linux and macOS X\n\n## 0.1.1\n\n- Fixed.\n")
def test_moves_the_patchs_entries_from_unreleased_to_a_section_after_it(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- First.\n")
def test_leaves_an_older_section_entry_that_reads_the_same(self):
changelog = "# Changelog\n\n## Unreleased\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n"
self.assertEqual(patch.moved_entries(changelog, ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n\n## 0.1.0\n\n- Fixed.\n")
def test_puts_the_section_last_where_unreleased_is_the_last_section(self):
self.assertEqual(patch.moved_entries("# Changelog\n\n## Unreleased\n\n- Fixed.\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## Unreleased\n\n## 0.1.1\n\n- Fixed.\n")
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -7,7 +7,7 @@ from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from plan_store.jira_epic import BLOCKS, FILED_BY, 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, 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 atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped
from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label
from failure import Failure
from do_epic.backend.jira_status import moved_by, moved_to
@@ -195,7 +195,7 @@ class JiraEpic:
posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body})
if isinstance(posted, Failure):
return Failure(f"cannot comment on {key} to tell its team the scores: {posted.reason}")
put = self.http("PUT", f"{self.epic.site}/rest/api/3/issue/{key}", authorization, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]})
put = edit_issue(self.epic.site, key, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]}, authorization, self.http)
return Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: {put.reason}") if isinstance(put, Failure) else None
def start_issue(self, key: str) -> str | None | Failure:
+7 -6
View File
@@ -119,12 +119,13 @@ class FakeJira:
assert isinstance(body, dict)
self.comments.setdefault(str(held["key"]), []).append(body["body"])
return {"id": "1"}
if method == "PUT" and (held := next((issue for issue in self.issues if url.startswith(f"{ISSUES}/{issue['key']}/properties/")), None)):
held.setdefault("properties", {})[url.rpartition("/")[2]] = body # type: ignore[attr-defined]
return None
if method == "PUT" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}"), None)):
assert isinstance(body, dict)
if "properties" in body:
[entry] = body["properties"]
held.setdefault("properties", {})[entry["key"]] = entry["value"] # type: ignore[attr-defined]
return None
if "fields" not in body and "update" not in body:
return Failure("Jira answered 400: one of 'fields' or 'update' required")
added = [change["add"] for change in body["update"]["labels"]]
held["fields"]["labels"] = sorted({*held["fields"]["labels"], *added}) # type: ignore[index]
return None
@@ -286,9 +287,9 @@ class Jira(Case):
self.jira.answers[("POST", f"{ISSUES}/{key}/comment")] = Failure("Jira answered 503")
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"cannot comment on {key} to tell its team the scores: Jira answered 503"))
del self.jira.answers[("POST", f"{ISSUES}/{key}/comment")]
self.jira.answers[("PUT", f"{ISSUES}/{key}")] = Failure("Jira answered 503")
self.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")] = Failure("Jira answered 503")
self.assertEqual(store.set_scores(key, scores, "", "Scored."), Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: Jira answered 503"))
del self.jira.answers[("PUT", f"{ISSUES}/{key}")]
del self.jira.answers[("PUT", f"{ISSUES}/{key}/properties/plan-item")]
# No scores were set while the comment failed, so the issue is still scored once Jira answers.
self.assertIsNone(store.set_scores(key, scores, "", "Scored."))
+13 -5
View File
@@ -32,11 +32,10 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return scratch
try:
pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8")
relative = os.path.relpath(scratch, top)
ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES}
out = cargo_mutants_out(top, scratch, ["--in-diff", os.path.join(os.path.relpath(scratch, top), "branch.diff")], run, jobs)
if isinstance(out, Failure):
return out
outcomes = {outcome: outcome_lines(out / f"{outcome}.txt") for outcome in CARGO_OUTCOMES}
except OSError as failure:
return Failure(f"could not hand cargo-mutants the diff or read its outcomes in {scratch}: {failure}")
finally:
@@ -45,6 +44,15 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return [f"cargo-mutants: {sum(map(len, outcomes.values()))} mutants on changed lines, {len(uncaught)} not caught.", *uncaught]
def cargo_mutants_out(top: str, scratch: str, arguments: list[str], run: Run, jobs: int) -> pathlib.Path | Failure:
"""Run `cargo mutants <arguments>` in top, and return the `mutants.out` folder it writes. That folder is in scratch, which is a
folder in top."""
ran = run(["cargo", "mutants", *arguments, "--output", os.path.relpath(scratch, top), "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
return pathlib.Path(scratch, "mutants.out")
class Mutant(typing.NamedTuple):
"""A mutant in Gremlins' report, in the order the report prints them."""
+3 -3
View File
@@ -13,7 +13,7 @@ from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SH
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.plans import cells, no_item, Plan, Written
from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
from atlassian.jira import edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
from failure import Failure
from plan.release import parsed, Release, tagged
from plan import ranking
@@ -198,7 +198,7 @@ class JiraPlan:
return isinstance(texts, list) and texts[0].strip() == detail.strip()
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets the fields and the detail in one request, so Jira takes all of those or none, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set.
"""Sets the fields, the detail and the scores in one request, so Jira takes all of those or none. Where the edit changes only the scores, `edit_issue` sets them through their property's endpoint. Then it changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set.
A link change or a comment Jira refuses leaves the edit made, so the write counts as landed, and a note says what to do by hand."""
authorization = basic_auth(self.env_file)
@@ -237,7 +237,7 @@ class JiraPlan:
return version
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
url = f"{self.epic.site}/rest/api/3/issue/{key}"
edited = self.http("PUT", url, authorization, body) if body else None
edited = edit_issue(self.epic.site, key, body, authorization, self.http)
if isinstance(edited, Failure):
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
notes = self.relinked(issue, revision.blockers, open_keys, authorization)
+11 -7
View File
@@ -509,9 +509,11 @@ class Editing(unittest.TestCase):
self.unlinked: object = None
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit, self.commented to a new comment, self.linked to a new link and self.unlinked to a deleted one."""
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit, self.commented to a new comment, self.linked to a new link and self.unlinked to a deleted one. Like Jira, it refuses an edit of an issue that holds neither fields nor update."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
if method == "PUT" and "/properties/" not in url and isinstance(body, dict) and "fields" not in body and "update" not in body:
return Failure("Jira answered 400: one of 'fields' or 'update' required")
if method == "PUT":
return self.edited
if method == "DELETE":
@@ -540,7 +542,8 @@ class Editing(unittest.TestCase):
def test_sends_only_what_the_edit_names(self):
self.edit(34, {"Tagline": "Count every run."})
self.edit(34, {"E": "3"})
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, PROPERTY | {"E": 3}])
self.assertEqual(self.writes()[1][1], f"{ISSUES}/ABC-34/properties/plan-item")
def test_a_detail_unchanged_since_the_read_leaves_the_description_as_jira_holds_it(self):
# Jira's own spacing paragraph and localIds, which a description converted back from markdown would lose.
@@ -548,7 +551,7 @@ class Editing(unittest.TestCase):
self.open = [issue("ABC-34", scores=PROPERTY, description=held)]
self.assertEqual(self.edit(34, {"L": "2"}, "Why it counts.\n"), Written(34))
self.assertEqual(self.edit(34, {}, "Why it counts."), Written(34))
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2}}]})])
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34/properties/plan-item", PROPERTY | {"L": 2})])
def test_an_edited_detail_replaces_the_description(self):
self.open = [issue("ABC-34", scores=PROPERTY, description=adf("Why it counts."))]
@@ -586,17 +589,18 @@ class Editing(unittest.TestCase):
def test_scores_an_issue_a_person_filed_and_comments_why(self):
self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35))
self.assertEqual(self.writes(), [
("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}),
("PUT", f"{ISSUES}/ABC-35/properties/plan-item", {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}),
("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}),
])
def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self):
self.edit(36, {"L": "2"}, None, COMMENT)
self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]})
self.assertEqual(self.writes()[0][1:], (f"{ISSUES}/ABC-36/properties/plan-item", {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}))
def test_a_persons_issue_is_never_labelled(self):
self.edit(36, {"Exempt": "security"}, None, COMMENT)
self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator]
# Labelling would take an edit of the issue itself; scores alone go to its property.
self.assertEqual([url for _, url, _ in self.writes()], [f"{ISSUES}/ABC-36/properties/plan-item", f"{ISSUES}/ABC-36/comment"])
def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self):
for comment in (None, "", " \n"):
@@ -663,7 +667,7 @@ class Editing(unittest.TestCase):
def test_changes_the_links_after_the_edit_and_before_the_comment(self):
self.assertEqual(self.edit(34, {"L": "2", "Blocked by": "35"}, None, COMMENT), Written(34))
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")])
self.assertEqual([(method, url) for method, url, _ in self.writes()], [("PUT", f"{ISSUES}/ABC-34/properties/plan-item"), ("POST", LINKS), ("POST", f"{ISSUES}/ABC-34/comment")])
def test_a_failed_edit_makes_no_link(self):
self.edited = Failure("HTTP 400")
+3 -2
View File
@@ -138,14 +138,15 @@ def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cw
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.
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. Where it is given, a title counts only where its release is later than after.
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.
"""
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 ")]
return any((named := parsed(review)) is not None and (after is None or named > after) for review in reviews)
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)
def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str, run: Git = git) -> list[str] | Failure:
+18
View File
@@ -236,6 +236,24 @@ class ChunkItem(unittest.TestCase):
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)
def test_counts_no_release_review_of_the_patch_release_cut_beside_main_as_a_review_of_the_next(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", "Cut release 0.15.1")
run("tag", "v0.15.1")
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.15.2")
run("switch", "-q", "--detach", "v0.15.1")
run("commit", "-q", "--allow-empty", "-m", "Cut release 0.15.2")
run("tag", "v0.15.2")
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)
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)
def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_no_tag(self):
repo = tempfile.mkdtemp()
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
+3 -1
View File
@@ -108,8 +108,10 @@ def median(column: Column, results: list[Result]) -> float | None:
def row(task: str, side: str, results: list[Result]) -> str:
"""A task's row for one side. A `|` in the task's name is escaped, since cargo-mutants names a mutant by its operator, as in
`replace || with &&`, and a bare one would end the cell."""
passed = f"{sum(result.passed for result in results)}/{len(results)}"
return cells([task, side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
return cells([task.replace("|", "\\|"), side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
def change(bugs: list[tuple[list[Result], list[Result]]]) -> str:
+21 -14
View File
@@ -14,13 +14,14 @@ 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`, and mutmut 3 over
the Python files, as `mutmut run`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
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 and from pytest's for a Python 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. Any other mutant is passed over, so a
change to the very lines of a bug is not benched. Go and Python are the languages so far.
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.
- 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
@@ -28,23 +29,29 @@ 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.
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. A Rust test that
stands in the file of the code it tests is the exception: the bench takes that file whole, so a change to such a test counts.
--image is the project's development image, such as golang:1.27.4. The bench adds Claude Code to it, as its installer installs it,
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 ...` or `mutmut run ...`. Gremlins runs 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` or the `mutmut` on the host's PATH. For example, for Go and then for Python:
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:
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
uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"
Where the places name files in both languages, the one prefix gets both tools' commands, Gremlins' first, and a tool it
cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins` or `mutmut`:
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
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
and Python:
sh -c 'case "$1" in
gremlins) shift; exec docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
@@ -140,7 +147,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 or Python 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 Go, Python or Rust file, 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.
@@ -346,11 +353,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
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 and Python files of the tree at base that hold a place
"""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."""
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 or Python 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 Go, Python or Rust file that the base holds, 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"]))
+2 -1
View File
@@ -6,7 +6,7 @@ import re
import typing
from failure import Failure
from task_bench import go_bugs, python_bugs
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 mutate_changes.tool_process import Run
@@ -29,6 +29,7 @@ class Language(typing.NamedTuple):
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_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),
)
+1 -1
View File
@@ -11,7 +11,7 @@ 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."""
mutant by, which is Gremlins' column and mutator, or mutmut's name. cargo-mutants' own name for a mutant holds all of it."""
path: str
line: int
+95
View File
@@ -0,0 +1,95 @@
"""The bugs task-bench plants in Rust: the mutants cargo-mutants reports as caught, each read from the diff it writes, and the message
cargo test prints when a test panics on one."""
import json
import re
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.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
# bug leaves it out, since it would show Haiku the line.
MARK = b" /* ~ changed by cargo-mutants ~ */"
HUNK = re.compile(rb"@@ -(\d+)")
# The heading of what a failed test printed, in cargo test's output: `---- tests::adds stdout ----`.
SECTION = re.compile(r"^---- (\S+) std(?:out|err) ----$")
# The line before a panic's message: `thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:`. An older Rust prints no
# thread id.
PANICKED = re.compile(r"^thread '.*' (?:\(\d+\) )?panicked at .*:$")
# What follows a panic's message: a hint to ask for a backtrace, or the backtrace.
AFTER_MESSAGE = ("note: run with `RUST_BACKTRACE", "stack backtrace:")
# The heading cargo test prints twice: before the first failed test's section, and before the list of the failed tests' names.
FAILED_TESTS = "failures:"
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 cargo-mutants finds them there, each under the name
cargo-mutants gives it. One whose diff holds no change, or more than one hunk, is left out."""
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
out = in_diff_tools.cargo_mutants_out(top, scratch, [argument for path in files for argument in ("--file", path)], run, jobs)
if isinstance(out, Failure):
return out
# cargo-mutants writes no outcomes where it finds no mutant, as in a file that holds only types.
outcomes = json.loads(listed.read_bytes())["outcomes"] if (listed := out / "outcomes.json").is_file() else []
# The run of the unmutated tree is an outcome too. Its scenario is the text `Baseline`, which holds no mutant, so the summary is
# checked first.
caught = [(mutant, outcome["diff_path"]) for outcome in outcomes if outcome["summary"] == "CaughtMutant" and (mutant := outcome["scenario"]["Mutant"])["file"] in files]
lines = [(mutant, changed((out / diff).read_bytes())) for mutant, diff in caught]
return [Mutant(mutant["file"], found[0], mutant["name"], found[1], found[2]) for mutant, found in lines if found]
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read cargo-mutants' outcomes in {scratch}: {failure}")
finally:
remove(scratch)
def changed(diff: bytes) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes, from the diff cargo-mutants writes for it: the number of the first, from 1, those lines as the
tree has them, and what the mutant has in their place, without MARK. An unchanged line between two changed ones is in both.
None where the diff holds no change, or more than one hunk."""
header, *hunks = HUNK.split(diff)
if len(hunks) != 2:
return None
# A line that starts with a backslash says the file ends without a line end.
body = [line for line in hunks[1].split(b"\n")[1:] if not line.startswith(b"\\")]
at = [index for index, line in enumerate(body) if line[:1] in (b"-", b"+")]
if not at:
return None
# Each line before the first changed one is a line of the tree.
first = int(hunks[0]) + at[0]
span = body[at[0]:at[-1] + 1]
was = tuple(line[1:] for line in span if not line.startswith(b"+"))
now = tuple(line[1:].replace(MARK, b"") for line in span if not line.startswith(b"-"))
return first, was, now
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the message of the first panic in a failed test's section of cargo test's output,
without the test's name or the file and line that panicked, so it says what goes wrong and not where.
None where no failed test's section holds a panic with a message, as on a passing run or a build that broke, or where the
message only names the test."""
test, within = "", False
message: list[str] = []
for line in output.splitlines():
heading = SECTION.match(line)
if message and (heading or line == FAILED_TESTS):
break
if heading:
test, within = heading[1], False
elif line == FAILED_TESTS:
test, within = "", False
elif test and not message and PANICKED.match(line):
within = True
elif within and line.startswith(AFTER_MESSAGE):
within = False
elif within:
message.append(line.strip())
# A test in a module has the module's name before its own, as `tests::adds`; a message may name the whole or the test alone. A Rust test's own
# name is often a plain word, such as `big`, so a longer identifier that holds it, such as `is_big`, doesn't name the test.
names = [re.compile(rf"(?<!\w){re.escape(name)}(?!\w)") for name in {test, test.rpartition("::")[2]}]
kept = [text for text in message if text and not any(name.search(text) for name in names)]
return "\n".join(kept) or None
+5
View File
@@ -85,6 +85,11 @@ def run(task: int, side: str, number: int, passed: bool, input_: int = 100, turn
class TableTest(unittest.TestCase):
def test_escapes_a_bar_in_a_tasks_name_so_its_row_keeps_the_headings_cells(self):
rows = table([run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3)], {1: "src/pick.rs:7:20: replace || with && in keep"}, "bug")
self.assertTrue(rows[2].startswith(r"| 1: src/pick.rs:7:20: replace \|\| with && in keep | base | 1/1 |"))
self.assertEqual(rows[2].replace(r"\|", "").count("|"), rows[0].count("|"))
def test_prints_a_row_per_task_and_side_with_the_pass_count_and_each_median_then_all_tasks_and_the_heads_change(self):
results = [
run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3),
+3 -2
View File
@@ -84,10 +84,11 @@ class LanguagesTest(unittest.TestCase):
class ShippedLanguagesTest(unittest.TestCase):
def test_go_reads_go_tests_output_and_python_pytests(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",))])
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(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.rs", "---- picks stdout ----\nthread 'picks' (7) panicked at src/calc.rs:9:5:\ngot 3, want 4\n"), "got 3, want 4")
if __name__ == "__main__":
+269
View File
@@ -0,0 +1,269 @@
"""task-bench's Rust planter: which files cargo-mutants mutates, how its diffs become mutants and what cargo test's output tells Haiku.
PICK's two diffs, ASSERTION and TWO_FAILED are what cargo-mutants 27.1.0 and Rust 1.100.0 wrote for a small project, and OUTCOMES
holds the keys the planter reads of that run's outcomes. The other diffs 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[1]))
from task_bench.rust_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = b"""pub fn first(items: &[i32]) -> Option<i32> {
if items.is_empty() {
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
}
"""
OPERATOR_DIFF = b"""--- src/pick.rs
+++ replace += with -= in total
@@ -3,12 +3,12 @@
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
- sum += item;
+ sum -= /* ~ changed by cargo-mutants ~ */ item;
}
sum
}
"""
BODY_DIFF = b"""--- src/pick.rs
+++ replace first -> Option<i32> with None
@@ -1,13 +1,10 @@
pub fn first(items: &[i32]) -> Option<i32> {
- if items.is_empty() {
- return None;
- }
- Some(items[0])
+ None /* ~ changed by cargo-mutants ~ */
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
"""
# cargo test's report of a test in the code's own file whose assertion failed.
ASSERTION = """running 2 tests
test tests::adds ... FAILED
test tests::big ... ok
failures:
---- tests::adds stdout ----
thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:
assertion `left == right` failed
left: 0
right: 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::adds
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `-p calc --lib`
"""
# Two failed tests: one that panicked with its own message, and one that unwrapped an error.
TWO_FAILED = """running 3 tests
test first_of_some ... ok
test totals ... FAILED
test unwraps ... FAILED
failures:
---- totals stdout ----
thread 'totals' (5813) panicked at tests/picks.rs:13:9:
total of 1, 2, 3 is -6, want 6
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- unwraps stdout ----
thread 'unwraps' (5814) panicked at tests/picks.rs:20:7:
called `Result::unwrap()` on an `Err` value: "bad total"
failures:
totals
unwraps
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
PASSING = """running 1 test
test totals ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
def section(test: str, *lines: str) -> str:
return "\n".join(["failures:", "", f"---- {test} stdout ----", *lines, "", "", "failures:", f" {test}", ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_an_operator_mutant_changes_without_cargo_mutants_mark(self):
self.assertEqual(changed(OPERATOR_DIFF), (11, (b" sum += item;",), (b" sum -= item;",)))
def test_is_every_line_a_replaced_body_spans(self):
was = (b" if items.is_empty() {", b" return None;", b" }", b" Some(items[0])")
self.assertEqual(changed(BODY_DIFF), (2, was, (b" None",)))
def test_the_tree_with_the_mutant_applied_is_the_code_cargo_mutants_tested_without_its_mark(self):
for diff, line in ((OPERATOR_DIFF, b" sum -= item;"), (BODY_DIFF, b" None")):
with self.subTest(line=line):
line_number, was, now = changed(diff)
planted = mutated(PICK, Mutant("src/pick.rs", line_number, "a name", was, now))
self.assertIn(line, planted.split(b"\n"))
self.assertNotIn(b"cargo-mutants", planted)
def test_keeps_an_unchanged_line_between_two_changed_ones_on_both_sides(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,5 +4,4 @@\n fn f() {\n- a\n b\n- c\n+ d /* ~ changed by cargo-mutants ~ */\n }\n"
self.assertEqual(changed(diff), (5, (b" a", b" b", b" c"), (b" b", b" d")))
def test_a_mutant_that_only_removes_lines_has_no_line_in_their_place(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,3 +4,2 @@\n fn f() {\n- a\n }\n"
self.assertEqual(changed(diff), (5, (b" a",), ()))
def test_skips_the_line_that_says_the_file_ends_without_a_line_end(self):
diff = b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n fn f() {\n-a }\n\\ No newline at end of file\n+b /* ~ changed by cargo-mutants ~ */ }\n\\ No newline at end of file\n"
self.assertEqual(changed(diff), (2, (b"a }",), (b"b }",)))
def test_is_none_for_a_diff_of_no_change_or_of_more_than_one_hunk(self):
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n b\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n-b\n+c\n@@ -9,2 +9,2 @@\n a\n-b\n+c\n"))
class TaskTextTest(unittest.TestCase):
def test_is_the_failed_tests_panic_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(ASSERTION), "assertion `left == right` failed\nleft: 0\nright: 3")
def test_takes_the_first_failed_test_that_has_a_message(self):
self.assertEqual(task_text(TWO_FAILED), "total of 1, 2, 3 is -6, want 6")
self.assertEqual(task_text(TWO_FAILED.replace("total of 1, 2, 3 is -6, want 6\n", "")), 'called `Result::unwrap()` on an `Err` value: "bad total"')
def test_a_message_ends_at_the_next_tests_section_where_no_note_follows_it(self):
self.assertEqual(task_text(TWO_FAILED.replace("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n", "")), "total of 1, 2, 3 is -6, want 6")
def test_takes_the_panic_not_what_the_test_printed_before_it(self):
output = section("totals", "summing 3 items", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "got -6, want 6")
self.assertEqual(task_text(output), "got -6, want 6")
def test_tells_a_panic_in_the_code_under_test(self):
output = section("first_of_none", "", "thread 'first_of_none' (7) panicked at src/pick.rs:5:10:", "index out of bounds: the len is 0 but the index is 0")
self.assertEqual(task_text(output), "index out of bounds: the len is 0 but the index is 0")
def test_leaves_out_each_line_that_names_the_test(self):
output = section("tests::adds", "", "thread 'tests::adds' (7) panicked at src/lib.rs:21:9:", "adds: got 0", "want 3")
self.assertEqual(task_text(output), "want 3")
self.assertEqual(task_text(output.replace("adds: got 0", "tests::adds broke")), "want 3")
self.assertEqual(task_text(output.replace("tests::adds", "pick::tests::adds")), "want 3")
def test_a_message_may_hold_the_tests_name_inside_a_longer_identifier(self):
output = section("tests::big", "", "thread 'tests::big' (7) panicked at src/lib.rs:27:9:", "assertion failed: !is_big(10)")
self.assertEqual(task_text(output), "assertion failed: !is_big(10)")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(section("totals", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "totals failed")))
def test_is_none_where_no_test_panicked_as_on_a_passing_run_or_a_build_that_broke(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("error[E0308]: mismatched types\n --> src/lib.rs:4:5\nerror: could not compile `calc` (lib) due to 1 previous error\n"))
self.assertIsNone(task_text(""))
def test_a_panic_outside_a_failed_tests_section_is_no_message(self):
after_the_list = section("totals", "summing 3 items") + "thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"
self.assertIsNone(task_text(after_the_list))
self.assertIsNone(task_text("thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"))
class KilledMutantsTest(unittest.TestCase):
OUTCOMES = {"outcomes": [
{"scenario": "Baseline", "summary": "Success"},
{"scenario": {"Mutant": {"name": "src/pick.rs:11:13: replace += with -= in total", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/operator.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:2:5: replace first -> Option<i32> with None", "file": "src/pick.rs"}}, "summary": "MissedMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:9:5: replace total -> i32 with 0", "file": "src/pick.rs"}}, "summary": "Timeout", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/lib.rs:2:5: replace first -> Option<i32> with None", "file": "src/lib.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:1:1: a mutant whose diff holds no change", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/empty.diff"},
]}
DIFFS = {"operator.diff": OPERATOR_DIFF, "body.diff": BODY_DIFF, "empty.diff": b"--- src/pick.rs\n+++ a name\n"}
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = folder.name
self.ran: list[tuple[list[str], str]] = []
def cargo_mutants(self, outcomes: object, code: int = 0, diffs: dict[str, bytes] = DIFFS):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
out = pathlib.Path(cwd, argv[argv.index("--output") + 1], "mutants.out")
(out / "diff").mkdir(parents=True)
for name, diff in diffs.items():
(out / "diff" / name).write_bytes(diff)
if outcomes is not None:
(out / "outcomes.json").write_text(json.dumps(outcomes))
return Ran(code, "cargo-mutants said so")
return run
def test_runs_cargo_mutants_at_the_top_over_the_files_asked_for(self):
killed_mutants(self.top, ["src/pick.rs", "src/lib.rs"], self.cargo_mutants({"outcomes": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, self.top)
self.assertEqual(argv[:6], ["cargo", "mutants", "--file", "src/pick.rs", "--file", "src/lib.rs"])
self.assertEqual((argv[6], argv[8:]), ("--output", ["--jobs", "3"]))
def test_keeps_the_caught_mutants_of_the_files_asked_for_as_the_lines_each_changes_under_cargo_mutants_name(self):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=2), 3)
self.assertEqual(found, [Mutant("src/pick.rs", 11, "src/pick.rs:11:13: replace += with -= in total", (b" sum += item;",), (b" sum -= item;",))])
def test_removes_its_scratch_folder(self):
killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES), 3)
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
def test_a_cargo_mutants_that_does_not_finish_is_a_failure_with_what_it_printed(self):
# 4 is its exit code where the tests fail before any mutant.
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=4), 3)
self.assertIsInstance(found, Failure)
self.assertIn("cargo-mutants said so", found.reason)
def test_outcomes_or_a_diff_that_cannot_be_read_are_a_failure_that_names_the_folder(self):
for outcomes, diffs in (({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})):
with self.subTest(outcomes=outcomes, diffs=diffs):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(outcomes, diffs=diffs), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read cargo-mutants' outcomes in {self.top}", found.reason)
def test_finds_no_mutant_where_cargo_mutants_wrote_no_outcomes_as_it_does_where_it_finds_none(self):
self.assertEqual(killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(None), 3), [])
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -236,7 +236,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 or Python 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 Go, Python or Rust file that the base holds, 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))
@@ -306,10 +306,10 @@ class BenchTest(unittest.TestCase):
self.assertEqual(report[0], f"task-bench: base {self.head[:12]}, head {self.head[:12]}. 1 bug, each run 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
self.assertEqual(report[4:6], ["| 1: calc.go:5:11 ARITHMETIC_BASE | base | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| 1: calc.go:5:11 ARITHMETIC_BASE | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"])
def test_fails_where_the_places_name_no_go_or_python_file_of_the_base(self):
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 or Python file that the base holds, so there is nowhere to plant a bug."))
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."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):
+5 -1
View File
@@ -150,10 +150,12 @@ The cap is 5, `bin/plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: b
Valid while `~/.claude` is a checkout of this repo.
## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it, and `--cut-patch` tags a patch of the newest tag beside `main`, then merges the tag back; the human runs both
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`.
## 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
2026-11-18, lilleman's answers to claude's questions while planning release 0.12.0. Serves goal 1, so development scales past one repo, and goal 1.6, since the epic stays in the client's Jira. Valid while Jira is the only backend; another backend goes behind the same interface.
@@ -724,6 +726,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
2026-11-23, lilleman kept the ladder and the steps, settling two calls raised on the routing figures measured at 2026-11-23T15:40:14Z: chunks routed onto Opus 5.5 at medium took more review rounds past each pass's first, and more unfinished verdicts, than chunks routed onto Fable 5.2 at low. The figures came from 124 chunks finished since the 2026-11-17 reset. The 24 chunks started on Opus 5.5 at medium took a mean 0.7 rounds, 0.4 unfinished verdicts and 0.5 later fixes (18 known); the 11 started on Fable 5.2 at low took 0.3, 0.0 and 0.0 (10 known). Fable 5.2 at low has 6 chunks above the 5 a call needs, and Opus 5.5 at medium costs less per task, $2.45 against $3.10 on the 2026-11-11 index (goal 1.4). The later fixes lean towards Fable 5.2 at low, and the call doesn't count them. lilleman had kept the steps against such gaps on 2026-10-31 and 2026-11-18.
2026-11-25, lilleman kept the ladder, the steps and the delegation rule, settling the same two calls as on 2026-11-23, raised again on the routing figures measured at 2026-11-25T21:54:59Z. The figures came from 141 chunks finished since the 2026-11-17 reset. The 24 chunks started on Opus 5.5 at medium took a mean 0.7 review rounds past each pass's first, 0.4 unfinished verdicts and 0.5 later fixes (18 known); the 16 started on Fable 5.2 at low took 0.2, 0.2 and 0.0 (14 known). The figures compare the old steps with the new ones. By a count of the archive's files by modification time, every chunk started on Opus 5.5 at medium that names an item is L 3 and began by 2026-11-19T09:43Z, and v0.12.0, which moved L 3 to Fable 5.2 at low, was installed at 13:19:03Z that day. On an Opus 5.5 project no L now starts a worker on Opus 5.5 at medium; only a chunk without an item does. lilleman had the figures restart from that install, with a reset stamped 2026-11-19T13:19:03Z. loop-claude stamps these calls when the session that put them to lilleman ends, so their stamp is later than the time this note cites.
Valid while the index ranks these models, and while no newer model joins the catalog.
## routing: the offline classifier may decide finished, since lilleman ruled a miss rate of about 1 in 100 decided close enough to none; the judge's model keeps every other verdict kind
+17
View File
@@ -3570,3 +3570,20 @@ Read most (opens and searches):
- `bin/task_bench/registers.py` 1
- `bin/task_bench/runs.py` 1
- `bin/task_bench/tasks.py` 1
## Reading cost, chunk 242dc2ee7cca, finished 2026-11-24T02:22:09Z
109823 new input tokens before the first commit.
Read most (opens and searches):
- `bin/task_bench/main.py` 7
- `README.md` 6
- `bin/task_bench/test_go_bugs.py` 3
- `bin/mutate_changes/changed_lines.py` 2
- `bin/mutate_changes/in_diff_tools.py` 2
- `bin/task_bench/go_bugs.py` 2
- `bin/mutate_changes/tool_process.py` 1
- `bin/task_bench/plant.py` 1
- `bin/task_bench/planted_mutant.py` 1
- `bin/task_bench/python_bugs.py` 1
+80 -15
View File
@@ -6,25 +6,25 @@
`Bar = 0.1`
`Next ID = 532`
## Renamed
- 0.15.1 renamed to 0.16.0
`Next ID = 541`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 540 | 0.16.0 | | | **Review once more each prose fix that rewrites a checkable claim, such as a claim about generated output, a number or a licence term, so no such rewrite reaches the merge unreviewed.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.5 |
| 539 | 0.16.0 | | defect | **Start a chunk's worker on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find.** | 1 | 2 | 3 | 4 | 2 | 1.5 by 3 | 1.1 |
| 531 | 0.16.0 | | | **Bench the shipped features of a branch that landed by fast-forward: take as the feature the commits from the one after the item finished before it, up to the commit that took its item out of the plan.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 3 | 1.1 |
| 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 |
| 526 | 0.16.0 | | owner | **Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 532 | 0.16.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a Rust test that stands in the file of the code it tests.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 |
| 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 |
| 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 |
| 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 |
@@ -96,6 +96,8 @@
| 193 | 0.23.0 | | | **Narrow `numbered`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 0.9 |
| 194 | 0.23.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 0.9 |
| 519 | 0.23.0 | | | **Make stability-reviewer check that a test which runs git, or a script that runs git on another repository, isolates it from the caller's git environment.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 534 | 0.23.0 | | | **Have the stability and product-owner reviewers follow three paths an outside reviewer found unchecked: the loser of a create race, a stored null reaching a typed parameter, and each documented outcome against the order of the code's branches.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 535 | 0.23.0 | | | **Have stability-reviewer check four things an outside reviewer and two failed gate runs found unchecked: that a timeout bounds the I/O it wraps, that no early error hides an outcome's class, that a test takes its timestamps where the events happen, and that it waits for every state it depends on before it disrupts the system.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 298 | 0.23.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 0.9 |
| 265 | 0.23.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 0.8 |
| 475 | 0.23.0 | | | **Have stability-reviewer report, as a finding, each lookup that an input from outside the repo can make fail without an error naming what was missing.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 2 | 0.8 |
@@ -112,6 +114,30 @@
## Details
### 540. Review once more each prose fix that rewrites a checkable claim, such as a claim about generated output, a number or a licence term, so no such rewrite reaches the merge unreviewed.
Today the prose pass runs one round per chunk, and a fix for a prose finding reruns no pass ("Re-entry"). So a rewrite of a factual claim merges unchecked. In one chunk the prose reviewer flagged a doc's claim about generated output as false; the rewrite was still false, and only the outside auto-reviewer caught it, after the PR was marked ready. In the same chunk a credit sentence left out parts the project's licence file lists for that source: a licence link and a notice of changes.
Two directions; the implementer picks the cheaper that fits what the rounds cost:
- let the prose pass re-enter once where a round's fix answers a finding that asserts something checkable;
- or have prose-reviewer check each claim a fix rewrites against a concrete counter-example, and against the source it names, such as the licence file's listed credit, before it accepts the rewrite.
Touches:
- `skills/larv-review/SKILL.md`: `## 3. Passes` (small), `### Prose` (small)
- `agents/prose-reviewer.md`: `## Checks, in priority order` (small)
### 539. Start a chunk's worker on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find.
Today `session_open` in `bin/claude_code/session.py` counts a session as open wherever its `<session id>.jsonl` exists. On 2026-11-24 a run left item-532's transcript as a 0-byte file, with an archive folder whose transcript and outcomes were empty too. On 2026-11-25 every rerun of item-532 called `claude --resume <id>`. Each got "No conversation found with session ID …" and exited 1. The window stopped after three failures and waited for the human, who had to move the file away by hand.
Count an empty transcript as no session. Before the worker starts that session with `--session-id`, remove the empty file, so claude doesn't refuse the id. Leave a non-empty transcript to resume as today. The worker's start, in `bin/agent_cycle/run.py` → `worker_start`, and a chunk's start, in `bin/loop_claude/loop/chunk_start.py`, both read `session_open`, so the fix holds for both.
Touches:
- `bin/claude_code/session.py`: `session_open` (small)
- `bin/claude_code/test_claude_code.py`
### 531. Bench the shipped features of a branch that landed by fast-forward: take as the feature the commits from the one after the item finished before it, up to the commit that took its item out of the plan.
Today `task-bench --tasks shipped-features` passes such a feature over. A fast-forwarded branch's commits keep a commit time each, so `branch_chunks` cuts each commit into a chunk of its own, and the chunk that took the item out of the plan holds only the feature's last commit. This project landed 114 of its 260 shipped features that way, and none of those can be benched. A squash-merged feature whose one commit was authored and committed at the same time would be passed over too; whether a forge writes such commits is not checked.
@@ -138,18 +164,16 @@ The second part of item 504, which says what a bench feature is and when a run c
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.
### 526. Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.
### 532. Leave out of a `task-bench` fix a change Haiku makes to a Rust test that stands in the file of the code it tests.
cargo-mutants 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 the diffs it writes under `mutants.out`. Tell Haiku the failure `cargo test` 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 Rust.
Today the check takes each file that is no test as Haiku left it, and `is_test` tells a test by its file's path. Rust keeps unit tests in the source file, in a `#[cfg(test)]` module, so 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, so the head's change against the base still compares like with like; the Passed column of a Rust bench counts such a run as a fix.
Recommended: keep each `#[cfg(test)]` module of a Rust file as the planted tree has it, and take the rest of the file from Haiku's copy; where the module cannot be told apart, pass the mutant over. Passing over every mutant that a test in a source file kills would leave most Rust bugs out, since unit tests are where most Rust tests stand. A product-owner finding on item 526's chunk raised this.
Touches:
- `bin/task_bench/rust_bugs.py`
- `bin/task_bench/test_rust_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_cargo_mutants`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
- `bin/task_bench/runs.py`: `checked_tree`, `of_tests` (small)
- `bin/task_bench/test_task_bench.py`
- `bin/task_bench/main.py`: lines 30-33
### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.
@@ -203,6 +227,20 @@ Part of the standalone-install plan lilleman approved on 2026-11-20. Later items
An outside reviewer found it on a client project's PR that added a secret: a Gitea token documented as able to run Actions on one repository, "and nothing wider". The token reaches every repository its owning account can, so the docs had to require a dedicated account with access to that repository only. Neither `/security-review` nor stability-reviewer raised it. Where a change adds a secret or a token, ask each to check that the doc beside it states what the credential can reach, not only what the change uses it for.
### 537. Flag regexes that use `$` to validate a whole input, since `$` also matches before a final newline.
An outside auto-reviewer found a validation regex anchored with `$` that accepted a value with a trailing newline; neither the stability standard nor any tool flags this. In PCRE (PHP's `preg_match`, Laravel's `regex:` rule) and in Python's `re.match`, `^…$` accepts `"value\n"`. Add a bullet to stability-reviewer's "Edge Cases & Input Validation": where a change validates a whole input with a regex anchored by `$`, report it and ask for `\z` (PCRE, Python's `\Z`), PCRE's `D` modifier, or a full-match call such as Python's `re.fullmatch`. A deterministic check doesn't fit: no tool in this setup scans a project's diff for code patterns, and the regex syntax differs by language.
Touches:
- `agents/stability-reviewer.md`: `### 5. Edge Cases & Input Validation` (small)
### 538. Flag validation that checks a value other than the one the code goes on to use, such as before trimming, stripping or converting it.
An outside human reviewer found input validation that checked the value the client sent, while the code then searched with a normalised value, with its leading zeros stripped. A value passed the minimum-length rule, but the search ran on far fewer characters and matched broadly. Stability-reviewer didn't flag it. The implementer's unit test listed the bad value as accepted: its expected values came from the code, not the requirement, which the technical principles' test bullet already bans and section 11 already asks about. Add a bullet to stability-reviewer's "Edge Cases & Input Validation": where a change validates a value and then trims, strips, converts or otherwise normalises it before use, check that each rule, such as a minimum length, holds for the value the code uses, and report an input that passes the check but reaches the code as something the check would refuse. A deterministic check doesn't fit: whether two values are the same one is semantic, and no tool here scans a project's diff for code patterns. Kept apart from item 537, since the two catch different faults, though one chunk may take both.
Touches:
- `agents/stability-reviewer.md`: `### 5. Edge Cases & Input Validation` (small)
### 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.
@@ -304,6 +342,8 @@ Name the entry and the Dockerfile line. Source the secret-name list from a widel
Found while shipping item 461: `mutate-changes` printed `23 mutants on changed lines, 18 not killed. Left out the tests that fail without a mutant, in do_epic/test_main.py, larv_review/test_larv_review.py, larv_review/test_scoring_setup.py, plan/test_ranking.py, repo_checks/…, review_rules/test_review_passes.py, review_rules/test_reviewer_context.py, rule_hook/test_rule_hook.py, test_settings_filter.py`. All 18 survivors were in `bin/larv_review/scoring_setup.py`: `prepare_scoring`, whose tests are among those left out, so the chunk checked four of them by hand and left 14 unchecked. Find why each left-out test fails in mutmut's copy, such as a path to `skills/` or a git checkout it expects, and make it pass there, or report under the count which changed lines no remaining test covers.
Item 536 met the same gap: `deploy_release/test_deploy_release.py` runs `deploy-release` as a subprocess, and those tests fail in mutmut's copy, so only its in-process tests ran, and 530 of 590 mutants of `bin/deploy_release/` went unchecked.
Touches `bin/mutate_changes/`, and the tests named above.
### 77. Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.
@@ -688,6 +728,31 @@ Add one check to the stability reviewer (`agents/stability-reviewer.md`), or to
A finding names the test or script line and the variables it inherits.
### 534. Have the stability and product-owner reviewers follow three paths an outside reviewer found unchecked: the loser of a create race, a stored null reaching a typed parameter, and each documented outcome against the order of the code's branches.
An outside auto-reviewer raised three findings on one chunk, after two rounds of the stability pass and two of the product-owner pass had cleared it. Each fell under a rule the reviewers already hold, read too narrowly:
- `agents/stability-reviewer.md` asks whether a unique constraint wins a check-then-insert race. It doesn't ask what the losing request then does. The reviewer saw the constraint and stopped, and the loser answered with a server error instead of taking the path for a row that exists. Add: follow the loser, on every branch that inserts.
- The same file asks whether null inputs are handled. The reviewer checked the request's values, not the stored row's. A nullable column read into a typed parameter throws. Add: for each column the change newly reads, ask what a null in an existing row does.
- `agents/product-owner-reviewer.md` doesn't ask the reviewer to check each outcome the documentation promises against the branch that returns it. An early return for "nothing to change" answered before the branch the documentation promised. Add: for each documented outcome, name the input that reaches it and the branch that returns it, in the order the code tests them.
Touches:
- `agents/stability-reviewer.md`: `### 6. Concurrency & State Management` (small)
- `agents/product-owner-reviewer.md`
### 535. Have stability-reviewer check four things an outside reviewer and two failed gate runs found unchecked: that a timeout bounds the I/O it wraps, that no early error hides an outcome's class, that a test takes its timestamps where the events happen, and that it waits for every state it depends on before it disrupts the system.
An outside reviewer raised three findings on a client chunk that two stability rounds had passed. Each was real and was fixed. Add each as a check in `agents/stability-reviewer.md`:
- **A timeout that doesn't bound the I/O it wraps.** A call was given a context with a deadline, but the library's blocking socket write doesn't watch the context, so a peer that stops reading holds the caller for good. For each timeout a change adds, the reviewer names the blocking call it is meant to bound and checks, in the library's source or docs, that the call honours it.
- **An error on the way that hides the answer's class.** A response's status said the failure was permanent, but an error while reading the body returned first, as retryable. Where code sorts an outcome into retry or give up, the reviewer follows each early error return between receiving the outcome and sorting it.
- **A test that times an event where it is observed, not where it happens.** A test asserted a minimum wait between two events from the times the test read them off a channel, so a slow reader passes or fails by scheduling. The reviewer checks that an assertion on elapsed time takes both timestamps where the events happen.
The same chunk's own review found a fourth of this kind late, after two failed gate runs: a test disrupted the system once one state was visible, while the behaviour under test also needed a second state to have settled. Add it to the same list: before a test disrupts a system, it waits for every state the assertion depends on.
Touches:
- `agents/stability-reviewer.md`
### 298. Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.
153 `Judge cost:` entries total $109.76, a median of about $0.76 a verdict at every rung, and the cost follows the size of the records, not the transcript: about 76k characters in log and 188k in claude-config. In 224 of 251 recent verdicts (89%) the evidence sits in the worker's final message. A missed interrupt is the costly error, so the bar is zero changed interrupts and zero new rejections across the replay. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster.