From 6fbfd548213f10935fc08b9679cca663fb7d061e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:13:14 +0100 Subject: [PATCH 01/39] Record the reading cost --- docs/reading-cost.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 3df0d017..f2efc71c 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3558,3 +3558,15 @@ Read most (opens and searches): - `README.md` 1 - `bin/task_bench/python_bugs.py` 1 - `bin/task_bench/test_planted_mutant.py` 1 + +## Reading cost, chunk be78ef577b52, finished 2026-11-24T01:07:00Z + +102199 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/task_bench/feature_tasks.py` 3 +- `bin/task_bench/main.py` 2 +- `bin/task_bench/registers.py` 1 +- `bin/task_bench/runs.py` 1 +- `bin/task_bench/tasks.py` 1 From 49d16378e87c76e9f10e9f19d080ef026569bc4c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:13:14 +0100 Subject: [PATCH 02/39] Plant bugs for task-bench in Rust, from the mutants cargo-mutants kills --- README.md | 4 +- bin/mutate_changes/in_diff_tools.py | 17 +- bin/task_bench/main.py | 32 ++-- bin/task_bench/plant.py | 3 +- bin/task_bench/planted_mutant.py | 3 +- bin/task_bench/rust_bugs.py | 92 ++++++++++ bin/task_bench/test_plant.py | 5 +- bin/task_bench/test_rust_bugs.py | 260 ++++++++++++++++++++++++++++ bin/task_bench/test_task_bench.py | 4 +- 9 files changed, 394 insertions(+), 26 deletions(-) create mode 100644 bin/task_bench/rust_bugs.py create mode 100644 bin/task_bench/test_rust_bugs.py diff --git a/README.md b/README.md index 02eb8079..2124de54 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,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] ` 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 --test []` 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. It passes over a feature whose branch landed by fast-forward. 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 --test []` 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. It passes over a feature whose branch landed by fast-forward. 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 ` one item's row and detail; `add …` files an item under the next free ID, `edit …` sets an item's cells or detail, and `move --release ` sets an item's release; `finish ` 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 ...` 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 [] [--timeout ]` waits until a file a background job writes holds a line matching the pattern, and prints it. @@ -278,7 +278,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. diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index 68d1d7c1..f3bd6765 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -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,14 @@ 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: + """The `mutants.out` folder that `cargo mutants `, which runs in top, writes in scratch, 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.""" diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index fc66729b..13112455 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -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`. 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. Any + other mutant is passed over, so a change to the very lines of a bug is not benched. Go, Python and Rust are the languages so + far. - 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 @@ -34,17 +35,22 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at the copy's top, with no network, so the image must hold what the tests would otherwise download. --prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs ` "$@"` 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, in the order above, 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 \ @@ -136,7 +142,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. @@ -342,11 +348,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"])) diff --git a/bin/task_bench/plant.py b/bin/task_bench/plant.py index 7595268d..52c0400b 100644 --- a/bin/task_bench/plant.py +++ b/bin/task_bench/plant.py @@ -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), ) diff --git a/bin/task_bench/planted_mutant.py b/bin/task_bench/planted_mutant.py index 6ff0d6ae..85a4c6c2 100644 --- a/bin/task_bench/planted_mutant.py +++ b/bin/task_bench/planted_mutant.py @@ -11,7 +11,8 @@ class Mutant(typing.NamedTuple): """A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1, those lines as the tree has them, and what the mutant has in their place. Where it only adds lines, the number is that of the line they go in before. name is what the report calls the bug it becomes: the path and line, then what the tool tells the - mutant by, which is Gremlins' column and mutator, or mutmut's name.""" + mutant by, which is Gremlins' column and mutator, or mutmut's name. A Rust mutant's name is the one cargo-mutants gives it, which holds + the path and line.""" path: str line: int diff --git a/bin/task_bench/rust_bugs.py b/bin/task_bench/rust_bugs.py new file mode 100644 index 00000000..d690875c --- /dev/null +++ b/bin/task_bench/rust_bugs.py @@ -0,0 +1,92 @@ +"""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 of the list that names the failed tests, after the last test's section. +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 is not one run of changed lines 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 + outcomes = json.loads((out / "outcomes.json").read_bytes())["outcomes"] + # The run of the unmutated tree is an outcome too, whose scenario is no mutant. + 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 + first = int(hunks[0]) + sum(not line.startswith(b"+") for line in body[: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 is named after it, 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"(? Option { + 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 +} +""" +# A mutant that swaps an operator, and one that replaces a function's body. +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 with None +@@ -1,13 +1,10 @@ + pub fn first(items: &[i32]) -> Option { +- 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")): + 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") + + 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): + 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 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 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 ((None, self.DIFFS), ({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})): + 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) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index e7b10f92..5e5aa67f 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -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)) @@ -309,7 +309,7 @@ class BenchTest(unittest.TestCase): def test_fails_where_the_places_name_no_go_or_python_file_of_the_base(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): From a1465a386a5199e5d7c04a7141b4e92b46f807e7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:16:52 +0100 Subject: [PATCH 03/39] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?gs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 70fbc2a02d5d31248703feed7d2b7b8cc38486e1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:34:10 +0100 Subject: [PATCH 04/39] Kill the mutants that survived in the Rust planter --- bin/task_bench/rust_bugs.py | 5 +++-- bin/task_bench/test_rust_bugs.py | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/bin/task_bench/rust_bugs.py b/bin/task_bench/rust_bugs.py index d690875c..ba79a414 100644 --- a/bin/task_bench/rust_bugs.py +++ b/bin/task_bench/rust_bugs.py @@ -56,7 +56,8 @@ def changed(diff: bytes) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | N at = [index for index, line in enumerate(body) if line[:1] in (b"-", b"+")] if not at: return None - first = int(hunks[0]) + sum(not line.startswith(b"+") for line in body[:at[0]]) + # 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"-")) @@ -87,6 +88,6 @@ def task_text(output: str) -> str | None: message.append(line.strip()) # A test in a module is named after it, 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"(? Date: Tue, 24 Nov 2026 02:57:18 +0100 Subject: [PATCH 05/39] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20no=20outcom?= =?UTF-8?q?es=20file=20means=20no=20mutant,=20two=20tests=20use=20subTest,?= =?UTF-8?q?=20and=20a=20test's=20name=20fits=20its=20assertion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mutate_changes/in_diff_tools.py | 3 ++- bin/task_bench/figures.py | 4 +++- bin/task_bench/main.py | 15 ++++++++------- bin/task_bench/planted_mutant.py | 3 +-- bin/task_bench/rust_bugs.py | 12 +++++++----- bin/task_bench/test_figures.py | 5 +++++ bin/task_bench/test_rust_bugs.py | 26 ++++++++++++++++---------- bin/task_bench/test_task_bench.py | 2 +- todo.md | 14 +++++++++++++- 9 files changed, 56 insertions(+), 28 deletions(-) diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index f3bd6765..e8d198f6 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -45,7 +45,8 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git, def cargo_mutants_out(top: str, scratch: str, arguments: list[str], run: Run, jobs: int) -> pathlib.Path | Failure: - """The `mutants.out` folder that `cargo mutants `, which runs in top, writes in scratch, a folder in top.""" + """Run `cargo mutants ` 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) diff --git a/bin/task_bench/figures.py b/bin/task_bench/figures.py index 53300c1a..04a01ccb 100644 --- a/bin/task_bench/figures.py +++ b/bin/task_bench/figures.py @@ -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: diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index 13112455..17579781 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -15,13 +15,13 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream. - Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places` prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over - the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of + the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. No other language is planted + in so far. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where, planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must - run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short. Any - other mutant is passed over, so a change to the very lines of a bug is not benched. Go, Python and Rust are the languages so - far. + 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 @@ -29,7 +29,8 @@ 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 @@ -48,8 +49,8 @@ for Go, for Python and then for Rust: docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e CARGO_HOME=/tmp/cargo -v "$PWD:$PWD" -w "$PWD" \ rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh -Where the places name files in more than one language, the one prefix gets each tool's command, in the order above, 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 +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 diff --git a/bin/task_bench/planted_mutant.py b/bin/task_bench/planted_mutant.py index 85a4c6c2..ba6f31f8 100644 --- a/bin/task_bench/planted_mutant.py +++ b/bin/task_bench/planted_mutant.py @@ -11,8 +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. A Rust mutant's name is the one cargo-mutants gives it, which holds - the path and line.""" + 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 diff --git a/bin/task_bench/rust_bugs.py b/bin/task_bench/rust_bugs.py index ba79a414..6a1a6cd1 100644 --- a/bin/task_bench/rust_bugs.py +++ b/bin/task_bench/rust_bugs.py @@ -19,13 +19,13 @@ SECTION = re.compile(r"^---- (\S+) std(?:out|err) ----$") 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 of the list that names the failed tests, after the last test's section. +# 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 is not one run of changed lines is left out.""" + 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 @@ -33,8 +33,10 @@ def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Muta 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 - outcomes = json.loads((out / "outcomes.json").read_bytes())["outcomes"] - # The run of the unmutated tree is an outcome too, whose scenario is no mutant. + # 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] @@ -86,7 +88,7 @@ def task_text(output: str) -> str | None: within = False elif within: message.append(line.strip()) - # A test in a module is named after it, as `tests::adds`; a message may name the whole or the test alone. A Rust test's own + # 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"(? i32 { sum } """ -# A mutant that swaps an operator, and one that replaces a function's body. OPERATOR_DIFF = b"""--- src/pick.rs +++ replace += with -= in total @@ -3,12 +3,12 @@ @@ -135,10 +135,11 @@ class ChangedTest(unittest.TestCase): 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")): - 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) + 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" @@ -253,10 +254,15 @@ class KilledMutantsTest(unittest.TestCase): 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 ((None, self.DIFFS), ({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})): - 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) + 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__": diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 5e5aa67f..c40d6ee7 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -306,7 +306,7 @@ 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, Python or Rust file that the base holds, so there is nowhere to plant a bug.")) diff --git a/todo.md b/todo.md index 5819ddde..ace2558f 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 532` +`Next ID = 533` ## Renamed @@ -18,6 +18,7 @@ |---|---|---|---|---|---|---|---|---|---|---|---| | 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 | +| 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 | | 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 | | 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 | @@ -138,6 +139,17 @@ 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. +### 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. + +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/runs.py`: `checked_tree`, `of_tests` (small) +- `bin/task_bench/test_task_bench.py` +- `bin/task_bench/main.py`: lines 30-33 + ### 526. Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills. 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. From 178aeb674962adc4b5464ef91052af719eb76bf7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:57:18 +0100 Subject: [PATCH 06/39] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20a=20bar?= =?UTF-8?q?=20in=20a=20bug's=20name=20is=20escaped=20in=20the=20table,=20t?= =?UTF-8?q?he=20help=20says=20a=20Rust=20test=20in=20its=20code's=20file?= =?UTF-8?q?=20counts,=20and=20item=20532=20files=20leaving=20it=20out;=20t?= =?UTF-8?q?he=20fixes=20are=20in=20the=20commit=20before?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 1fc164a54769b894fba955762105050e3306a63e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 02:57:18 +0100 Subject: [PATCH 07/39] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20the=20docst?= =?UTF-8?q?rings,=20comments=20and=20help=20are=20reworded=20in=20the=20st?= =?UTF-8?q?ability=20round's=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From dc8c463ad3c076dd2884299883fd8b0dc58f0f9e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 03:16:04 +0100 Subject: [PATCH 08/39] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20approved?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 794ce37208ea1763d27deb31e4a2de8d40f157bf Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 24 Nov 2026 03:17:13 +0100 Subject: [PATCH 09/39] Finish item 526 in the plan --- CHANGELOG.md | 1 + todo.md | 14 -------------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b0b1f8c..e09e0ce3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `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 ` sets how many it takes, and a feature whose branch landed by fast-forward is passed over. - `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. diff --git a/todo.md b/todo.md index ace2558f..4bca87e6 100644 --- a/todo.md +++ b/todo.md @@ -19,7 +19,6 @@ | 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 | | 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 | -| 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 | | 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 | @@ -150,19 +149,6 @@ Touches: - `bin/task_bench/test_task_bench.py` - `bin/task_bench/main.py`: lines 30-33 -### 526. Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills. - -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. - -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 - ### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills. Stryker runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON report. Tell Haiku the failure the project's test runner prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no TypeScript. From b6a576187a1f965fffc68096951207b040531638 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 07:35:01 +0100 Subject: [PATCH 10/39] File item 533, a patch release 0.15.1 for Jira's refused score edits --- CHANGELOG.md | 2 +- todo.md | 21 ++++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e09e0ce3..664d0a93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ - `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 `. diff --git a/todo.md b/todo.md index 4bca87e6..ae4230e4 100644 --- a/todo.md +++ b/todo.md @@ -6,16 +6,13 @@ `Bar = 0.1` -`Next ID = 533` - -## Renamed - -- 0.15.1 renamed to 0.16.0 +`Next ID = 534` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| +| 533 | 0.15.1 | | defect | **Set an issue's scores in Jira through its issue-property endpoint, so do-epic and `todo-item edit` save them where Jira refuses an edit that holds only properties.** | 2 | 2 | 2 | 4 | 3 | 1.6 by 3, 1.1 by 2 | 1.7 | | 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 | | 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 | @@ -112,6 +109,20 @@ ## Details +### 533. Set an issue's scores in Jira through its issue-property endpoint, so do-epic and `todo-item edit` save them where Jira refuses an edit that holds only properties. + +Jira Cloud's edit request, `PUT /rest/api/3/issue/{key}`, refuses a body that holds `properties` without `fields` or `update`: it answers 400 "one of 'fields' or 'update' required". do-epic's scoring sends exactly that body, after it has posted the comment that tells the team the scores. So on a team's epic every scored issue got the comment but no scores, and each later run would score and comment on it again. `todo-item edit` sends the same body where it changes only the scores of an issue, as it does on an issue a person filed. The test fakes accepted the body, so no test saw it. + +Fix: one function in `bin/atlassian/jira.py` sends an issue edit. Where the edit sets only issue properties, it sets each through `PUT /rest/api/3/issue/{key}/properties/{propertyKey}`, whose body is the property's value. Both callers use it, and both fakes refuse an edit that holds neither `fields` nor `update`, as Jira does. + +Touches: +- `bin/atlassian/jira.py`: `edited` +- `bin/atlassian/test_jira.py`: `Edited` +- `bin/do_epic/backend/jira.py`: `JiraEpic.set_scores` (small) +- `bin/do_epic/backend/test_jira.py`: `FakeJira` (small) +- `bin/plan_store/jira_epic.py`: `JiraPlan.edit` (small) +- `bin/plan_store/test_jira_epic.py`: `Editing` (small) + ### 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. From b3bb2dd3f5633b0732ac0ac7e2d69badcaeab1c6 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 07:38:55 +0100 Subject: [PATCH 11/39] Set an issue's scores through its property endpoint where an edit holds neither fields nor update --- bin/atlassian/jira.py | 12 ++++++++++++ bin/atlassian/test_jira.py | 32 ++++++++++++++++++++++++++++++++ bin/do_epic/backend/jira.py | 4 ++-- bin/do_epic/backend/test_jira.py | 13 +++++++------ bin/plan_store/jira_epic.py | 6 +++--- bin/plan_store/test_jira_epic.py | 14 ++++++++------ 6 files changed, 64 insertions(+), 17 deletions(-) diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index 5d940053..eabc59ed 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -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 an edit of the issue named key: its fields, its updates and its issue properties in one request, or the Failure Jira answered. Jira refuses an edit that holds neither fields nor update, 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}) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index 0e086c59..5db09715 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -109,3 +109,35 @@ class TheRefusalOfAnIssueType(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +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_a_request_jira_refuses_is_its_failure_and_sets_no_later_property(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) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 269580ce..2a664a84 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -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: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 5da2d0ea..68840910 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -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.")) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index a0b984e2..5e0c8082 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -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, or sets the scores alone as `edit_issue` says, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set. A link change or a comment Jira refuses leaves the edit made, so the write counts as landed, and a note says what to do by hand.""" authorization = basic_auth(self.env_file) @@ -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 body else None 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) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 1300921f..4611484e 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -540,7 +540,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 +549,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 +587,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 +665,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") From 0c10eeb986f3cc6b18c0899cf59152c7fb0844a4 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 07:52:37 +0100 Subject: [PATCH 12/39] Kill the mutants of edit_issue: an empty edit sends nothing, and an answer on success is no failure --- bin/atlassian/test_jira.py | 8 ++++++++ bin/plan_store/jira_epic.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index 5db09715..bdd4333b 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -136,6 +136,14 @@ class AnIssueEdit(unittest.TestCase): ("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/seen", True), ]) + def test_an_answer_jira_sends_on_success_is_no_failure(self): + self.answer = {"id": "10001"} + self.assertIsNone(self.edit({"fields": {"summary": "Count."}})) + + def test_an_edit_that_sets_nothing_sends_no_request(self): + self.assertIsNone(self.edit({})) + self.assertEqual(self.calls, []) + def test_a_request_jira_refuses_is_its_failure_and_sets_no_later_property(self): self.answer = Failure("Jira answered 503") self.assertEqual(self.edit({"fields": {"summary": "Count."}}), Failure("Jira answered 503")) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index 5e0c8082..7528e13a 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -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 = edit_issue(self.epic.site, key, body, authorization, self.http) 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) From e96b8a8182af47076c8f39b8a2c9cfe8539bcf19 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 09:57:54 +0100 Subject: [PATCH 13/39] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?gs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From fb55fc7a03b6385f3c8fe517ceeb22b59973b59f Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 10:05:08 +0100 Subject: [PATCH 14/39] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(1=20misread);=20the=20plan?= =?UTF-8?q?=20store's=20fake=20refuses=20an=20edit=20with=20neither=20fiel?= =?UTF-8?q?ds=20nor=20update,=20and=200.15.1=20is=20cut=20off=20v0.15.0,?= =?UTF-8?q?=20never=20from=20main?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/plan_store/test_jira_epic.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 4611484e..0674eda0 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -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": From 0cf70b06b1532d91a209627a77e01b381f123853 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 10:05:08 +0100 Subject: [PATCH 15/39] =?UTF-8?q?Answer=20prose=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20clearer=20d?= =?UTF-8?q?ocstrings,=20test=20names=20and=20item=20text,=20and=20AnIssueE?= =?UTF-8?q?dit=20above=20the=20main=20guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/atlassian/jira.py | 2 +- bin/atlassian/test_jira.py | 14 +++++++------- bin/plan_store/jira_epic.py | 2 +- todo.md | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index eabc59ed..5359e6f2 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -155,7 +155,7 @@ def project_of(key: str) -> str: def edit_issue(site: str, key: str, body: dict[str, typing.Any], authorization: str, http: Http) -> None | Failure: - """Sends an edit of the issue named key: its fields, its updates and its issue properties in one request, or the Failure Jira answered. Jira refuses an edit that holds neither fields nor update, so such an edit sets each property through the property's own endpoint, one request each, and stops at the first that fails.""" + """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 diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index bdd4333b..13388b86 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -107,10 +107,6 @@ 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") -if __name__ == "__main__": - unittest.main() - - class AnIssueEdit(unittest.TestCase): def setUp(self) -> None: self.calls: list[tuple[str, str, object]] = [] @@ -136,16 +132,20 @@ class AnIssueEdit(unittest.TestCase): ("PUT", "https://acme.atlassian.net/rest/api/3/issue/ABC-1/properties/seen", True), ]) - def test_an_answer_jira_sends_on_success_is_no_failure(self): + 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_edit_that_sets_nothing_sends_no_request(self): + 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_sets_no_later_property(self): + 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() diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index 7528e13a..4424e35c 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -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, the detail and the scores in one request, so Jira takes all of those or none, or sets the scores alone as `edit_issue` says, 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) diff --git a/todo.md b/todo.md index ae4230e4..c8b7be0d 100644 --- a/todo.md +++ b/todo.md @@ -111,9 +111,9 @@ ### 533. Set an issue's scores in Jira through its issue-property endpoint, so do-epic and `todo-item edit` save them where Jira refuses an edit that holds only properties. -Jira Cloud's edit request, `PUT /rest/api/3/issue/{key}`, refuses a body that holds `properties` without `fields` or `update`: it answers 400 "one of 'fields' or 'update' required". do-epic's scoring sends exactly that body, after it has posted the comment that tells the team the scores. So on a team's epic every scored issue got the comment but no scores, and each later run would score and comment on it again. `todo-item edit` sends the same body where it changes only the scores of an issue, as it does on an issue a person filed. The test fakes accepted the body, so no test saw it. +Jira Cloud's edit request, `PUT /rest/api/3/issue/{key}`, refuses a body that holds `properties` without `fields` or `update`: it answers 400 "one of 'fields' or 'update' required". do-epic's scoring sends exactly that body, after it has posted the comment that tells the team the scores. So on a team's epic every scored issue got the comment but no scores, and each later run would score and comment on it again. `todo-item edit` sends the same body where it changes only an issue's scores, which is all it may change on an issue a person filed. The test fakes accepted that body, so no test caught the refusal. -Fix: one function in `bin/atlassian/jira.py` sends an issue edit. Where the edit sets only issue properties, it sets each through `PUT /rest/api/3/issue/{key}/properties/{propertyKey}`, whose body is the property's value. Both callers use it, and both fakes refuse an edit that holds neither `fields` nor `update`, as Jira does. +Fix: one function in `bin/atlassian/jira.py` sends an issue edit. Where the edit sets only issue properties, it sets each through `PUT /rest/api/3/issue/{key}/properties/{propertyKey}`, whose body is the property's value. Both callers use it, and the fakes in both callers' tests refuse an edit that holds neither `fields` nor `update`, as Jira does. Touches: - `bin/atlassian/jira.py`: `edited` From 1aa2367a3198fc517e1ad3f6066ad530b71b58fe Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 10:08:20 +0100 Subject: [PATCH 16/39] Finish item 533 in the plan --- CHANGELOG.md | 1 + todo.md | 15 --------------- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 664d0a93..fb2356df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `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. - `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 ` sets how many it takes, and a feature whose branch landed by fast-forward is passed over. - `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. diff --git a/todo.md b/todo.md index c8b7be0d..7804377a 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 533 | 0.15.1 | | defect | **Set an issue's scores in Jira through its issue-property endpoint, so do-epic and `todo-item edit` save them where Jira refuses an edit that holds only properties.** | 2 | 2 | 2 | 4 | 3 | 1.6 by 3, 1.1 by 2 | 1.7 | | 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 | | 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 | @@ -109,20 +108,6 @@ ## Details -### 533. Set an issue's scores in Jira through its issue-property endpoint, so do-epic and `todo-item edit` save them where Jira refuses an edit that holds only properties. - -Jira Cloud's edit request, `PUT /rest/api/3/issue/{key}`, refuses a body that holds `properties` without `fields` or `update`: it answers 400 "one of 'fields' or 'update' required". do-epic's scoring sends exactly that body, after it has posted the comment that tells the team the scores. So on a team's epic every scored issue got the comment but no scores, and each later run would score and comment on it again. `todo-item edit` sends the same body where it changes only an issue's scores, which is all it may change on an issue a person filed. The test fakes accepted that body, so no test caught the refusal. - -Fix: one function in `bin/atlassian/jira.py` sends an issue edit. Where the edit sets only issue properties, it sets each through `PUT /rest/api/3/issue/{key}/properties/{propertyKey}`, whose body is the property's value. Both callers use it, and the fakes in both callers' tests refuse an edit that holds neither `fields` nor `update`, as Jira does. - -Touches: -- `bin/atlassian/jira.py`: `edited` -- `bin/atlassian/test_jira.py`: `Edited` -- `bin/do_epic/backend/jira.py`: `JiraEpic.set_scores` (small) -- `bin/do_epic/backend/test_jira.py`: `FakeJira` (small) -- `bin/plan_store/jira_epic.py`: `JiraPlan.edit` (small) -- `bin/plan_store/test_jira_epic.py`: `Editing` (small) - ### 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. From dcd55df69aa5978af84539bcf68d45fd84ae8b24 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 10:17:59 +0100 Subject: [PATCH 17/39] Cut release 0.15.1 --- CHANGELOG.md | 4 ++++ bin/atlassian/jira.py | 12 ++++++++++ bin/atlassian/test_jira.py | 40 ++++++++++++++++++++++++++++++++ bin/do_epic/backend/jira.py | 4 ++-- bin/do_epic/backend/test_jira.py | 13 ++++++----- bin/plan_store/jira_epic.py | 6 ++--- bin/plan_store/test_jira_epic.py | 18 ++++++++------ 7 files changed, 79 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dc97850..0f64f461 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 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. diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index 5d940053..5359e6f2 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -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}) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index 0e086c59..13388b86 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -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() diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 269580ce..2a664a84 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -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: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 5da2d0ea..68840910 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -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.")) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index a0b984e2..4424e35c 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -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) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 1300921f..0674eda0 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -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") From 7e03aafe41694d308da5bc2dc82ed7469e2bc7f6 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 10:18:22 +0100 Subject: [PATCH 18/39] List the fix under 0.15.1 in the changelog --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb2356df..b405a0b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,6 @@ ## Unreleased -- `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. - `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 ` sets how many it takes, and a feature whose branch landed by fast-forward is passed over. - `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. @@ -18,6 +17,10 @@ - `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 `. +## 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. From 58cbc9a5e33d2f2de6d52b476f84eea1a683dee9 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 12:54:21 +0100 Subject: [PATCH 19/39] File item 534: have the reviewers follow three paths an outside reviewer found unchecked --- todo.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 7804377a..734ac133 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 534` +`Next ID = 535` ## Items @@ -92,6 +92,7 @@ | 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 | | 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 | @@ -682,6 +683,18 @@ 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` + ### 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. From fdb631d293ce93c3170291c74f472df2f29fa4de Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 13:41:27 +0100 Subject: [PATCH 20/39] File item 535: have stability-reviewer check four things an outside reviewer and two failed gate runs found unchecked --- todo.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 734ac133..dad74be6 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 535` +`Next ID = 536` ## Items @@ -93,6 +93,7 @@ | 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 | @@ -695,6 +696,19 @@ 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. From 80de753b9ebb00a95d7d9b8ef292d457691a7365 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:05:11 +0100 Subject: [PATCH 21/39] File item 536: cut a patch release with deploy-release --cut-patch --- todo.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index dad74be6..d6ff97a4 100644 --- a/todo.md +++ b/todo.md @@ -6,13 +6,14 @@ `Bar = 0.1` -`Next ID = 536` +`Next ID = 537` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 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 | +| 536 | 0.16.0 | | owner | **Cut a patch release with `deploy-release --cut-patch `: the newest tag plus only the commits named, tested with `ci.sh`, tagged, merged back into main and deployed.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 3 | 0.6 | | 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 | | 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 | @@ -123,6 +124,27 @@ Touches: - `bin/task_bench/main.py`: `(module)` (small) - `README.md`: `## Tools` (small) +### 536. Cut a patch release with `deploy-release --cut-patch `: the newest tag plus only the commits named, tested with `ci.sh`, tagged, merged back into main and deployed. + +Today a fix that must ship before `main`'s other unreleased work is cut by hand, as 0.15.1 was: branch off the newest tag, apply only the fix's code, write the changelog section, commit `Cut release `, tag and push, then merge the tag back into `main` with `-s ours` through a pull request, so the tag is an ancestor of `main`, and run a bare `deploy-release`. `deploy-release --cut` can't, since it cuts all of `main`. + +`deploy-release --cut-patch []`, run in the development clone, does those steps. A reader panel picked the spelling over `--cut --patch` and `--hotfix`: one flag that names the action and can't be read as a plain `--cut`. + +- **Version:** the newest tag's next patch, such as 0.15.2 after v0.15.1. The plan must name that release, and it must hold no item, as `--cut` checks. A patch skips the release review: it holds only fixes, and the review is of the whole project. +- **Commits:** one revision as `git log` reads it, such as `794ce37..1aa2367`, which follows git's `..` and leaves out the first commit, or one commit. Each must be on `origin/main` and not on the tag. Merge commits are skipped. +- **Patch:** in a worktree of its own, at the tag, it applies each commit's changes except to `todo.md`, `CHANGELOG.md` and the records every chunk writes. The changelog section is the bullets the commits add under `## Unreleased`. It commits `Cut release `, runs `ci.sh` on it, and stops where that fails. Then it tags and pushes the tag. +- **Merge-back:** a branch `release-` off `origin/main` merges the tag with `-s ours` and moves those bullets under `## `, and goes through a pull request as `--cut`'s branch does. +- **Rerun:** a step an earlier run finished is skipped: a tag on origin, a tag `main` holds. +- **Plain `--cut`** refuses a patch release and names `--cut-patch`, since it would ship all of `main` under a patch number. + +Touches: +- `bin/deploy_release/main.py`: `main` +- `bin/deploy_release/cut.py`: `cut`, `ready_release`, `land`, `push_cut_commit` +- `bin/deploy_release/patch.py` +- `bin/deploy_release/release_pull.py`: `create_pull` (small) +- `bin/deploy_release/test_deploy_release.py`: `Cut` +- `README.md`: `## Release`, `## Tools` (small) + ### 524. Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names. The second part of item 504, which says what a bench feature is and when a run counts. A stronger model than the project's writes the six, once. Each breaks one of fejkdata's goals while it would suit another audience: From 9c2587b5cab8e90d8e2137d453e33ce68528d128 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:09:56 +0100 Subject: [PATCH 22/39] Cut a patch release of only the commits named with deploy-release --cut-patch --- README.md | 10 +- bin/deploy_release/cut.py | 41 +++-- bin/deploy_release/main.py | 39 ++++- bin/deploy_release/patch.py | 192 ++++++++++++++++++++++ bin/deploy_release/release_pull.py | 6 +- bin/deploy_release/test_deploy_release.py | 125 +++++++++++++- 6 files changed, 389 insertions(+), 24 deletions(-) create mode 100644 bin/deploy_release/patch.py diff --git a/README.md b/README.md index 2124de54..c3ecb654 100644 --- a/README.md +++ b/README.md @@ -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`, 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 with the commits the chunk merged, as a range or one commit: + +```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. `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 [] [--calls ]` 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 ` 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] []` 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 ] []` 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 ` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-`, 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 --dry-run` prints what `do-epic ` 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 [--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. diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 9245079b..04330f08 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -16,12 +16,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 +40,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 +64,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 , 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) @@ -116,8 +133,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 +146,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 +169,12 @@ 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- 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 with build 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 the branch's commit on ref: a new branch, or in place of the commit it names, origin's branch's head.""" 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 +183,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 +191,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): diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index c9a827e5..ec856427 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -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] [] +usage: deploy-release [--cut | --cut-patch ] [] 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, @@ -34,7 +34,25 @@ It says on stderr as each step finishes, and ends stdout, after the changelog, w Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the -move stopped, fix what it names and run a bare deploy-release. +move stopped, fix what it names and run a bare deploy-release. --cut 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. + +--cut-patch 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, such as 0.15.2 after v0.15.1, holding only on top of the tag. +is one revision as git log reads it: a range such as 794ce37..1aa2367, which leaves out 794ce37 as git's `..` does, or one +commit. Each must be on origin's main and not in the tag; merge commits are left out. Name the commit that finished the +fix's item too: its entries under ## Unreleased in CHANGELOG.md become the release's. todo.md must name the release and file +no item under it; a patch skips the release review. It refuses without changing anything where any of that doesn't hold. +1. In a worktree of its own at the tag, it applies each commit's changes, except to todo.md, CHANGELOG.md and the records + every chunk appends to, heads CHANGELOG.md with the release's section, and commits that titled `Cut release `. + Where a commit doesn't apply, it stops and names it: cut that patch by hand. +2. It runs ci.sh on that commit, and stops where it fails, before anything is tagged. +3. It tags the commit v, annotated `Cut release `, and pushes only the tag. +4. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a + ## section, commits that titled `Merge release into main`, and lands it through the branch + release- and a pull request as --cut does, so the tag is in main's history. +5. It moves to the tag as above, and ends stdout as --cut does. +A rerun skips a tag origin holds already and a merge main holds already. """ import os import pathlib @@ -43,6 +61,7 @@ import time from deploy_release.cut import cut from deploy_release.deploy import deploy +from deploy_release.patch import cut_patch from failure import Failure @@ -50,13 +69,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] []", 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 ] []", 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 diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py new file mode 100644 index 00000000..83972eba --- /dev/null +++ b/bin/deploy_release/patch.py @@ -0,0 +1,192 @@ +"""`deploy-release --cut-patch `: 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. + +Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped. +""" +import pathlib +import re +import shutil +import subprocess +import tempfile +import typing + +from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, ready_release, said, same_origin +from deploy_release.deploy import deploy +from failure import Failure +from git_cli.git_repo import default_ref, git +from plan.release import newest_tag, Release, tagged, UNRELEASED_TITLE, version +from text_files.markdown_text import section + +# The files a patch leaves as the tag holds them: the plan, the changelog the cut writes itself, and the records every chunk appends to, which seldom apply on an older tag. +LEFT_AS_TAGGED = ("todo.md", "CHANGELOG.md", "docs/reading-cost.md", "docs/comprehension-history.md") +MERGE_BACK_BODY = "Merge the patch release's tag into main, keeping main's files, and list its changelog entries under its version." + + +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 one revision as git log reads it, or one commit.""" + if isinstance(same := same_origin(clone, checkout), Failure): + return same + 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_release = tagged(base) + if base is None or cut_release is None: + return Failure(f"{ref} holds no v* tag to cut a patch of") + named = version((cut_release[0], cut_release[1], cut_release[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) + if isinstance(entries, Failure): + return entries + title, tag = f"Cut release {named}", f"v{named}" + pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone) + if isinstance(pushed, Failure): + return pushed + if not pushed.strip(): + if isinstance(made := tag_patch(clone, base, picked, entries, named, title), Failure): + return made + if isinstance(git("merge-base", "--is-ancestor", tag, ref, cwd=clone), Failure): + branch = f"release-{named}" + build = lambda replacing: push_merge_back(clone, ref, branch, tag, named, entries, replacing) + if isinstance(landed := land(clone, ref, branch, f"Merge release {named} into main", MERGE_BACK_BODY, build, sleep), Failure): + return landed + 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_commits(clone: str, ref: str, base: str, commits: str) -> list[str] | Failure: + """The commits commits names, oldest first, merge commits left out; a Failure where one is missing from ref or the tag base already holds it.""" + listed = git("rev-list", "--reverse", "--no-merges", 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 but merges") + 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 tag_patch(clone: str, base: str, commits: list[str], entries: list[str], named: str, title: str) -> Failure | None: + """In a worktree at the tag base, apply commits but for LEFT_AS_TAGGED, head CHANGELOG.md with entries under ## named, commit that titled title, test it with ci.sh, then tag it v and push the tag.""" + tag = f"v{named}" + worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "patch" + try: + if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), base, cwd=clone), Failure): + return added + for commit in commits: + if isinstance(applied := apply_commit(clone, worktree, commit, base), Failure): + return applied + changelog = worktree / "CHANGELOG.md" + text = changelog.read_text() if changelog.exists() else "# Changelog\n" + section_text = f"## {named}\n\n" + "\n".join(entries) + "\n\n" + headed, count = re.subn(r"^## ", lambda _: section_text + "## ", text, count=1, flags=re.M) + changelog.write_text(headed if count else text.rstrip("\n") + "\n\n" + section_text.rstrip("\n") + "\n") + if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure): + return committed + said(f"applied {len(commits)} commit(s) on {base}; testing them with ci.sh") + if isinstance(tested := run_ci(worktree), 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 + finally: + git("worktree", "remove", "--force", str(worktree), cwd=clone) + shutil.rmtree(worktree.parent, ignore_errors=True) + + +def apply_commit(clone: str, worktree: pathlib.Path, commit: str, base: str) -> Failure | None: + """Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the tag base'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 = worktree.parent / "commit.patch" + patch.write_text(diff) + if isinstance(applied := git("apply", "--3way", "--index", str(patch), 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 {base}: {applied.reason}. Cut this patch by hand.") + return None + + +def run_ci(worktree: pathlib.Path) -> 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:\n{tail}") + + +def push_merge_back(clone: str, ref: str, branch: str, tag: str, named: str, entries: list[str], replacing: str | None) -> Failure | None: + """On ref, merge tag keeping ref's files, with entries moved from ## Unreleased to a ## named section after it, in a worktree of its own; push that 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-")) / "merge-back" + try: + if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure): + return added + if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", tag, cwd=str(worktree)), Failure): + return merged + changelog = worktree / "CHANGELOG.md" + changelog.write_text(moved_entries(changelog.read_text(), entries, named)) + if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {named} into main", 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 + finally: + git("worktree", "remove", "--force", str(worktree), cwd=clone) + shutil.rmtree(worktree.parent, ignore_errors=True) + + +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 after it.""" + 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:]]) diff --git a/bin/deploy_release/release_pull.py b/bin/deploy_release/release_pull.py index 5d919e01..31bf0e3b 100644 --- a/bin/deploy_release/release_pull.py +++ b/bin/deploy_release/release_pull.py @@ -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 diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 851a1487..25a830cb 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -248,7 +248,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,6 +469,129 @@ 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 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_changing_nothing_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_changing_nothing_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_or_origins_main_doesnt(self): + self.plan_patch() + for commit in ("v0.1.0", "HEAD"): + if commit == "HEAD": + self.commit({"tool.txt": "local\n"}, "Unpushed") + ran = self.cut_patch(commit) + self.assertEqual(ran.returncode, 1, commit) + self.assertIn(self.git(self.clone, "rev-parse", "--short", f"{commit}^{{commit}}").strip()[:7], ran.stderr) + self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "") + + 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_takes_no_option_but_cut(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) From 2cdd3460601aeb5ca73c95133d64aa80e9d1d964 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:10:29 +0100 Subject: [PATCH 23/39] Record the patch cut in the deploy decision --- docs/decisions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/decisions.md b/docs/decisions.md index fec9ae62..17e09a93 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -154,6 +154,8 @@ Valid while `~/.claude` is a checkout of this repo. 2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_plan/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release `, 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, todo item 536. `deploy-release --cut-patch ` 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, as 0.15.1 did by hand. Its commit sits on the tag, not on `main`, so no pull request 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. A patch skips the release review: it holds only fixes, and the review reads the whole project. `chunk-preflight` still calls that review 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. + ## 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. From 366a10cc0e2eea223c6ece12b4d75b7ab199a105 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:13:32 +0100 Subject: [PATCH 24/39] Sort deploy_release's imports by their first binding --- bin/deploy_release/main.py | 2 +- bin/deploy_release/patch.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index ec856427..d8ce8935 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -60,8 +60,8 @@ import sys import time from deploy_release.cut import cut -from deploy_release.deploy import deploy from deploy_release.patch import cut_patch +from deploy_release.deploy import deploy from failure import Failure diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index 83972eba..427ab427 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -9,10 +9,10 @@ import subprocess import tempfile import typing +from git_cli.git_repo import default_ref, git from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, ready_release, said, same_origin from deploy_release.deploy import deploy from failure import Failure -from git_cli.git_repo import default_ref, git from plan.release import newest_tag, Release, tagged, UNRELEASED_TITLE, version from text_files.markdown_text import section From 459a3d5f54dc403cbc5d022e1e79681aa6c3177d Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:28:55 +0100 Subject: [PATCH 25/39] Note in item 462 that deploy-release's tests fail in mutmut's copy too --- todo.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/todo.md b/todo.md index d6ff97a4..0ec382db 100644 --- a/todo.md +++ b/todo.md @@ -322,6 +322,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 it too: `deploy_release/test_deploy_release.py`, which runs `deploy-release` as a subprocess, fails there, so none of 597 mutants of `bin/deploy_release/` was checked. + 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. From 39cb2f4d9e3e5da6081a9ccdc93b1120254ba3f2 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:29:51 +0100 Subject: [PATCH 26/39] Unit-test the patch cut's changelog edits in-process --- bin/deploy_release/patch.py | 14 ++++++++++---- bin/deploy_release/test_deploy_release.py | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index 427ab427..e0addadf 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -112,10 +112,7 @@ def tag_patch(clone: str, base: str, commits: list[str], entries: list[str], nam if isinstance(applied := apply_commit(clone, worktree, commit, base), Failure): return applied changelog = worktree / "CHANGELOG.md" - text = changelog.read_text() if changelog.exists() else "# Changelog\n" - section_text = f"## {named}\n\n" + "\n".join(entries) + "\n\n" - headed, count = re.subn(r"^## ", lambda _: section_text + "## ", text, count=1, flags=re.M) - changelog.write_text(headed if count else text.rstrip("\n") + "\n\n" + section_text.rstrip("\n") + "\n") + changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", entries, named)) if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure): return committed said(f"applied {len(commits)} commit(s) on {base}; testing them with ci.sh") @@ -135,6 +132,15 @@ def tag_patch(clone: str, base: str, commits: list[str], entries: list[str], nam shutil.rmtree(worktree.parent, ignore_errors=True) +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\n" + added + return changelog[:first.start()] + added + "\n" + changelog[first.start():] + + def apply_commit(clone: str, worktree: pathlib.Path, commit: str, base: str) -> Failure | None: """Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the tag base'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) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 25a830cb..d9012a33 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -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" @@ -611,5 +612,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_ends_a_changelog_with_no_section_with_the_patchs_section(self): + self.assertEqual(patch.headed("# Changelog\n\n", ["- Fixed."], "0.1.1"), "# Changelog\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() From 3f74d32caedb273c571f26074439aae8855d3e96 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:48:06 +0100 Subject: [PATCH 27/39] Kill the mutant that strips more than blank lines off a changelog with no section --- bin/deploy_release/patch.py | 2 +- bin/deploy_release/test_deploy_release.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index e0addadf..bb74dd86 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -137,7 +137,7 @@ def headed(changelog: str, entries: list[str], named: str) -> str: 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\n" + added + return changelog.rstrip() + "\n\n" + added return changelog[:first.start()] + added + "\n" + changelog[first.start():] diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index d9012a33..e10e8e04 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -619,7 +619,7 @@ class PatchChangelog(unittest.TestCase): 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_ends_a_changelog_with_no_section_with_the_patchs_section(self): - self.assertEqual(patch.headed("# Changelog\n\n", ["- Fixed."], "0.1.1"), "# Changelog\n\n## 0.1.1\n\n- Fixed.\n") + 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" From ec497aa9892ff0809e84363255b7fa49c25ec5b2 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 14:48:11 +0100 Subject: [PATCH 28/39] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?gs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From db32e4ef59b5fb9c1a570e7a3b426f4665255d90 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 15:12:17 +0100 Subject: [PATCH 29/39] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20share=20the?= =?UTF-8?q?=20scratch=20worktree,=20check=20a=20reused=20tag=20and=20main'?= =?UTF-8?q?s=20merge-back,=20refuse=20GitHub,=20split=20the=20looped=20tes?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- bin/deploy_release/cut.py | 38 +++-- bin/deploy_release/main.py | 42 ++--- bin/deploy_release/patch.py | 182 +++++++++++++--------- bin/deploy_release/test_deploy_release.py | 70 +++++++-- bin/release_plan/release_standing.py | 5 +- bin/release_plan/test_release_standing.py | 18 +++ docs/decisions.md | 4 +- todo.md | 10 +- 9 files changed, 249 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index c3ecb654..cc7f636d 100644 --- a/README.md +++ b/README.md @@ -198,13 +198,13 @@ 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`, 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 with the commits the chunk merged, as a range or one commit: +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. `deploy-release --help` lists the steps. +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 diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 04330f08..b6f795af 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -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 @@ -117,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 @@ -170,7 +171,9 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: 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 with build 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 the branch's commit on ref: a new branch, or in place of the commit it names, origin's branch's head.""" + """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 @@ -225,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: @@ -237,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 diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index d8ce8935..ff665415 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -18,7 +18,9 @@ memory, stay as they are. --cut runs in the development clone, and refuses where that clone's origin isn't '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 `, and pushes it as the branch release-. The clone's own checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main. @@ -34,25 +36,29 @@ It says on stderr as each step finishes, and ends stdout, after the changelog, w Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the -move stopped, fix what it names and run a bare deploy-release. --cut 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. +move stopped, fix what it names and run a bare deploy-release. --cut-patch 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, such as 0.15.2 after v0.15.1, holding only on top of the tag. -is one revision as git log reads it: a range such as 794ce37..1aa2367, which leaves out 794ce37 as git's `..` does, or one -commit. Each must be on origin's main and not in the tag; merge commits are left out. Name the commit that finished the -fix's item too: its entries under ## Unreleased in CHANGELOG.md become the release's. todo.md must name the release and file -no item under it; a patch skips the release review. It refuses without changing anything where any of that doesn't hold. -1. In a worktree of its own at the tag, it applies each commit's changes, except to todo.md, CHANGELOG.md and the records - every chunk appends to, heads CHANGELOG.md with the release's section, and commits that titled `Cut release `. - Where a commit doesn't apply, it stops and names it: cut that patch by hand. -2. It runs ci.sh on that commit, and stops where it fails, before anything is tagged. -3. It tags the commit v, annotated `Cut release `, and pushes only the tag. -4. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a - ## section, commits that titled `Merge release into main`, and lands it through the branch - release- and a pull request as --cut does, so the tag is in main's history. -5. It moves to the tag as above, and ends stdout as --cut does. -A rerun skips a tag origin holds already and a merge main holds already. +cuts the newest tag's next patch release, holding only on top of the tag. 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 `. 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, annotated `Cut release `, 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 + ## section below it, commits that titled `Merge release into main`, and lands it through the branch + release- and a pull request as --cut does. Then it checks main holds the tag. +6. It moves 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 diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index bb74dd86..5e31b394 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -1,30 +1,79 @@ """`deploy-release --cut-patch `: 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. -Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped. +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 shutil import subprocess -import tempfile import typing from git_cli.git_repo import default_ref, git -from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, ready_release, said, same_origin +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 plan.release import newest_tag, Release, tagged, UNRELEASED_TITLE, version +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 plan, the changelog the cut writes itself, and the records every chunk appends to, which seldom apply on an older tag. -LEFT_AS_TAGGED = ("todo.md", "CHANGELOG.md", "docs/reading-cost.md", "docs/comprehension-history.md") +# 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 one revision as git log reads it, or one commit.""" + """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): @@ -35,10 +84,10 @@ def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[f base = newest_tag(clone, merged_into=ref) if isinstance(base, Failure): return base - cut_release = tagged(base) - if base is None or cut_release is None: - return Failure(f"{ref} holds no v* tag to cut a patch of") - named = version((cut_release[0], cut_release[1], cut_release[2] + 1)) + 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): @@ -49,35 +98,17 @@ def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[f if isinstance(picked, Failure): return picked entries = changelog_entries(clone, ref, picked) - if isinstance(entries, Failure): - return entries - title, tag = f"Cut release {named}", f"v{named}" - pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone) - if isinstance(pushed, Failure): - return pushed - if not pushed.strip(): - if isinstance(made := tag_patch(clone, base, picked, entries, named, title), Failure): - return made - if isinstance(git("merge-base", "--is-ancestor", tag, ref, cwd=clone), Failure): - branch = f"release-{named}" - build = lambda replacing: push_merge_back(clone, ref, branch, tag, named, entries, replacing) - if isinstance(landed := land(clone, ref, branch, f"Merge release {named} into main", MERGE_BACK_BODY, build, sleep), Failure): - return landed - 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." + 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 left out; a Failure where one is missing from ref or the tag base already holds it.""" - listed = git("rev-list", "--reverse", "--no-merges", commits if ".." in commits else f"{commits}^!", "--", cwd=clone) + """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 but merges") + return Failure(f"{commits} names no commit that isn't a merge: write a range as ..") 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") @@ -101,22 +132,32 @@ def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | F 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 tag_patch(clone: str, base: str, commits: list[str], entries: list[str], named: str, title: str) -> Failure | None: - """In a worktree at the tag base, apply commits but for LEFT_AS_TAGGED, head CHANGELOG.md with entries under ## named, commit that titled title, test it with ci.sh, then tag it v and push the tag.""" - tag = f"v{named}" - worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "patch" - try: - if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), base, cwd=clone), Failure): - return added - for commit in commits: - if isinstance(applied := apply_commit(clone, worktree, commit, base), Failure): +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 than the commits named: name the commits it was cut from") + 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 `, 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", entries, named)) + 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 {len(commits)} commit(s) on {base}; testing them with ci.sh") - if isinstance(tested := run_ci(worktree), Failure): + 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): @@ -127,9 +168,6 @@ def tag_patch(clone: str, base: str, commits: list[str], entries: list[str], nam return pushed said(f"pushed the tag {tag}") return None - finally: - git("worktree", "remove", "--force", str(worktree), cwd=clone) - shutil.rmtree(worktree.parent, ignore_errors=True) def headed(changelog: str, entries: list[str], named: str) -> str: @@ -141,22 +179,26 @@ def headed(changelog: str, entries: list[str], named: str) -> str: return changelog[:first.start()] + added + "\n" + changelog[first.start():] -def apply_commit(clone: str, worktree: pathlib.Path, commit: str, base: str) -> Failure | None: - """Apply commit's change, but for LEFT_AS_TAGGED, to worktree's index and files, merging three ways where the tag base's files differ from commit's parent.""" +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 = worktree.parent / "commit.patch" - patch.write_text(diff) - if isinstance(applied := git("apply", "--3way", "--index", str(patch), cwd=str(worktree)), Failure): + 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 {base}: {applied.reason}. Cut this patch by hand.") + 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 CHANGELOG.md's ## {patch.named} section, commit that titled `Cut release {patch.named}`, " + f"tag it v{patch.named}, annotated with that title, and push the tag. A rerun then merges it back and deploys it." + ) return None -def run_ci(worktree: pathlib.Path) -> Failure | 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") @@ -164,31 +206,25 @@ def run_ci(worktree: pathlib.Path) -> Failure | None: 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:\n{tail}") + 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, ref: str, branch: str, tag: str, named: str, entries: list[str], replacing: str | None) -> Failure | None: - """On ref, merge tag keeping ref's files, with entries moved from ## Unreleased to a ## named section after it, in a worktree of its own; push that 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-")) / "merge-back" - try: - if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure): - return added - if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", tag, cwd=str(worktree)), Failure): +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 ## section below ## Unreleased, and push that as the branch release-, 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(), entries, named)) - if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {named} into main", cwd=str(worktree)), Failure): + 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 - 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 - finally: - git("worktree", "remove", "--force", str(worktree), cwd=clone) - shutil.rmtree(worktree.parent, ignore_errors=True) + 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 after it.""" + """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)) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index e10e8e04..8ed6f5d8 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -508,7 +508,7 @@ class Cut(unittest.TestCase): self.assertEqual(ran.returncode, 0, ran.stderr) self.assertEqual(self.origin_git("show", "v0.1.1:tool.txt"), "fixed\n") - def test_refuses_changing_nothing_where_the_plan_names_no_patch_release(self): + 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") @@ -517,7 +517,7 @@ class Cut(unittest.TestCase): self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "") self.assertEqual(self.forge_state()["pulls"], []) - def test_refuses_changing_nothing_while_the_patch_release_holds_an_item(self): + 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") @@ -532,16 +532,64 @@ class Cut(unittest.TestCase): ran = self.cut_patch(self.plan_patch()) self.assertEqual(ran.returncode, 0, ran.stderr) - def test_refuses_a_commit_the_tag_holds_or_origins_main_doesnt(self): + def test_refuses_a_commit_the_tag_holds(self): self.plan_patch() - for commit in ("v0.1.0", "HEAD"): - if commit == "HEAD": - self.commit({"tool.txt": "local\n"}, "Unpushed") - ran = self.cut_patch(commit) - self.assertEqual(ran.returncode, 1, commit) - self.assertIn(self.git(self.clone, "rev-parse", "--short", f"{commit}^{{commit}}").strip()[:7], ran.stderr) + 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_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("other changelog entries", 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") @@ -593,7 +641,7 @@ class Cut(unittest.TestCase): self.assertIn("usage", ran.stderr) self.assertEqual(self.forge_state()["calls"], []) - def test_takes_no_option_but_cut(self): + 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) @@ -618,7 +666,7 @@ class PatchChangelog(unittest.TestCase): 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_ends_a_changelog_with_no_section_with_the_patchs_section(self): + 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): diff --git a/bin/release_plan/release_standing.py b/bin/release_plan/release_standing.py index 427b5371..e4ef5bc8 100644 --- a/bin/release_plan/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -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 `: 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: diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 36c52749..349f5854 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -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]) diff --git a/docs/decisions.md b/docs/decisions.md index 17e09a93..2442b5a4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -150,11 +150,11 @@ 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 `, 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, todo item 536. `deploy-release --cut-patch ` 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, as 0.15.1 did by hand. Its commit sits on the tag, not on `main`, so no pull request 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. A patch skips the release review: it holds only fixes, and the review reads the whole project. `chunk-preflight` still calls that review 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. +2026-11-24, lilleman, todo item 536. `deploy-release --cut-patch ` 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 diff --git a/todo.md b/todo.md index 0ec382db..bb1fd1cc 100644 --- a/todo.md +++ b/todo.md @@ -128,22 +128,22 @@ Touches: Today a fix that must ship before `main`'s other unreleased work is cut by hand, as 0.15.1 was: branch off the newest tag, apply only the fix's code, write the changelog section, commit `Cut release `, tag and push, then merge the tag back into `main` with `-s ours` through a pull request, so the tag is an ancestor of `main`, and run a bare `deploy-release`. `deploy-release --cut` can't, since it cuts all of `main`. -`deploy-release --cut-patch []`, run in the development clone, does those steps. A reader panel picked the spelling over `--cut --patch` and `--hotfix`: one flag that names the action and can't be read as a plain `--cut`. +`deploy-release --cut-patch []`, run in the development clone, does those steps; `docs/decisions.md` → "deploy: `deploy-release --cut` cuts a release …" says why it is spelled so. - **Version:** the newest tag's next patch, such as 0.15.2 after v0.15.1. The plan must name that release, and it must hold no item, as `--cut` checks. A patch skips the release review: it holds only fixes, and the review is of the whole project. - **Commits:** one revision as `git log` reads it, such as `794ce37..1aa2367`, which follows git's `..` and leaves out the first commit, or one commit. Each must be on `origin/main` and not on the tag. Merge commits are skipped. - **Patch:** in a worktree of its own, at the tag, it applies each commit's changes except to `todo.md`, `CHANGELOG.md` and the records every chunk writes. The changelog section is the bullets the commits add under `## Unreleased`. It commits `Cut release `, runs `ci.sh` on it, and stops where that fails. Then it tags and pushes the tag. - **Merge-back:** a branch `release-` off `origin/main` merges the tag with `-s ours` and moves those bullets under `## `, and goes through a pull request as `--cut`'s branch does. -- **Rerun:** a step an earlier run finished is skipped: a tag on origin, a tag `main` holds. +- **Rerun:** it takes a tag origin holds, once the tag lists the same changelog entries, and the merge-back's open pull request. - **Plain `--cut`** refuses a patch release and names `--cut-patch`, since it would ship all of `main` under a patch number. Touches: +- `README.md`: `## Release`, `## Tools` (small) +- `bin/deploy_release/cut.py`: `cut`, `land`, `push_cut_commit`, `ready_release` - `bin/deploy_release/main.py`: `main` -- `bin/deploy_release/cut.py`: `cut`, `ready_release`, `land`, `push_cut_commit` - `bin/deploy_release/patch.py` - `bin/deploy_release/release_pull.py`: `create_pull` (small) - `bin/deploy_release/test_deploy_release.py`: `Cut` -- `README.md`: `## Release`, `## Tools` (small) ### 524. Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names. @@ -322,7 +322,7 @@ 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 it too: `deploy_release/test_deploy_release.py`, which runs `deploy-release` as a subprocess, fails there, so none of 597 mutants of `bin/deploy_release/` was checked. +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. From 010be0c9e75c9a0dffe9830500be0544eac5f04d Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 15:12:17 +0100 Subject: [PATCH 30/39] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20a=20patc?= =?UTF-8?q?h's=20review=20no=20longer=20counts=20for=20the=20next=20releas?= =?UTF-8?q?e,=20the=20help=20says=20what=20a=20rerun=20does,=20and=20the?= =?UTF-8?q?=20cut=20lists=20the=20commits=20it=20ships,=20in=20the=20stabi?= =?UTF-8?q?lity=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 0a38f99a8d79888270ddab9ba470508e2d4ab1e9 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 15:12:17 +0100 Subject: [PATCH 31/39] =?UTF-8?q?Answer=20prose=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20true=20reru?= =?UTF-8?q?n=20and=20range=20text,=20clearer=20refusals=20and=20test=20nam?= =?UTF-8?q?es,=20and=20the=20decision=20names=20its=20choices,=20in=20the?= =?UTF-8?q?=20stability=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From a1e6791cdb59cc0cca2fcfc0e67d1c2b657ce93c Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 15:35:08 +0100 Subject: [PATCH 32/39] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20the=20hand-?= =?UTF-8?q?cut=20steps=20and=20the=20reused=20tag's=20refusal=20list=20the?= =?UTF-8?q?=20exact=20entries,=20and=20a=20hand=20cut=20reruns=20to=20the?= =?UTF-8?q?=20end?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/deploy_release/patch.py | 7 ++++--- bin/deploy_release/test_deploy_release.py | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/bin/deploy_release/patch.py b/bin/deploy_release/patch.py index 5e31b394..4f349905 100644 --- a/bin/deploy_release/patch.py +++ b/bin/deploy_release/patch.py @@ -139,7 +139,7 @@ def tagged_entries(clone: str, patch: Patch) -> Failure | None: 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 than the commits named: name the commits it was cut from") + 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 @@ -192,8 +192,9 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch) 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 CHANGELOG.md's ## {patch.named} section, commit that titled `Cut release {patch.named}`, " - f"tag it v{patch.named}, annotated with that title, and push the tag. A rerun then merges it back and deploys it." + 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 diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 8ed6f5d8..c8d2499e 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -578,6 +578,24 @@ class Cut(unittest.TestCase): 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() @@ -587,7 +605,7 @@ class Cut(unittest.TestCase): self.set_checks("success") ran = self.cut_patch("HEAD") self.assertEqual(ran.returncode, 1) - self.assertIn("other changelog entries", ran.stderr) + 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): From a38dad4a6cfe0408fbbcf1f35b14654a54f80e21 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 15:38:23 +0100 Subject: [PATCH 33/39] Finish item 536 in the plan --- CHANGELOG.md | 1 + todo.md | 22 ---------------------- 2 files changed, 1 insertion(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b405a0b3..6475fcf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `deploy-release --cut-patch ` 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 ` sets how many it takes, and a feature whose branch landed by fast-forward is passed over. - `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. diff --git a/todo.md b/todo.md index bb1fd1cc..21640c83 100644 --- a/todo.md +++ b/todo.md @@ -13,7 +13,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 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 | -| 536 | 0.16.0 | | owner | **Cut a patch release with `deploy-release --cut-patch `: the newest tag plus only the commits named, tested with `ci.sh`, tagged, merged back into main and deployed.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 3 | 0.6 | | 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 | | 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 | @@ -124,27 +123,6 @@ Touches: - `bin/task_bench/main.py`: `(module)` (small) - `README.md`: `## Tools` (small) -### 536. Cut a patch release with `deploy-release --cut-patch `: the newest tag plus only the commits named, tested with `ci.sh`, tagged, merged back into main and deployed. - -Today a fix that must ship before `main`'s other unreleased work is cut by hand, as 0.15.1 was: branch off the newest tag, apply only the fix's code, write the changelog section, commit `Cut release `, tag and push, then merge the tag back into `main` with `-s ours` through a pull request, so the tag is an ancestor of `main`, and run a bare `deploy-release`. `deploy-release --cut` can't, since it cuts all of `main`. - -`deploy-release --cut-patch []`, run in the development clone, does those steps; `docs/decisions.md` → "deploy: `deploy-release --cut` cuts a release …" says why it is spelled so. - -- **Version:** the newest tag's next patch, such as 0.15.2 after v0.15.1. The plan must name that release, and it must hold no item, as `--cut` checks. A patch skips the release review: it holds only fixes, and the review is of the whole project. -- **Commits:** one revision as `git log` reads it, such as `794ce37..1aa2367`, which follows git's `..` and leaves out the first commit, or one commit. Each must be on `origin/main` and not on the tag. Merge commits are skipped. -- **Patch:** in a worktree of its own, at the tag, it applies each commit's changes except to `todo.md`, `CHANGELOG.md` and the records every chunk writes. The changelog section is the bullets the commits add under `## Unreleased`. It commits `Cut release `, runs `ci.sh` on it, and stops where that fails. Then it tags and pushes the tag. -- **Merge-back:** a branch `release-` off `origin/main` merges the tag with `-s ours` and moves those bullets under `## `, and goes through a pull request as `--cut`'s branch does. -- **Rerun:** it takes a tag origin holds, once the tag lists the same changelog entries, and the merge-back's open pull request. -- **Plain `--cut`** refuses a patch release and names `--cut-patch`, since it would ship all of `main` under a patch number. - -Touches: -- `README.md`: `## Release`, `## Tools` (small) -- `bin/deploy_release/cut.py`: `cut`, `land`, `push_cut_commit`, `ready_release` -- `bin/deploy_release/main.py`: `main` -- `bin/deploy_release/patch.py` -- `bin/deploy_release/release_pull.py`: `create_pull` (small) -- `bin/deploy_release/test_deploy_release.py`: `Cut` - ### 524. Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names. The second part of item 504, which says what a bench feature is and when a run counts. A stronger model than the project's writes the six, once. Each breaks one of fejkdata's goals while it would suit another audience: From 4bad84d087069dd518288c7db6f5d534887cbb47 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Tue, 24 Nov 2026 20:41:01 +0100 Subject: [PATCH 34/39] File item 537: flag $ anchors in whole-input validation regexes --- todo.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 21640c83..8d60a08b 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 537` +`Next ID = 538` ## Items @@ -21,6 +21,7 @@ | 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 | | 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/`, 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 | @@ -199,6 +200,13 @@ 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) + ### 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. From a70ea1a726c2db0efef6a8018756d06e8b0eed37 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Wed, 25 Nov 2026 08:58:18 +0100 Subject: [PATCH 35/39] File item 538: flag validation of a value other than the one the code uses --- todo.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 8d60a08b..992c34f4 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 538` +`Next ID = 539` ## Items @@ -22,6 +22,7 @@ | 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/`, 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 | @@ -207,6 +208,13 @@ An outside auto-reviewer found a validation regex anchored with `$` that accepte 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. From 4fbb0ede2d2150fde0f1bfea48518bff996b032c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 25 Nov 2026 23:00:46 +0100 Subject: [PATCH 36/39] Keep the routing ladder, the steps and the delegation rule against the calls of 2026-11-25 --- docs/decisions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/decisions.md b/docs/decisions.md index 2442b5a4..5cdd53b6 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -726,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 From 3d8c00617bd6403c931547724730f7c42abff00e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 25 Nov 2026 23:15:47 +0100 Subject: [PATCH 37/39] Record the reading cost of chunk 242dc2ee7cca, which a broken worktree kept out of the repo --- docs/reading-cost.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index f2efc71c..9bce7b73 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -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 From fc05048180610d294b56389c2cf1a9460ba65553 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 25 Nov 2026 23:28:09 +0100 Subject: [PATCH 38/39] File item 539: start a fresh session where its transcript is empty --- todo.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 992c34f4..5095e545 100644 --- a/todo.md +++ b/todo.md @@ -6,12 +6,13 @@ `Bar = 0.1` -`Next ID = 539` +`Next ID = 540` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| +| 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 | | 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 | @@ -112,6 +113,16 @@ ## Details +### 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 `.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 `. 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. From 88e94d5980b14370242023a951044e622a57d816 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 25 Nov 2026 23:30:01 +0100 Subject: [PATCH 39/39] File item 540: review once more each prose fix that rewrites a checkable claim --- todo.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 992c34f4..d074a0d6 100644 --- a/todo.md +++ b/todo.md @@ -6,12 +6,13 @@ `Bar = 0.1` -`Next ID = 539` +`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 | | 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 | | 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 | @@ -112,6 +113,20 @@ ## 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) + ### 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.