Answer principles round 1: 0 🔴, 1 🟡 (0 misread); bound and stream a patch cut's ci.sh, keep a trace of each deploy-release run, fail on file errors and a missing Unreleased heading, read the plan once per cut, one home for the review title, inject task-bench's container names, one spelling of its task kind
CI / tests (pull_request) Has been cancelled

This commit is contained in:
2026-11-27 11:57:54 +01:00
parent f8ad35c1f9
commit 4fc4763710
16 changed files with 627 additions and 157 deletions
+1
View File
@@ -9,6 +9,7 @@
- loop-claude starts a chunk on a fresh session where its session's transcript is empty, in place of resuming a session claude cannot find, which failed three times and waited for the human.
- larv-review's prose pass takes a second round after a fix that rewrites a claim a command or a source file can check, such as generated output, a number or a licence term.
- `deploy-release --cut-patch <commits>` cuts the newest tag's next patch release, such as 0.15.2 after v0.15.1, holding only the commits named, for a fix that must ship before main's other unreleased work. It runs `ci.sh` on the patch, tags and pushes it, merges the tag back into main through a pull request, and moves `~/.claude` to it. Plain `--cut` now refuses a patch release, and a release review counts only for the release its title names: `Release review of 0.16.0` reviews 0.16.0 and no other.
- `deploy-release` keeps each run's steps, with their times, in a file under `~/.local/state/deploy-release/`, and stops a patch cut's `ci.sh` after 30 minutes, naming the log that holds its output.
- `task-bench` plants bugs in Rust files too, from the mutants cargo-mutants catches, and tells Haiku the panic message `cargo test` prints.
- `task-bench --tasks shipped-features` benches rebuilding features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of its plan item, and checks the build with the tests that change holds. `--shipped <n>` sets how many it takes, and a feature whose branch landed by fast-forward starts after the latest earlier chunk that shipped an item or landed by a merge or a rebase, and is passed over where none comes before it or its branch merged the default branch into itself.
- `task-bench` plants a Python mutant in a file whose lines end in CRLF, which it could not re-apply before, and a Go mutant there keeps applying.
+1 -1
View File
@@ -196,7 +196,7 @@ Once the next release holds no item in `todo.md` and its release review has land
bin/deploy-release --cut
```
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time, in a file of its own under `~/.local/state/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first:
+55
View File
@@ -0,0 +1,55 @@
"""Run a patch's ci.sh with its output in a file the human can follow, and stop it where it runs too long."""
import contextlib
import os
import pathlib
import signal
import subprocess
from deploy_release.patch import Ci, CiRan
from failure import Failure
from deploy_release.trace import Say
# As long as forge.pulls waits for a pull request's checks, which run the same ci.sh.
CI_SECONDS = 30 * 60
# How long a stopped ci.sh has to end on SIGINT, which a container's CLI passes on to its container, before it is killed.
GRACE_SECONDS = 10
def ci_runner(log: pathlib.Path, seconds: float, say: Say, grace: float = GRACE_SECONDS) -> Ci:
"""Runs ci.sh in a worktree with its output in log, as it comes. A Failure where it can't start, where log can't be written, or where it still runs after seconds, which stops it and each process it started."""
def run(worktree: pathlib.Path) -> CiRan | Failure:
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
try:
with log.open("w", encoding="utf-8") as output:
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
try:
code = process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
stopped(process, grace)
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped; {log} holds its output")
except BaseException:
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
stopped(process, grace)
raise
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
except OSError as failure:
return Failure(f"ci.sh could not run: {failure}")
return run
def stopped(process: subprocess.Popen[bytes], grace: float) -> None:
"""End process's whole group: SIGINT first, then SIGKILL once grace seconds have passed."""
try:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=grace)
finally:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def lasting(seconds: float) -> str:
return f"{seconds / 60:g} minutes" if seconds >= 60 else f"{seconds:g} seconds"
+56 -40
View File
@@ -3,9 +3,9 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import contextlib
import dataclasses
import pathlib
import shutil
import sys
import tempfile
import typing
@@ -20,14 +20,23 @@ from forge.commands import forge_of, runner
from plan.release import newest_tag, Release, tagged, UNRELEASED_HEADING, version
from forge import pulls
from deploy_release import release_pull
from deploy_release.trace import Say
from project_config import templates
CUT_BODY = "Rename ## Unreleased in CHANGELOG.md to the version."
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
@dataclasses.dataclass(frozen=True)
class Ready:
"""The next release, which holds no item in todo.md while changes are unreleased."""
release: Release
# Whether its release review has landed.
reviewed: bool
def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None], say: Say) -> str | Failure:
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped. say takes each step as it finishes."""
if isinstance(same := same_origin(clone, checkout), Failure):
return same
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
@@ -37,20 +46,20 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
ref = default_ref(cwd=clone)
if isinstance(ref, Failure):
return ref
ready = ready_release(clone, ref)
if isinstance(ready, Failure):
return ready
named = version(ready.release)
# The patch refusal comes before the review's: a patch takes no release review, so "hasn't landed" would send the human the wrong way.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
named = version(release)
if isinstance(patched := patch_refusal(clone, ref, release), Failure):
if isinstance(patched := patch_refusal(clone, ref, ready.release), Failure):
return patched
if isinstance(reviewed := ready_release(clone, ref), Failure):
return reviewed
if not ready.reviewed:
return Failure(f"the release review of {named} hasn't landed")
title, tag, branch = f"Cut release {named}", f"v{named}", f"release-{named}"
merged = commit_titled(title, ref, clone)
if merged is None:
build = lambda replacing: push_cut_commit(clone, ref, branch, named, title, replacing)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep)
landed = land(clone, ref, branch, title, CUT_BODY, build, sleep, say)
if isinstance(landed, Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
@@ -62,13 +71,13 @@ def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str
return merged
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
return made
said(f"tagged {merged[:12]} {tag}")
say(f"tagged {merged[:12]} {tag}")
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
delete_release_branch(clone, branch)
say(f"pushed the tag {tag}")
delete_release_branch(clone, branch, say)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
@@ -86,21 +95,16 @@ def patch_refusal(clone: str, ref: str, release: Release) -> Failure | None:
return None
def said(step: str) -> None:
"""Say on stderr that step finished, so the human sees how far the cut got before the changelog fills the screen."""
print(f"deploy-release: {step}", file=sys.stderr)
def delete_release_branch(clone: str, branch: str) -> None:
def delete_release_branch(clone: str, branch: str, say: Say) -> None:
"""Delete origin's merged branch, where it is still there; only warn where that fails, since the release is cut by then."""
listed = branch_head(branch, clone)
if listed is None:
return
deleted = listed if isinstance(listed, Failure) else git("push", "--quiet", "origin", "--delete", f"refs/heads/{branch}", cwd=clone)
if isinstance(deleted, Failure):
said(f"warning: the branch {branch} stays on origin: {deleted.reason}")
say(f"warning: the branch {branch} stays on origin: {deleted.reason}")
else:
said(f"deleted the branch {branch} on origin")
say(f"deleted the branch {branch} on origin")
def drop_unpushed_cut_tags(clone: str) -> Failure | None:
@@ -137,23 +141,23 @@ def clone_plan(clone: str) -> FilePlan:
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str, review: bool = True) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed, unless review is False, and changes are unreleased."""
def ready_release(clone: str, ref: str) -> Ready | Failure:
"""The next release, as chunk-preflight works it out, where it holds no item in todo.md and changes are unreleased, with whether its release review has landed: the caller decides whether the cut needs one."""
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
if isinstance(plan.plan, Failure):
return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}")
match chunk_item(plan.plan.items, plan.cut):
case ReadyToCut(release=release) if release is not None:
return release
return Ready(release, reviewed=True)
case ReadyToCut():
return Failure("todo.md names no release after the last one cut")
case Next(release=release) if release is not None:
return Failure(f"release {version(release)} still holds items in todo.md")
case ReviewDue(release=release) if not review and release is not None:
return release
case ReviewDue(release=release):
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
case ReviewDue(release=release) if release is not None:
return Ready(release, reviewed=False)
case ReviewDue():
return Failure("the release review of the next release hasn't landed")
case Unplanned():
return Failure("every change is released already: nothing has landed since the last release cut")
case Cut(release=release):
@@ -173,7 +177,7 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None]) -> Failure | None:
def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing.Callable[[str | None], Failure | None], sleep: typing.Callable[[float], None], say: Say) -> Failure | None:
"""Push branch and open its pull request, titled title with body, where an earlier run hasn't; then wait for its checks and merge it.
build pushes branch's commit, made on ref. It takes the commit origin's branch points at, which the push replaces, or None where origin has no such branch yet."""
@@ -191,7 +195,7 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
if isinstance(pushed := build(head), Failure):
return pushed
said(f"pushed the branch {branch}")
say(f"pushed the branch {branch}")
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
if isinstance(head, Failure):
return head
@@ -201,19 +205,19 @@ def land(clone: str, ref: str, branch: str, title: str, body: str, build: typing
return created
number = pulls.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, str):
said(f"opened pull request {number}")
say(f"opened pull request {number}")
if isinstance(number, Failure):
return number
required = pulls.required_checks(on, base, run)
if isinstance(required, Failure):
return required
said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
say(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else ""))
if isinstance(passed := pulls.checks_passed(on, number, head, required, run, sleep), Failure):
return passed
said(f"the checks of pull request {number} passed")
say(f"the checks of pull request {number} passed")
if isinstance(merged := release_pull.merge(on, number, head, run), Failure):
return merged
said(f"merged pull request {number}")
say(f"merged pull request {number}")
return None
@@ -235,16 +239,28 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
with scratch_worktree(clone, ref) as worktree:
if isinstance(worktree, Failure):
return worktree
changelog = worktree / "CHANGELOG.md"
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
changelog.write_text(renamed)
def renamed(changelog: str | None) -> str | Failure:
text, count = UNRELEASED_HEADING.subn(f"## {named}", changelog or "", count=1)
return text if count else Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"rename ## Unreleased to ## {named} in the cut's worktree, so nothing is pushed", renamed), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, branch, replacing)
def rewritten(file: pathlib.Path, doing: str, rewrite: typing.Callable[[str | None], str | Failure]) -> Failure | None:
"""Replace file's text with what rewrite makes of it, or of None where there is no such file. A Failure where rewrite gives one, which leaves the file, or where the file can't be read or written: that one says doing, the step that stopped, and names the file."""
try:
text = rewrite(file.read_text(encoding="utf-8") if file.exists() else None)
if isinstance(text, Failure):
return text
file.write_text(text, encoding="utf-8")
except (OSError, UnicodeError) as failure:
return Failure(f"could not {doing}: {failure}" + ("" if str(file) in str(failure) else f" ({file})"))
return None
@contextlib.contextmanager
def scratch_worktree(clone: str, at: str) -> typing.Iterator[pathlib.Path | Failure]:
"""A worktree of clone, detached at at, in a folder of its own that is removed afterwards, so the clone's checkout stays as it is; a Failure where git can't add it."""
+27 -4
View File
@@ -33,6 +33,8 @@ with --cut-patch.
deletes the branch on origin, then moves <checkout> to the tag as above. A failed delete only warns.
It says on stderr as each step finishes, and ends stdout, after the changelog, with the line
`Done: v<version> is cut and pushed, and <checkout> is on it.`
It keeps each of those lines, with its time, in a file of the run's own under $XDG_STATE_HOME/deploy-release
(default ~/.local/state/deploy-release), and so does --cut-patch.
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
@@ -51,7 +53,8 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
docs/comprehension-history.md and docs/reading-cost.md, heads CHANGELOG.md with the release's section, and commits that
titled `Cut release <version>`. Where a commit doesn't apply, it stops, names it, and says how to cut the patch by hand.
3. It runs ci.sh on that commit, and stops where it fails, before anything is tagged.
3. It runs ci.sh on that commit, with its output in a file beside the run's trace, which it names on stderr. It stops
where ci.sh fails or still runs after 30 minutes, before anything is tagged.
4. It tags the commit v<version>, annotated `Cut release <version>`, and pushes only the tag.
5. On a fresh origin/main it merges the tag keeping main's files, moves the release's entries from ## Unreleased to a
## <version> section below it, commits that titled `Merge release <version> into main`, and lands it through the branch
@@ -60,15 +63,19 @@ doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from
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 datetime
import os
import pathlib
import shlex
import sys
import time
from deploy_release.ci_script import ci_runner, CI_SECONDS
from deploy_release.cut import cut
from deploy_release.patch import cut_patch
from deploy_release.deploy import deploy
from failure import Failure
from deploy_release import trace
def main(argv: list[str]) -> int:
@@ -82,12 +89,28 @@ def main(argv: list[str]) -> int:
print("deploy-release: usage: deploy-release [--cut | --cut-patch <commits>] [<checkout>]", file=sys.stderr)
return 1
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
if not cutting and commits is None:
moved = deploy(checkout)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
return 1
print(moved)
return 0
clone, now = os.getcwd(), datetime.datetime.now
folder, name = trace.trace_folder(os.environ, pathlib.Path.home()), trace.run_name(now(), os.getpid())
begun = trace.started(folder, name, f"deploy-release {shlex.join([*argv[:2 if patching else 1], checkout])} in {clone}", now)
if isinstance(begun, Failure):
print(f"deploy-release: warning: {begun.reason}", file=sys.stderr)
file = None if isinstance(begun, Failure) else begun
say = trace.saying(file, now, sys.stderr)
if commits is not None:
moved = cut_patch(os.getcwd(), checkout, commits, time.sleep)
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say))
else:
moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout)
moved = cut(clone, checkout, time.sleep, say)
if isinstance(moved, Failure):
print(f"deploy-release: {moved.reason}", file=sys.stderr)
say(moved.reason)
return 1
print(moved)
# The ending is on stdout already, so only the trace takes it.
trace.kept(file, moved.splitlines()[-1], now, sys.stderr)
return 0
+67 -34
View File
@@ -5,15 +5,15 @@ A rerun takes the tag an earlier run pushed, once it checks the tag lists the sa
import dataclasses
import pathlib
import re
import subprocess
import typing
from git_cli.git_repo import default_ref, git
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, said, same_origin, scratch_worktree
from deploy_release.cut import delete_release_branch, drop_unpushed_cut_tags, land, push_branch, ready_release, rewritten, same_origin, scratch_worktree
from deploy_release.deploy import deploy
from failure import Failure
from forge.commands import forge_of
from plan.release import newest_tag, tagged, UNRELEASED_TITLE, version
from deploy_release.trace import Say
from text_files.markdown_text import section
# The files a patch leaves as the tag holds them: the changelog, whose section the cut writes itself; the plan; and the records each chunk appends to, which seldom apply on an older tag.
@@ -36,29 +36,42 @@ class Patch:
entries: list[str]
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None]) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit."""
@dataclasses.dataclass(frozen=True)
class CiRan:
code: int
# stdout and stderr, as ci.sh interleaved them.
output: str
class Ci(typing.Protocol):
"""Runs the ci.sh that worktree holds, as ci_script.ci_runner's does: a Failure where it could not start or was stopped."""
def __call__(self, worktree: pathlib.Path) -> CiRan | Failure: ...
def cut_patch(clone: str, checkout: str, commits: str, sleep: typing.Callable[[float], None], say: Say, ci: Ci) -> str | Failure:
"""What the patch cut did, as the tool prints it; a Failure with git's, the forge's, ci.sh's or the tool's reason where a step stopped. commits is a range as git log reads it, or one commit. say takes each step as it finishes, and ci runs the patch's ci.sh."""
patch = planned(clone, checkout, commits)
if isinstance(patch, Failure):
return patch
for commit in patch.commits:
subject = git("log", "-1", "--format=%h %s", commit, cwd=clone)
said(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
say(f"ships {'' if isinstance(subject, Failure) else subject.strip()}")
tag, branch = f"v{patch.named}", f"release-{patch.named}"
pushed = git("ls-remote", "--tags", "--refs", "origin", f"refs/tags/{tag}", cwd=clone)
if isinstance(pushed, Failure):
return pushed
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch)
made = tagged_entries(clone, patch) if pushed.strip() else tag_patch(clone, patch, say, ci)
if isinstance(made, Failure):
return made
build = lambda replacing: push_merge_back(clone, patch, replacing)
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep), Failure):
if isinstance(landed := land(clone, patch.ref, branch, f"Merge release {patch.named} into main", MERGE_BACK_BODY, build, sleep, say), Failure):
return landed
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
return fetched
if isinstance(git("merge-base", "--is-ancestor", tag, patch.ref, cwd=clone), Failure):
return Failure(f"the merge-back merged, but {patch.ref} doesn't hold {tag}, so the next cut can't read it as cut")
delete_release_branch(clone, branch)
delete_release_branch(clone, branch, say)
moved = deploy(checkout)
if isinstance(moved, Failure):
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
@@ -88,12 +101,12 @@ def planned(clone: str, checkout: str, commits: str) -> Patch | Failure:
if base is None or cut is None:
return Failure(f"{ref}'s newest tag, {base}, names no release x.y.z to cut a patch of" if base else f"{ref} holds no v* tag to cut a patch of")
named = version((cut[0], cut[1], cut[2] + 1))
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut without one.
release = ready_release(clone, ref, review=False)
if isinstance(release, Failure):
return release
if version(release) != named:
return Failure(f"the next release in todo.md is {version(release)}, not {named}, the patch of {base}: file the fix under {named}")
ready = ready_release(clone, ref)
if isinstance(ready, Failure):
return ready
# A patch holds only fixes, and the release review reads the whole project, so a patch is cut whether or not ready.reviewed.
if version(ready.release) != named:
return Failure(f"the next release in todo.md is {version(ready.release)}, not {named}, the patch of {base}: file the fix under {named}")
picked = patch_commits(clone, ref, base, commits)
if isinstance(picked, Failure):
return picked
@@ -118,7 +131,7 @@ def patch_commits(clone: str, ref: str, base: str, commits: str) -> list[str] |
def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | Failure:
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none."""
"""The entries under ref's ## Unreleased in CHANGELOG.md that commits added, in the order ref lists them; a Failure where they added none, or where ref's CHANGELOG.md has no such section, which the merge-back moves the entries out of."""
added: set[str] = set()
for commit in commits:
diff = git("diff", f"{commit}^", commit, "--", "CHANGELOG.md", cwd=clone)
@@ -128,7 +141,11 @@ def changelog_entries(clone: str, ref: str, commits: list[str]) -> list[str] | F
changelog = git("show", f"{ref}:CHANGELOG.md", cwd=clone)
if isinstance(changelog, Failure):
return changelog
entries = [line for line in section(changelog, UNRELEASED_TITLE) or [] if line in added]
unreleased = section(changelog, UNRELEASED_TITLE)
# The merge-back finds the heading with unreleased_start, after the tag is pushed, so that is asked here too.
if unreleased is None or unreleased_start(changelog.split("\n")) is None:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section, which the patch's entries come from: add it on {ref}")
entries = [line for line in unreleased if line in added]
return entries or Failure(f"the commits add no entry under ## Unreleased in CHANGELOG.md on {ref}: name the commit that finished the fix's item too")
@@ -143,7 +160,7 @@ def tagged_entries(clone: str, patch: Patch) -> Failure | None:
return None
def tag_patch(clone: str, patch: Patch) -> Failure | None:
def tag_patch(clone: str, patch: Patch, say: Say, ci: Ci) -> Failure | None:
"""In a worktree at the base tag, apply patch's commits but for LEFT_AS_TAGGED, head CHANGELOG.md with its section, commit that titled `Cut release <version>`, test it with ci.sh, then tag it and push the tag."""
title, tag = f"Cut release {patch.named}", f"v{patch.named}"
with scratch_worktree(clone, patch.base) as worktree:
@@ -152,21 +169,22 @@ def tag_patch(clone: str, patch: Patch) -> Failure | None:
for commit in patch.commits:
if isinstance(applied := apply_commit(clone, worktree, commit, patch), Failure):
return applied
changelog = worktree / "CHANGELOG.md"
changelog.write_text(headed(changelog.read_text() if changelog.exists() else "# Changelog\n", patch.entries, patch.named))
head = lambda changelog: headed("# Changelog\n" if changelog is None else changelog, patch.entries, patch.named)
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"head CHANGELOG.md with ## {patch.named} in the patch's worktree, so nothing is tagged", head), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "--all", "--message", title, cwd=str(worktree)), Failure):
return committed
said(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref), Failure):
say(f"applied the commits on {patch.base}; testing them with ci.sh")
if isinstance(tested := run_ci(worktree, patch.ref, ci), Failure):
return tested
said("ci.sh passed")
say("ci.sh passed")
if isinstance(made := git("tag", "--annotate", "--message", title, tag, "HEAD", cwd=str(worktree)), Failure):
return made
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
git("tag", "--delete", tag, cwd=clone)
return pushed
said(f"pushed the tag {tag}")
say(f"pushed the tag {tag}")
return None
@@ -187,7 +205,8 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
if not diff:
return None
patch_file = worktree.parent / "commit.patch"
patch_file.write_text(diff)
if isinstance(written := rewritten(patch_file, f"write {commit[:12]}'s changes to a file to apply, so nothing is tagged", lambda _: diff), Failure):
return written
if isinstance(applied := git("apply", "--3way", "--index", str(patch_file), cwd=str(worktree)), Failure):
subject = git("log", "-1", "--format=%s", commit, cwd=clone)
return Failure(
@@ -199,14 +218,16 @@ def apply_commit(clone: str, worktree: pathlib.Path, commit: str, patch: Patch)
return None
def run_ci(worktree: pathlib.Path, ref: str) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head; a Failure with the end of its output where it fails."""
def run_ci(worktree: pathlib.Path, ref: str, ci: Ci) -> Failure | None:
"""None where the patch's ci.sh passes on its committed head, run by ci; a Failure with the end of its output where it fails, or with ci's reason where it could not run or was stopped."""
if not (worktree / "ci.sh").exists():
return Failure("the patch holds no ci.sh to test it with")
ran = subprocess.run(["sh", "ci.sh"], capture_output=True, cwd=worktree, text=True, errors="replace")
if ran.returncode == 0:
ran = ci(worktree)
if isinstance(ran, Failure):
return Failure(f"{ran.reason}, so nothing is tagged. Rerun once that is fixed.")
if ran.code == 0:
return None
tail = "\n".join((ran.stdout + ran.stderr).strip().splitlines()[-30:])
tail = "\n".join(ran.output.strip().splitlines()[-30:])
return Failure(f"ci.sh failed on the patch, so nothing is tagged. Fix it on {ref}, then rerun naming the fix's commits too. The end of its output:\n{tail}")
@@ -217,19 +238,31 @@ def push_merge_back(clone: str, patch: Patch, replacing: str | None) -> Failure
return worktree
if isinstance(merged := git("merge", "--quiet", "--no-ff", "--no-commit", "--strategy", "ours", f"v{patch.named}", cwd=str(worktree)), Failure):
return merged
changelog = worktree / "CHANGELOG.md"
changelog.write_text(moved_entries(changelog.read_text(), patch.entries, patch.named))
# The tag is pushed by now, so each stop here says that a rerun with the same commits takes it and builds only this merge-back again.
rerun = f"v{patch.named} is pushed, and a rerun with the same commits merges it back"
def move(changelog: str | None) -> str | Failure:
moved = moved_entries(changelog or "", patch.entries, patch.named)
return Failure(f"{moved.reason}, on {patch.ref}: add the heading there; {rerun}") if isinstance(moved, Failure) else moved
if isinstance(written := rewritten(worktree / "CHANGELOG.md", f"move the entries of {patch.named} out of ## Unreleased in the merge-back's worktree; {rerun}", move), Failure):
return written
if isinstance(committed := git("commit", "--quiet", "--all", "--message", f"Merge release {patch.named} into main", cwd=str(worktree)), Failure):
return committed
return push_branch(worktree, f"release-{patch.named}", replacing)
def moved_entries(changelog: str, entries: list[str], named: str) -> str:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section."""
def moved_entries(changelog: str, entries: list[str], named: str) -> str | Failure:
"""changelog with entries taken out of its ## Unreleased section and put in a ## named section right below that section; a Failure where it has no such heading."""
lines = changelog.split("\n")
start = next(index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line))
start = unreleased_start(lines)
if start is None:
return Failure(f"CHANGELOG.md has no ## Unreleased heading to move the entries of {named} from")
end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith("## ")), len(lines))
kept = [line for line in lines[start + 1:end] if line not in entries]
while kept and not kept[-1].strip():
kept.pop()
return "\n".join([*lines[:start + 1], *kept, "", f"## {named}", "", *entries, "", *lines[end:]])
def unreleased_start(lines: list[str]) -> int | None:
"""The index in lines of a changelog's ## Unreleased heading; None where it has none."""
return next((index for index, line in enumerate(lines) if re.fullmatch(f"## {UNRELEASED_TITLE}", line)), None)
+188 -2
View File
@@ -1,16 +1,19 @@
import datetime
import io
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from deploy_release import ci_script, cut, patch, trace
from failure import Failure
from test_env import isolated_env
from deploy_release import patch
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
@@ -244,7 +247,7 @@ class Cut(unittest.TestCase):
(fake / name).write_text(FAKE_FORGE)
(fake / name).chmod(0o755)
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"}
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}", "XDG_STATE_HOME": str(self.temp / "state")}
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
self.clone = self.temp / "claude-config"
@@ -470,6 +473,43 @@ class Cut(unittest.TestCase):
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
def traces(self) -> list[str]:
"""The text of each run's trace, oldest first."""
return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")]
def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self):
self.assert_cut(self.cut())
[kept] = self.traces()
lines = kept.splitlines()
self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}\S* deploy-release --cut {self.target} in {self.clone}$")
self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}\S* pushed the tag v0\.2\.0$")
self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1])
def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self):
self.assert_cut(self.cut())
self.assertEqual(self.cut().returncode, 1)
first, second = self.traces()
self.assertTrue(second.endswith(" release 0.3.0 still holds items in todo.md\n"), second)
self.assertNotIn("still holds items", first)
def test_reads_whether_the_next_releases_review_landed_beside_the_release(self):
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 2, 0), reviewed=True))
self.plan_patch()
self.assertEqual(cut.ready_release(str(self.clone), "origin/main"), cut.Ready((0, 1, 1), reviewed=False))
def test_refuses_before_any_change_where_mains_changelog_has_no_unreleased_heading(self):
ran = self.cut_patch(self.plan_patch({"CHANGELOG.md": "# Changelog\n\n- Second.\n- Fixed.\n\n## 0.1.0\n\n- First.\n"}))
self.assertEqual(ran.returncode, 1)
self.assertIn("CHANGELOG.md on origin/main has no ## Unreleased section", ran.stderr)
self.assertEqual(self.origin_git("tag", "-l", "v0.1.1"), "")
def test_says_where_ci_shs_output_goes_and_keeps_it_there(self):
ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"}))
self.assertEqual(ran.returncode, 0, ran.stderr)
[log] = (self.temp / "state" / "deploy-release").glob("*-ci.log")
self.assertEqual(log.read_text(), "the suite ran\n")
self.assertIn(f"ci.sh's output goes to {log}", ran.stderr)
def plan_patch(self, fix: dict[str, str] | None = None) -> str:
"""On top of setUp's main: a feature no patch may ship, item 3 filed under 0.1.1, then the commit that fixes tool.txt and finishes item 3, pushed. The revision range that names only the fix."""
self.commit({"feature.txt": "new\n"}, "Add a feature")
@@ -678,6 +718,149 @@ class Cut(unittest.TestCase):
def still_runs(pid: int) -> bool:
"""Whether the process pid runs: one that ended and that nobody has waited for yet doesn't."""
try:
return pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
except OSError:
return False
class PatchCi(unittest.TestCase):
"""The patch's ci.sh run, read in-process with the runner handed in, and the runner itself on a real ci.sh."""
def setUp(self):
self.worktree = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)])
self.log = self.worktree / "ci.log"
self.said: list[str] = []
def test_passes_where_ci_sh_exits_zero(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
seen: list[pathlib.Path] = []
self.assertIsNone(patch.run_ci(self.worktree, "origin/main", lambda worktree: seen.append(worktree) or patch.CiRan(0, "fine\n")))
self.assertEqual(seen, [self.worktree])
def test_a_failed_ci_sh_gives_the_last_30_lines_of_its_output(self):
(self.worktree / "ci.sh").write_text("exit 1\n")
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: patch.CiRan(1, "".join(f"line {number}\n" for number in range(1, 41))))
self.assertIsInstance(failed, Failure)
self.assertIn("ci.sh failed on the patch, so nothing is tagged. Fix it on origin/main", failed.reason)
self.assertTrue(failed.reason.endswith("\nline 11\n" + "\n".join(f"line {number}" for number in range(12, 41))), failed.reason)
self.assertNotIn("line 10\n", failed.reason)
def test_a_ci_sh_that_could_not_run_or_was_stopped_tags_nothing_and_gives_the_runners_reason(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
failed = patch.run_ci(self.worktree, "origin/main", lambda worktree: Failure("ci.sh still ran after 30 minutes and was stopped"))
self.assertEqual(failed, Failure("ci.sh still ran after 30 minutes and was stopped, so nothing is tagged. Rerun once that is fixed."))
def test_refuses_a_patch_without_ci_sh_before_running_anything(self):
self.assertEqual(patch.run_ci(self.worktree, "origin/main", lambda worktree: self.fail("ran")), Failure("the patch holds no ci.sh to test it with"))
def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self):
(self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n")
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree)
self.assertEqual(ran, patch.CiRan(3, "out\nerr\n"))
self.assertEqual(self.log.read_text(), "out\nerr\n")
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"])
def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self):
(self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n")
began = time.monotonic()
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, grace=0.2)(self.worktree)
self.assertLess(time.monotonic() - began, 20)
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
self.assertEqual(self.log.read_text(), "started\n")
child = int((self.worktree / "child.pid").read_text())
deadline = time.monotonic() + 5
while still_runs(child) and time.monotonic() < deadline:
time.sleep(0.05)
self.assertFalse(still_runs(child), "the process ci.sh started still runs")
def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self):
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree / "gone")
self.assertIsInstance(ran, Failure)
self.assertIn("ci.sh could not run: ", ran.reason)
self.assertIn(str(self.worktree / "gone"), ran.reason)
def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self):
(self.worktree / "ci.sh").write_text("exit 0\n")
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append)(self.worktree)
self.assertIsInstance(ran, Failure)
self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason)
class Trace(unittest.TestCase):
"""What a cut says, in-process, with the clock and stderr handed in."""
def setUp(self):
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
self.now = lambda: datetime.datetime(2026, 11, 27, 9, 30, 5)
def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self):
self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release"))
self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release"))
def test_names_a_run_by_its_start_and_its_process(self):
self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05-4711")
def test_starts_a_trace_with_the_command_then_appends_each_step_with_its_time_and_says_it(self):
file = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
self.assertEqual(file, self.temp / "state" / "deploy-release" / "run.log")
out = io.StringIO()
say = trace.saying(file, self.now, out)
say("pushed the tag v0.2.0")
say("merged pull request 3")
self.assertEqual(out.getvalue(), "deploy-release: pushed the tag v0.2.0\ndeploy-release: merged pull request 3\n")
self.assertEqual(file.read_text(), "2026-11-27T09:30:05 deploy-release --cut\n2026-11-27T09:30:05 pushed the tag v0.2.0\n2026-11-27T09:30:05 merged pull request 3\n")
def test_a_trace_that_cannot_be_started_is_a_failure_naming_the_file(self):
(self.temp / "state").write_text("a file where the folder goes\n")
made = trace.started(self.temp / "state" / "deploy-release", "run", "deploy-release --cut", self.now)
self.assertIsInstance(made, Failure)
self.assertIn(str(self.temp / "state" / "deploy-release" / "run.log"), made.reason)
def test_still_says_each_step_where_there_is_no_trace_or_it_cannot_be_written(self):
out = io.StringIO()
trace.saying(None, self.now, out)("pushed the tag v0.2.0")
trace.saying(self.temp / "gone" / "run.log", self.now, out)("merged pull request 3")
self.assertEqual(out.getvalue().splitlines()[:2], ["deploy-release: pushed the tag v0.2.0", "deploy-release: merged pull request 3"])
self.assertIn(f"warning: the trace {self.temp / 'gone' / 'run.log'} could not be written", out.getvalue().splitlines()[2])
class Rewritten(unittest.TestCase):
"""A cut's file edits, where the filesystem refuses one."""
def setUp(self):
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
def test_replaces_a_files_text_and_hands_none_for_a_file_that_is_not_there(self):
file = self.temp / "CHANGELOG.md"
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: f"{text!r} new\n"))
self.assertEqual(file.read_text(), "None new\n")
self.assertIsNone(cut.rewritten(file, "head CHANGELOG.md", lambda text: text.upper()))
self.assertEqual(file.read_text(), "NONE NEW\n")
def test_a_file_that_cannot_be_read_or_written_is_a_failure_naming_the_step_and_the_file(self):
folder = self.temp / "CHANGELOG.md"
folder.mkdir()
# A folder can't be read as a file, and a file in a folder that isn't there can't be written.
for file in (folder, self.temp / "gone" / "commit.patch"):
with self.subTest(file=file):
failed = cut.rewritten(file, "head CHANGELOG.md with ## 0.1.1, so nothing is tagged", lambda text: "new\n")
self.assertIsInstance(failed, Failure)
self.assertTrue(failed.reason.startswith("could not head CHANGELOG.md with ## 0.1.1, so nothing is tagged: "), failed.reason)
self.assertIn(str(file), failed.reason)
def test_gives_the_rewrites_own_failure_and_leaves_the_file(self):
file = self.temp / "CHANGELOG.md"
file.write_text("old\n")
self.assertEqual(cut.rewritten(file, "x", lambda text: Failure("no heading")), Failure("no heading"))
self.assertEqual(file.read_text(), "old\n")
class PatchChangelog(unittest.TestCase):
"""The changelog edits of a patch cut, read in-process, so a mutation tester reaches them."""
@@ -698,6 +881,9 @@ class PatchChangelog(unittest.TestCase):
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")
def test_a_changelog_without_an_unreleased_heading_is_a_failure_that_names_it(self):
self.assertEqual(patch.moved_entries("# Changelog\n\n## 0.1.0\n\n- First.\n", ["- Fixed."], "0.1.1"), Failure("CHANGELOG.md has no ## Unreleased heading to move the entries of 0.1.1 from"))
if __name__ == "__main__":
unittest.main()
+55
View File
@@ -0,0 +1,55 @@
"""What a cut says as each step finishes: on stderr, and in a file of the run's own, so the steps outlast the terminal."""
import datetime
import pathlib
import typing
from failure import Failure
# Says that one step of a cut finished, as `saying` makes it.
Say = typing.Callable[[str], None]
Clock = typing.Callable[[], datetime.datetime]
def trace_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
"""The folder each cut keeps its trace in, under the state folder as run-heavy finds it."""
state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state")
return pathlib.Path(state) / "deploy-release"
def run_name(began: datetime.datetime, pid: int) -> str:
"""The name of the files one run keeps, which sorts by when it began."""
return f"{began:%Y-%m-%dT%H-%M-%S}-{pid}"
def stamped(at: datetime.datetime, line: str) -> str:
return f"{at.isoformat(timespec='seconds')} {line}\n"
def started(folder: pathlib.Path, name: str, command: str, now: Clock) -> pathlib.Path | Failure:
"""A new trace, <folder>/<name>.log, whose first line is command; a Failure where it can't be written."""
file = folder / f"{name}.log"
try:
folder.mkdir(parents=True, exist_ok=True)
file.write_text(stamped(now(), command), encoding="utf-8")
except OSError as failure:
return Failure(f"the trace {file} could not be started: {failure}")
return file
def kept(trace: pathlib.Path | None, line: str, now: Clock, out: typing.TextIO) -> None:
"""Append line with its time to trace, where there is one. A trace that can't be written only warns on out, since the cut's own steps count."""
if trace is None:
return
try:
with trace.open("a", encoding="utf-8") as file:
file.write(stamped(now(), line))
except OSError as failure:
print(f"deploy-release: warning: the trace {trace} could not be written: {failure}", file=out)
def saying(trace: pathlib.Path | None, now: Clock, out: typing.TextIO) -> Say:
"""Says each step on out, so the human sees how far the cut got before the changelog fills the screen, and keeps it in trace."""
def say(step: str) -> None:
print(f"deploy-release: {step}", file=out)
kept(trace, step, now, out)
return say
+2 -1
View File
@@ -19,6 +19,7 @@ from do_epic.split import finished
from do_epic.repo_pick import label_of, LabelRepos, recorded, Repo
from text_files.markdown_text import listed
from text_files.piped_text import piped
from plan.release import REVIEW_TITLE
# Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it.
CLOSE = "--close-epic"
@@ -67,7 +68,7 @@ def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib
f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. "
f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"<summary>\" {findings.LABEL} <label> {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. "
f"The `<label>` is {listed([f'`{label_of(Repo(name), team)}` for {name}' for name in lacking], 'and')}. "
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `Release review of {epic}`. "
f"The detail asks for a release review of the whole repo, as the epic's issues left it: the one `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" describes. The epic's key stands in place of the release there, so the review's branch opens with an empty commit titled `{REVIEW_TITLE}{epic}`. "
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
f"The chunk is finished once each issue is filed: {DRIVER} works them, and starts this chunk again once the epic holds no open issue."
)
+3
View File
@@ -16,6 +16,7 @@ from do_epic.test_scheduler import issue
from chunk_driver.claims import LOCK
from do_epic.backend.fake import MemoryEpic
from loop_state.paths import paths_from
from plan.release import REVIEW_TITLE
from claude_code.session import session_named
from do_epic.test_do_epic import SETTINGS
@@ -64,6 +65,8 @@ class TheFinishingChunksTask(DoEpicTest):
self.assertIn("first, and api has none. ", finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True)], {}, LAUNCHER, "Swedish"))
self.assertIn('`/b/do-epic ABC-12 --file "<summary>" --label <label> --label do-epic-release-review`', task)
self.assertIn("`Release review of ABC-12`", task)
self.assertIn(f"`{REVIEW_TITLE}ABC-12`", task)
self.assertEqual(REVIEW_TITLE, "Release review of ")
self.assertIn("in Swedish", task)
self.assertNotIn("--close-epic", task)
+2
View File
@@ -12,6 +12,8 @@ DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits
TAG = re.compile(rf"v({VERSION})")
# The title of CHANGELOG.md's section for news not yet released: Unreleased, or a title that says unreleased, such as `0.6.0 (unreleased)`, as a project's own changelog may head it; and its ## heading.
UNRELEASED_TITLE = r"(?i:.*unreleased.*)"
# What opens the title of a release review's first commit, before the release it reviews, or the epic's key in do-epic's finishing chunk. release_standing counts a review by it.
REVIEW_TITLE = "Release review of "
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
+2 -2
View File
@@ -6,7 +6,7 @@ from failure import Failure
from plan.todo_table import Item, NoItemsTable
from text_files.markdown_text import listed
from plan_store.plans import Plan
from plan.release import Release, version
from plan.release import Release, REVIEW_TITLE, version
from project_config import templates
@@ -79,7 +79,7 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
if isinstance(pick, ReviewDue):
awaited = version(pick.release) if pick.release else "<release>"
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of {awaited}` has landed {'since the cut' if named is not None else 'yet'}. `chunk-preflight --help` says which commit counts. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `{REVIEW_TITLE}{awaited}` has landed {'since the cut' if named is not None else 'yet'}. `chunk-preflight --help` says which commit counts. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
if isinstance(pick, ReadyToCut):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
+2 -2
View File
@@ -3,7 +3,7 @@ import dataclasses
from release_plan.awaiting_merge import awaiting, marked
from git_cli.git_repo import commits_since, file_at, git, Git
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, REVIEW_TITLE, tagged, UNRELEASED_TITLE
from failure import Failure
from forge.commands import forge_of, Run
from plan.todo_table import Item, items, next_item, renames
@@ -144,7 +144,7 @@ def reviewed_releases(tag: str | None, ref: str, cwd: str, titles: templates.Tit
if isinstance(log, Failure):
return log
summaries = [titles.summary(line) for line in log.splitlines()]
reviews = [summary.removeprefix("Release review of ") for summary in summaries if summary.startswith("Release review of ")]
reviews = [summary.removeprefix(REVIEW_TITLE) for summary in summaries if summary.startswith(REVIEW_TITLE)]
floor = after if after is not None else tagged(tag)
return frozenset(named for review in reviews if (named := parsed(review)) is not None and (floor is None or named > floor))
@@ -121,7 +121,7 @@ class BenchOfTasksCase(unittest.TestCase):
def bench(self, **given: str):
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home)
return main.bench({**self.given, **given}, self.env, lambda home: "", self.home, "task-bench-0123456789ab", "1234:5678")
class FeatureBenchTest(BenchOfTasksCase):
+145 -66
View File
@@ -196,7 +196,7 @@ import time
import typing
import uuid
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, SHIPPED, Side, SIDES, Task, tests_in_copy
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, DATA_SOURCE, FEATURE, Kind, KINDS, on_disk, Planned, SHIPPED, Side, SIDES, Task, tests_in_copy
from task_bench.bugs.planted_mutant import bug_at_sides, Mutant
from claude_code.reply import Claude
from task_bench.bench_folder import clear_left, held
@@ -206,15 +206,15 @@ from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, Git, top
from task_bench.figures.gather import DIGEST, gather, run_claude
from task_bench.bugs.plant import drawn, killed_mutants, place_files, task_text
from claude_code.entries import entry_from, json_objects
from claude_code.entries import Entry, entry_from, json_objects
from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure
from task_bench.features.feature_tasks import feature_tasks, Features, read_features
from task_bench.figures.run_figures import figures, Result, table
from task_bench.figures.run_figures import Figures, figures, Result, table
from git_cli import git_repo
from review_rules.review_folder import made_review_folder, REPORTS
from larv_review.history_commands import read_places
from task_bench.features.shipped_features import read_shipped, shipped_tasks, ShippedFeatures
from task_bench.features.shipped_features import read_shipped, shipped_tasks
from task_bench.figures.record_figures import recorded_bench
from run_heavy.capped_docker import SHARE_VARIABLE
from task_bench.rust_test_modules import tells_apart
@@ -234,15 +234,43 @@ KEPT = "The digest, and each run's result and stream, until `task-bench gather`
ONLY_FOR = {"--seed": BUG, "--bugs": BUG, "--prefix": BUG, "--shipped": SHIPPED}
# What plans a bench's tasks, once the bench has opened its containers.
Planner = typing.Callable[[Bench], Planned | Failure]
# What makes a kind's planner from each side's tree, once the trees stand.
Planning = typing.Callable[[dict[Side, str]], Planner | Failure]
# What reads a kind's tasks once the bench knows its checkout and its sides' commits, with git to read them by.
Source = typing.Callable[[str, dict[Side, str], Git], Planning | Failure]
class Fixes(typing.NamedTuple):
"""The runs that finished, in the order they ran, and the failure that stopped the bench before the rest, if one did."""
results: list[Result]
stopped: Failure | None
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude) -> int:
class Call(typing.NamedTuple):
"""What a bench was called with: its options, the environment its tools run in, what reads what `larv-review places` prints,
and the home folder."""
given: dict[str, str]
env: typing.Mapping[str, str]
read: typing.Callable[[pathlib.Path], str | Failure]
home: pathlib.Path
def new_name() -> str:
"""A name no other bench's containers have."""
return f"task-bench-{uuid.uuid4().hex[:12]}"
def host_user() -> str:
"""The user and group this process runs as, as docker's --user takes them."""
return f"{os.getuid()}:{os.getgid()}"
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int:
"""Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers."""
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers. `name` names a bench's containers,
and `user` is the user they run as."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
@@ -254,7 +282,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
if isinstance(given, Failure):
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
report = bench(given, env, read, home)
report = bench(given, env, read, home, name(), user())
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
@@ -263,6 +291,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[
def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""The options argv gives, with each default filled in; a Failure where argv cannot be read, or asks what no bench does."""
given = parsed(argv)
return given if isinstance(given, Failure) else checked(given, env)
def parsed(argv: list[str]) -> dict[str, str] | Failure:
"""Each option argv names, with its value, given as `--name value` or `--name=value`."""
given: dict[str, str] = {}
rest = list(argv)
while rest:
@@ -279,6 +314,11 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] |
if not equals and not rest:
return Failure(f"{name} needs a value")
given[name] = value if equals else rest.pop(0)
return given
def checked(given: dict[str, str], env: typing.Mapping[str, str]) -> dict[str, str] | Failure:
"""given with each default filled in, where it holds what a bench of its kind needs and env holds the token."""
for name in ("--image", "--test"):
if not given.get(name):
return Failure(f"{name} is missing")
@@ -288,14 +328,17 @@ def options(argv: list[str], env: typing.Mapping[str, str]) -> dict[str, str] |
for name, only in ONLY_FOR.items():
if only is not kind and name in given:
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {given[TASKS]}")
return counts_failure(given, kind) or (given if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
def counts_failure(given: dict[str, str], kind: Kind) -> Failure | None:
"""Fills in the default of each count a bench of kind takes; a Failure where one given is no whole number from 1."""
for name, default in COUNTS.items():
if ONLY_FOR.get(name, kind) is not kind:
continue
if not given.setdefault(name, default).isdecimal() or int(given[name]) < 1:
return Failure(f"{name} takes a whole number from 1, not {given[name]}")
if not env.get(TOKEN):
return Failure(f"{TOKEN} holds no token")
return given
return None
def progress(line: str) -> None:
@@ -303,16 +346,15 @@ def progress(line: str) -> None:
print(line, file=sys.stderr)
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. It tells
its progress on stderr."""
# Only bugs are planted at the seats' places; features and data sources come from the project's folder, and shipped features from its history. Each kind reads what it makes its tasks from before anything is copied or built,
# so a fault there stops the bench at once.
def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure:
"""The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. Its
containers are named name and run as user. It tells its progress on stderr."""
# The one place that resolves the bench's kind from its options: SOURCES holds what reads each kind's tasks.
kind = KINDS[given[TASKS]]
# Shipped features are read from the base's history, once the base is known.
tasks_from: str | Features | ShippedFeatures | Failure | None = None if kind is SHIPPED else read(home) if kind is BUG else read_features(home, kind)
if isinstance(tasks_from, Failure):
return tasks_from
# Each kind reads what it makes its tasks from before anything is copied or built, so a fault there stops the bench at once.
source = SOURCES[kind](Call(given, env, read, home), kind)
if isinstance(source, Failure):
return source
git = functools.partial(git_repo.git, env=env)
checkout = top(git)
if isinstance(checkout, Failure):
@@ -320,10 +362,9 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
sides = commits(given, checkout, git)
if isinstance(sides, Failure):
return sides
if tasks_from is None:
tasks_from = read_shipped(home, checkout, sides["base"], git)
if isinstance(tasks_from, Failure):
return tasks_from
planning = source(checkout, sides, git)
if isinstance(planning, Failure):
return planning
progress(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.")
review = made_review_folder(checkout, home)
if isinstance(review, Failure):
@@ -332,15 +373,14 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal
if isinstance(folder, Failure):
return folder
clear_left(home / REPORTS)
run = functools.partial(bench_in, folder, given, env, tasks_from, checkout, sides, git)
containers = Containers(docker_cli(env), name, given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), user)
run = functools.partial(bench_in, folder, given["--image"], containers, Asked(kind, int(given["--runs"])), planning, checkout, sides, git)
return recorded_bench(run, folder, git, home, time.time) if RECORD in given else run()
def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[str, str], tasks_from: str | Features | ShippedFeatures, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, which empties folder and keeps its runs there. Where tasks_from is what
`larv-review places` prints, the bench plants bugs at the places it names. Where tasks_from holds features, data sources or
shipped features, the bench has Haiku build, add or rebuild them."""
containers = Containers(docker_cli(env), f"task-bench-{uuid.uuid4().hex[:12]}", given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), f"{os.getuid()}:{os.getgid()}")
def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: Asked, planning: Planning, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure:
"""The report of a bench of the commits sides names, in containers of image, which empties folder and keeps its runs there.
planning makes what plans the tasks of the kind asked."""
shutil.rmtree(folder, ignore_errors=True)
trees: dict[Side, str] = {}
for side, commit in sides.items():
@@ -348,23 +388,47 @@ def bench_in(folder: pathlib.Path, given: dict[str, str], env: typing.Mapping[st
if isinstance(tree, Failure):
return tree
trees[side] = tree
planned: typing.Callable[[Bench], Planned | Failure] | Failure
if isinstance(tasks_from, Features):
asked, planned = Asked(KINDS[given[TASKS]], int(given["--runs"])), features_planner(tasks_from, checkout, trees)
elif isinstance(tasks_from, ShippedFeatures):
asked, planned = Asked(SHIPPED, int(given["--runs"])), functools.partial(shipped_tasks, shipped=tasks_from, count=int(given["--shipped"]))
else:
asked, planned = Asked(BUG, int(given["--runs"])), bugs_planner(given, env, tasks_from, trees["base"])
planned = planning(trees)
if isinstance(planned, Failure):
return planned
try:
found = opened(containers, given["--image"]) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
found = opened(containers, image) or benched(Bench(checkout, sides, trees, asked, containers, folder, git, progress), planned)
finally:
closed(containers)
return found if isinstance(found, Failure) else [*found, f"{KEPT}{folder}"]
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> typing.Callable[[Bench], Planned | Failure]:
def bugs_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the seats' places, where alone bugs are planted."""
places = call.read(call.home)
if isinstance(places, Failure):
return places
return lambda checkout, sides, git: functools.partial(bugs_planner, call.given, call.env, places)
def features_source(call: Call, kind: Kind) -> Source | Failure:
"""Reads the features, or the data sources where kind is DATA_SOURCE, from the project's folder."""
features = read_features(call.home, kind)
if isinstance(features, Failure):
return features
return lambda checkout, sides, git: functools.partial(features_planner, features, checkout)
def shipped_source(call: Call, kind: Kind) -> Source:
"""Shipped features are read from the base's history, so only once the base is known."""
def source(checkout: str, sides: dict[Side, str], git: Git) -> Planning | Failure:
shipped = read_shipped(call.home, checkout, sides["base"], git)
if isinstance(shipped, Failure):
return shipped
return lambda trees: functools.partial(shipped_tasks, shipped=shipped, count=int(call.given["--shipped"]))
return source
# What reads each kind's tasks. A kind without an entry stops the bench before it reads anything.
SOURCES: dict[Kind, typing.Callable[[Call, Kind], Source | Failure]] = {BUG: bugs_source, FEATURE: features_source, DATA_SOURCE: features_source, SHIPPED: shipped_source}
def features_planner(features: Features, checkout: str, trees: dict[Side, str]) -> Planner:
"""What plans a bench of features in trees, each side's. It takes the features' folder, with its acceptance tests and
reference patches, out of trees first, so Haiku's copy leaves it out."""
if features.folder.is_relative_to(checkout):
@@ -374,10 +438,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
return functools.partial(feature_tasks, found=features.found, folder=features.folder)
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs. The bugs' files are those of the tree at base that hold a place in places and are in a language
of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until --bugs of
them have."""
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, trees: dict[Side, str]) -> Planner | Failure:
"""What plans a bench of bugs. The bugs' files are those of the base's tree in trees that hold a place in places and are in a
language of plant's LANGUAGES. Of the mutants the tests kill in those files, the ones --seed draws first become bugs, until
--bugs of them have."""
base = trees["base"]
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.")
@@ -417,7 +482,7 @@ def archived(commit: str, into: pathlib.Path, checkout: str, git: Git) -> str |
return removed if isinstance(removed, Failure) else str(into)
def benched(bench: Bench, planned: typing.Callable[[Bench], Planned | Failure]) -> list[str] | Failure:
def benched(bench: Bench, planned: Planner) -> list[str] | Failure:
"""Makes the tasks that planned plans, runs each, writes the results into the bench's folder and returns the report."""
if failure := baseline_failure(bench):
return failure
@@ -557,34 +622,48 @@ def fixed(task: Task, side: Side, number: int, containers: Containers, folder: p
stream = stream_of(Result(task.number, side, number, False, None), folder, kind.key)
copy, check = folder / "copy", folder / "check"
try:
try:
stream.parent.mkdir(exist_ok=True)
shutil.copytree(task.trees[side], copy, symlinks=True)
except OSError as failure:
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
if isinstance(attempted, Failure):
return attempted
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
entries = [entry_from(event) for event in events]
found = figures(events, task.file and os.path.join(WORK, task.file))
if isinstance(found, Failure):
return found
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return Result(task.number, side, number, isinstance(ran, Ran) and ran.code == 0, found, tuple(entries))
worked = attempt(task, side, containers, copy, stream, kind)
if isinstance(worked, Failure):
return worked
passed = verdict(task, side, containers, copy, check, kind)
if isinstance(passed, Failure):
return passed
return Result(task.number, side, number, passed, *worked)
finally:
shutil.rmtree(copy, ignore_errors=True)
shutil.rmtree(check, ignore_errors=True)
def attempt(task: Task, side: Side, containers: Containers, copy: pathlib.Path, stream: pathlib.Path, kind: Kind) -> tuple[Figures | None, tuple[Entry, ...]] | Failure:
"""Haiku's work on task in copy, made a copy of the side's tree: the figures of its run, None where it didn't finish, and
the entries of its stream, which it writes to the file stream."""
try:
stream.parent.mkdir(exist_ok=True)
shutil.copytree(task.trees[side], copy, symlinks=True)
except OSError as failure:
return Failure(f"could not copy {kind.noun} {task.number}'s tree at the {side}: {failure}")
attempted = fix_attempted(containers, str(copy), kind.prompt.format(told=task.told[side]), stream)
if isinstance(attempted, Failure):
return attempted
raw = on_disk(f"read {stream}", stream.read_bytes)
if isinstance(raw, Failure):
return raw
events = json_objects(raw)
found = figures(events, task.file and os.path.join(WORK, task.file))
return found if isinstance(found, Failure) else (found, tuple(entry_from(event) for event in events))
def verdict(task: Task, side: Side, containers: Containers, copy: pathlib.Path, check: pathlib.Path, kind: Kind) -> bool | Failure:
"""Whether the tests pass over check, made the side's tree with what Haiku changed in copy. Tests that run out of time don't."""
checked = on_disk(f"make the tree that checks {kind.noun} {task.number}'s fix at the {side}", lambda: check_made(task.trees[side], str(copy), str(check), task.acceptance))
if isinstance(checked, Failure):
return checked
ran = ran_tests(containers, str(check))
if isinstance(ran, Failure) and not isinstance(ran, TimedOut):
return ran
return isinstance(ran, Ran) and ran.code == 0
def stream_of(result: Result, folder: pathlib.Path, key: str) -> pathlib.Path:
"""The file that holds the stream of the run result names, of a task whose kind has that key. Its name without the suffix is
the run's id in the digest."""
+20 -4
View File
@@ -90,6 +90,8 @@ CLAUDE = textwrap.dedent("""\
usage = {"input_tokens": 40, "cache_creation_input_tokens": 9000, "cache_read_input_tokens": 52000, "output_tokens": 800}
print(json.dumps({"type": "result", "subtype": "success", "is_error": False, "num_turns": 3, "duration_ms": 61500, "usage": usage, "result": "Fixed."}))
""")
# The name of a bench's containers and the user they run as, where a test fixes them.
NAME, USER = "task-bench-0123456789ab", "1234:5678"
PLACES = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\nJunior A, hardest first:\n\n- `calc.go:3` `Add`: long\n- `gone.go:1` `Gone`: removed since\n- `README.md:1` `Calc`: thin\n"
@@ -131,7 +133,7 @@ class BenchTest(unittest.TestCase):
def bench(self, **given: str):
with contextlib.redirect_stderr(io.StringIO()) as self.progress:
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home)
return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home, NAME, USER)
def calls(self) -> list[list[str]]:
return [json.loads(line) for line in self.log.read_text().splitlines()]
@@ -223,6 +225,20 @@ class BenchTest(unittest.TestCase):
self.assertTrue((reports / "crashed/task-bench.lock").exists())
self.assertTrue((reports / "running/task-bench/trees/task-bench").exists())
def test_the_command_line_names_its_containers_afresh_and_runs_them_as_the_hosts_user(self):
self.assertRegex(main.new_name(), r"^task-bench-[0-9a-f]{12}$")
self.assertNotEqual(main.new_name(), main.new_name())
self.assertEqual(main.host_user(), f"{os.getuid()}:{os.getgid()}")
argv = [part for name, value in {**self.given, "--runs": "1"}.items() for part in (name, value)]
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(main.main(argv, self.env, lambda home: PLACES, name=lambda: "task-bench-other", user=lambda: "7:8"), 0)
calls = self.calls()
self.assertEqual(calls[1], ["network", "create", "--internal", "task-bench-other"])
self.assertIn(["--user", "7:8"], [call[at:at + 2] for call in calls if "claude" in call for at in range(len(call))])
def test_each_kind_of_task_has_what_reads_its_tasks(self):
self.assertEqual(set(main.SOURCES), set(main.KINDS.values()))
def test_the_command_line_runs_the_bench_on_the_seats_places_and_prints_its_report(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
homes = []
@@ -282,11 +298,11 @@ class BenchTest(unittest.TestCase):
fixes = [call for call in calls if "claude" in call]
self.assertEqual(len(fixes), 2)
name = fixes[0][fixes[0].index("--network") + 1]
self.assertRegex(name, r"^task-bench-[0-9a-f]{12}$")
self.assertEqual(name, NAME)
image = fixes[0].index(f"{name}:throwaway")
self.assertEqual(fixes[0][image + 1:], ["claude", "-p", "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence", "--model", "claude-haiku-5-5", "--effort", "low", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions", "A test of this project fails with the message below. Find the bug in the code and fix it. Change no test.\n\nAdd(1, 2) = -1, want 3"])
options = fixes[0][:image]
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", f"{os.getuid()}:{os.getgid()}"], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
for expected in (["--memory", "2048m"], ["--memory-swap", "2048m"], ["--user", USER], ["--env", "HOME=/tmp"], ["--env", "CLAUDE_CODE_OAUTH_TOKEN"], ["--env", f"HTTPS_PROXY=http://{name}-proxy:8080"], ["--workdir", "/work"]):
self.assertIn(expected, [options[at:at + 2] for at in range(len(options))])
self.assertNotIn("sk-secret-token", self.log.read_text())
self.assertEqual(calls[0][:1] + calls[0][-3:], ["build", "--tag", f"{name}:throwaway", "-"])
@@ -308,7 +324,7 @@ class BenchTest(unittest.TestCase):
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home, NAME, USER)
self.assertEqual(found, Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())