From 29b986ca42222335db07def9d166fbbabca10241 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:43:54 +0100 Subject: [PATCH 1/7] Have deploy-release --cut cut the next release through a pull request, then tag and deploy it --- AGENTS.md | 1 + CHANGELOG.md | 1 + README.md | 11 +- bin/deploy_release/cut.py | 150 +++++++++++++++ bin/deploy_release/deploy.py | 64 +++++++ bin/deploy_release/forge.py | 74 ++++++++ bin/deploy_release/main.py | 101 +++------- bin/deploy_release/test_deploy_release.py | 221 ++++++++++++++++++++++ docs/decisions.md | 4 + todo.md | 15 -- 10 files changed, 554 insertions(+), 88 deletions(-) create mode 100644 bin/deploy_release/cut.py create mode 100644 bin/deploy_release/deploy.py create mode 100644 bin/deploy_release/forge.py diff --git a/AGENTS.md b/AGENTS.md index 7d40a0c1..9290909f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,7 @@ Decisions live in `docs/decisions.md`: - bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers - chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone - comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release +- 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: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's - larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything - loop-claude: a `claude` that cannot start is a failed worker run, retried diff --git a/CHANGELOG.md b/CHANGELOG.md index e4c76c25..91b956dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request it opens, waits for and merges fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. `main` on the remote now takes no push, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0. - The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none. - In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. - `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file. diff --git a/README.md b/README.md index 801c45fd..99797e81 100644 --- a/README.md +++ b/README.md @@ -81,14 +81,20 @@ It refuses while a file `~/.claude` tracks has an uncommitted change, such as a ## Release -In `~/code/claude-config`, rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit `v`, and push both. Then run `bin/deploy-release` there, which moves this machine's `~/.claude` to the release: the cut isn't done until it has. Each other machine takes the release with Update. +Once the next release holds no item in `todo.md` and its release review has landed, cut it from `~/code/claude-config`: + +```sh +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. ## Tools Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`. - `chunk-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. -- `deploy-release []` moves `~/.claude`, or the checkout named, to the newest release, as Update says. +- `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. - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. @@ -122,6 +128,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. The non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. +- `deploy_release` imports `chunk_preflight`'s forge commands, which list a branch's open pull request with `gh` or `tea`, and `release_standing.py`, which says whether the next release is ready to cut. - `judge_replay` imports `loop_claude`'s judge. - `larv_review` imports `rank_todo.py`'s ranking. - `loop_claude` runs `chunk-preflight` as a process of its own. diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py new file mode 100644 index 00000000..e17745ca --- /dev/null +++ b/bin/deploy_release/cut.py @@ -0,0 +1,150 @@ +"""`deploy-release --cut`: cut the next release once it is ready, through a pull request, then tag it and 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 tempfile + +from chunk_preflight.choices import forge_of +from deploy_release import forge +from deploy_release.deploy import deploy +from failure import Failure +from git_repo import default_ref, git +from release import newest_tag, Release, version +from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned +from todo_table import items + + +def cut(clone: str, checkout: str) -> 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(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure): + return fetched + ref = default_ref(cwd=clone) + if isinstance(ref, Failure): + return ref + release = ready_release(clone, ref) + if isinstance(release, Failure): + return release + named = version(release) + title, tag = f"Cut release {named}", f"v{named}" + merged = commit_titled(title, ref, clone) + if merged is None: + landed = land(clone, ref, named, title) + if isinstance(landed, Failure): + return landed + if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure): + return fetched + merged = commit_titled(title, ref, clone) + if merged is None: + return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}") + if isinstance(merged, Failure): + return merged + tagged = tag_commit(tag, title, merged, clone) + if isinstance(tagged, Failure): + return tagged + if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure): + return pushed + moved = deploy(checkout) + if isinstance(moved, Failure): + return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}") + return f"Cut {tag}.\n\n{moved}" + + +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.""" + plan = default_plan(clone, ref) + found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo + if isinstance(found, Failure): + return Failure(f"todo.md on {ref} cannot be read: {found.reason}") + match chunk_item(found, plan.cut): + case ReadyToCut(release=release) if release is not None: + return release + 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): + return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed") + case Unplanned(): + return Failure("no change is unreleased since the last release cut") + case Cut(release=release): + return Failure(f"todo.md files items under {version(release)}, which is cut already") + case _: + return Failure("cannot tell which release is next") + + +def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: + """The commit on ref since the newest tag whose title is title; None where there is none.""" + tag = newest_tag(clone, merged_into=ref) + if isinstance(tag, Failure): + return tag + log = git("log", "--format=%H %s", f"{tag}..{ref}" if tag else ref, cwd=clone) + if isinstance(log, Failure): + return log + 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) -> 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.""" + url = git("config", "--get", "remote.origin.url", cwd=clone) + if isinstance(url, Failure): + return url + on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/") + number = forge.open_pull(on, branch, run) + if isinstance(number, Failure): + return number + head = branch_head(branch, clone) + if isinstance(head, Failure): + return head + if number is None: + if head is None: + if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure): + return pushed + if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure): + return created + number = forge.open_pull(on, branch, run) + if number is None or isinstance(number, Failure): + return number or Failure(f"opened a pull request for {branch}, but the forge lists none") + head = branch_head(branch, clone) + if head is None or isinstance(head, Failure): + return head or Failure(f"origin holds no branch {branch}") + if isinstance(passed := forge.checks_passed(on, number, head, run), Failure): + return passed + return forge.merge(on, number, run) + + +def branch_head(branch: str, clone: str) -> str | None | Failure: + """The commit origin's branch points at; None where origin has no such branch.""" + listed = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=clone) + return listed if isinstance(listed, Failure) else next(iter(listed.split()), None) + + +def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str) -> 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.""" + 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 + changelog = worktree / "CHANGELOG.md" + renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE) + if not count: + return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename") + changelog.write_text(renamed) + if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure): + return committed + pushed = git("push", "--quiet", "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 tag_commit(tag: str, title: str, commit: str, clone: str) -> Failure | None: + """Tag commit as tag, annotated with title, unless an earlier run did; a Failure where tag already names another commit.""" + existing = git("rev-parse", "--verify", "--quiet", f"refs/tags/{tag}^{{commit}}", cwd=clone) + if not isinstance(existing, Failure): + return None if existing.strip() == commit else Failure(f"{tag} already tags {existing.strip()[:12]}, not the merged commit {commit[:12]}") + made = git("tag", "--annotate", "--message", title, tag, commit, cwd=clone) + return made if isinstance(made, Failure) else None diff --git a/bin/deploy_release/deploy.py b/bin/deploy_release/deploy.py new file mode 100644 index 00000000..308c3682 --- /dev/null +++ b/bin/deploy_release/deploy.py @@ -0,0 +1,64 @@ +"""Move a checkout to this repo's newest release, as a bare `deploy-release` does.""" +from failure import Failure +from git_repo import git +from release import newest_tag, parsed, tagged +from markdown_text import sections + + +def deploy(checkout: str) -> str | Failure: + """What the move of checkout to the newest release did, as the tool prints it; a Failure where it refused or git failed.""" + fetched = git("fetch", "--quiet", "--tags", "origin", cwd=checkout) + if isinstance(fetched, Failure): + return fetched + tag = newest_tag(checkout) + if isinstance(tag, Failure): + return tag + if tag is None: + return Failure("origin has no v* tag to move to") + # Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged. + if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure): + return refreshed + changed = git("diff", "--name-only", "HEAD", cwd=checkout) + if isinstance(changed, Failure): + return changed + unreleased = git("diff", "--name-only", tag, "--", *changed.split(), cwd=checkout) if changed.split() else "" + if isinstance(unreleased, Failure): + return unreleased + if unreleased.split(): + return Failure(f"{checkout} has uncommitted changes that {tag} doesn't hold, to {', '.join(unreleased.split())}: merge them through the development clone and cut a release first") + old = git("describe", "--tags", "--abbrev=0", "--match", "v*", "HEAD", cwd=checkout) + old_tag = None if isinstance(old, Failure) else old.strip() + at_tag = git("describe", "--tags", "--exact-match", "--match", "v*", "HEAD", cwd=checkout) + if not isinstance(at_tag, Failure) and at_tag.strip() == tag: + return f"Already on {tag}, the newest release." + if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure): + return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first") + settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure) + # The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy. + if changed.split(): + restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout) + if isinstance(restored, Failure): + return restored + moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout) + if isinstance(moved, Failure): + return moved + changelog = git("show", f"{tag}:CHANGELOG.md", cwd=checkout) + lines = [f"Moved from {old_tag or 'an untagged commit'} to {tag}."] + if settings_changed: + lines.append("settings.json changed: pick the model again with /model.") + if not isinstance(changelog, Failure): + lines += newer_sections(changelog, old_tag) + return "\n\n".join(lines) + + +def newer_sections(changelog: str, old_tag: str | None) -> list[str]: + """Each `## ` section of changelog newer than old_tag, newest first, as it reads.""" + since = tagged(old_tag) + found = [] + for heading, bodies in sections(changelog).items(): + named = parsed(heading) + if named is None: + continue + if since is None or named > since: + found.append(f"## {heading}\n\n" + "\n".join(bodies)) + return found diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py new file mode 100644 index 00000000..5433dfd5 --- /dev/null +++ b/bin/deploy_release/forge.py @@ -0,0 +1,74 @@ +"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart.""" +import json +import subprocess +import time +import typing + +from chunk_preflight.choices import Forge, pulls_command +from chunk_preflight.facts import open_pulls +from failure import Failure + +# How long tea waits between two reads of the pull request's checks. +POLL_SECONDS = 10 + +# Runs a command in the clone: what it printed, or a Failure with its reason. +Run = typing.Callable[[list[str]], str | Failure] + + +def runner(cwd: str) -> Run: + def run(command: list[str]) -> str | Failure: + try: + done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL) + except OSError as failure: + return Failure(f"{command[0]} could not start: {failure}") + if done.returncode: + return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}") + return done.stdout + return run + + +def open_pull(forge: Forge, branch: str, run: Run) -> str | None | Failure: + """The number of branch's open pull request; None where it has none.""" + listed = run(pulls_command(forge, branch)) + if isinstance(listed, Failure): + return listed + found = open_pulls(listed, forge, branch) + return found[0].split()[0].removeprefix("#") if found else None + + +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."] + command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"] + created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body]) + return created if isinstance(created, Failure) else None + + +def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: + """None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails.""" + if forge == "gh": + watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"]) + if isinstance(watched, Failure) and "no checks reported" not in watched.reason: + return watched + return None + while True: + read = run(["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{head}/status"]) + if isinstance(read, Failure): + return read + # Gitea reads a commit with no status as pending, with total_count 0. + try: + status = json.loads(read) + count, state = status["total_count"], status["state"] + except (ValueError, KeyError, TypeError): + return Failure(f"tea api printed no commit status for {head}: {read.strip()[:200]}") + if count == 0 or state == "success": + return None + if state != "pending": + return Failure(f"a check on pull request {number} ended in {state}") + sleep(POLL_SECONDS) + + +def merge(forge: Forge, number: str, run: Run) -> Failure | None: + # GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title. + command = ["gh", "pr", "merge", number, "--rebase"] if forge == "gh" else ["tea", "pulls", "merge", "--style", "fast-forward-only", number] + merged = run(command) + return merged if isinstance(merged, Failure) else None diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 939fc441..01f98a38 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. +"""Move the checkout Claude Code reads its configuration from to this repo's newest release, and with --cut cut that release first. -usage: deploy-release [] +usage: deploy-release [--cut] [] 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, @@ -12,89 +12,48 @@ clean filter keeps the model out of every commit. It refuses, exit 1, and leaves the checkout as it was where a file the checkout tracks has an uncommitted change the newest tag doesn't hold: such as a hook Claude Code wrote into settings.json. Merge the change through the development clone and cut a release first. A model picked with /model -is no such change. It -also refuses where the newest tag doesn't hold the checkout's commit, since the move would drop -work no release holds. Untracked files, such as Claude Code's sessions and memory, stay as they are. +is no such change. It also refuses where the newest tag doesn't hold the checkout's commit, since +the move would drop work no release holds. Untracked files, such as Claude Code's sessions and +memory, stay as they are. + +--cut runs in the development clone. It cuts the next release, as chunk-preflight works it out, and +refuses, changing nothing, 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. +1. It commits CHANGELOG.md with ## Unreleased renamed to the version, as `Cut release `, on + a fresh origin/main, and pushes it as the branch release-. The clone's own checkout + stays as it is. +2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for + its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so + there it rebase-merges the branch, which is already on top of main. +3. It tags the merged commit v, annotated `Cut release `, pushes only the tag, + then moves to it as above. +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, a cut commit +already merged and a tag already on it. Once the tag is pushed, the release is cut: where only the +move stopped, fix what it names and run a bare deploy-release. """ +import os import pathlib import sys +from deploy_release.cut import cut +from deploy_release.deploy import deploy from failure import Failure -from git_repo import git -from release import newest_tag, parsed, tagged -from markdown_text import sections def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - if len(argv) > 1: - print("deploy-release: usage: deploy-release []", file=sys.stderr) + 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) return 1 - checkout = argv[0] if argv else str(pathlib.Path.home() / ".claude") - moved = deploy(checkout) + checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude") + moved = cut(os.getcwd(), checkout) if cutting else deploy(checkout) if isinstance(moved, Failure): print(f"deploy-release: {moved.reason}", file=sys.stderr) return 1 print(moved) return 0 - - -def deploy(checkout: str) -> str | Failure: - """What the move of checkout to the newest release did, as the tool prints it; a Failure where it refused or git failed.""" - fetched = git("fetch", "--quiet", "--tags", "origin", cwd=checkout) - if isinstance(fetched, Failure): - return fetched - tag = newest_tag(checkout) - if isinstance(tag, Failure): - return tag - if tag is None: - return Failure("origin has no v* tag to move to") - # Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged. - if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure): - return refreshed - changed = git("diff", "--name-only", "HEAD", cwd=checkout) - if isinstance(changed, Failure): - return changed - unreleased = git("diff", "--name-only", tag, "--", *changed.split(), cwd=checkout) if changed.split() else "" - if isinstance(unreleased, Failure): - return unreleased - if unreleased.split(): - return Failure(f"{checkout} has uncommitted changes that {tag} doesn't hold, to {', '.join(unreleased.split())}: merge them through the development clone and cut a release first") - old = git("describe", "--tags", "--abbrev=0", "--match", "v*", "HEAD", cwd=checkout) - old_tag = None if isinstance(old, Failure) else old.strip() - at_tag = git("describe", "--tags", "--exact-match", "--match", "v*", "HEAD", cwd=checkout) - if not isinstance(at_tag, Failure) and at_tag.strip() == tag: - return f"Already on {tag}, the newest release." - if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure): - return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first") - settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure) - # The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy. - if changed.split(): - restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout) - if isinstance(restored, Failure): - return restored - moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout) - if isinstance(moved, Failure): - return moved - changelog = git("show", f"{tag}:CHANGELOG.md", cwd=checkout) - lines = [f"Moved from {old_tag or 'an untagged commit'} to {tag}."] - if settings_changed: - lines.append("settings.json changed: pick the model again with /model.") - if not isinstance(changelog, Failure): - lines += newer_sections(changelog, old_tag) - return "\n\n".join(lines) - - -def newer_sections(changelog: str, old_tag: str | None) -> list[str]: - """Each `## ` section of changelog newer than old_tag, newest first, as it reads.""" - since = tagged(old_tag) - found = [] - for heading, bodies in sections(changelog).items(): - named = parsed(heading) - if named is None: - continue - if since is None or named > since: - found.append(f"## {heading}\n\n" + "\n".join(bodies)) - return found diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index f82cf365..047bfddf 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -1,3 +1,5 @@ +import json +import os import pathlib import subprocess import sys @@ -6,6 +8,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from deploy_release.forge import checks_passed +from failure import Failure from test_env import isolated_env TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release" @@ -123,5 +127,222 @@ class DeployRelease(unittest.TestCase): self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout) +TODO = """# todo + +## Scoring + +`Score = 100 * V / (2**S + 8)` + +`Bar = 0.1` + +`Next ID = 3` + +## Items + +| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +""" +ROW = "| {id} | {release} | | | **Do thing {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n" +# A forge holding origin's pull requests in /forge.json, as tea or gh, whichever name it runs under, reads and changes them. Its merge moves origin's main only by fast-forward. +FAKE_FORGE = """#!PYTHON +import json, pathlib, subprocess, sys +forge, args = pathlib.Path(sys.argv[0]).name, sys.argv[1:] +state_file = pathlib.Path(__file__).resolve().parent.parent / "forge.json" +state = json.loads(state_file.read_text()) +state["calls"].append([forge, *args]) +def save(): + state_file.write_text(json.dumps(state)) +def git(*words): + return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True) +def pull(number): + return next(found for found in state["pulls"] if str(found["number"]) == number) +def merge(number): + head = git("rev-parse", "refs/heads/" + pull(number)["head"]).stdout.strip() + if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode: + save() + sys.exit("Not possible to fast-forward") + git("update-ref", "refs/heads/main", head) + pull(number)["state"] = "merged" +opened = [found for found in state["pulls"] if found["state"] == "open"] +if forge == "tea" and args == ["pulls", "list", "--fields", "index,head,url", "--output", "tsv"]: + print("index\thead\turl") + for found in opened: + print(f"{found['number']}\t{found['head']}\thttps://forge/pulls/{found['number']}") +elif forge == "gh" and args[:3] == ["pr", "list", "--head"]: + for found in opened: + if found["head"] == args[3]: + print(f"{found['number']}\thttps://forge/pull/{found['number']}") +elif args[:2] in (["pulls", "create"], ["pr", "create"]): + state["pulls"].append({"number": len(state["pulls"]) + 1, "head": args[args.index("--head") + 1], "state": "open"}) +elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): + checks = state["checks"] + print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) +elif forge == "gh" and args[:2] == ["pr", "checks"]: + if state["checks"] == "none": + save() + sys.exit("no checks reported on the 'release' branch") + if state["checks"] == "failure": + save() + sys.exit("lint\tfail") +elif args[:3] == ["pulls", "merge", "--style"] and args[3] == "fast-forward-only": + merge(args[4]) +elif args[:2] == ["pr", "merge"] and args[3] == "--rebase": + merge(args[2]) +else: + save() + sys.exit("unexpected call") +save() +""".replace("PYTHON", sys.executable) + + +class Cut(unittest.TestCase): + """A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0.""" + + def setUp(self): + self.temp = pathlib.Path(os.path.realpath(tempfile.mkdtemp())) + self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)]) + self.origin = self.temp / "origin.git" + fake = self.temp / "fake-bin" + fake.mkdir() + for name in ("tea", "gh"): + (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.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" + 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.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") + self.git(self.clone, "push", "-q", "origin", "main", "--tags") + self.target = self.temp / "dot-claude" + self.git(self.temp, "clone", "-q", str(self.origin), str(self.target)) + self.git(self.target, "checkout", "-q", "--detach", "v0.1.0") + + def git(self, cwd: pathlib.Path, *args: str) -> str: + return subprocess.run(["git", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout + + def commit(self, files: dict[str, str], title: str) -> None: + for name, text in files.items(): + (self.clone / name).write_text(text) + self.git(self.clone, "add", "-A") + self.git(self.clone, "commit", "-q", "-m", title) + + def forge_state(self, state: dict | None = None) -> dict: + if state is not None: + (self.temp / "forge.json").write_text(json.dumps(state)) + return json.loads((self.temp / "forge.json").read_text()) + + def set_checks(self, checks: str) -> None: + self.forge_state({**self.forge_state(), "checks": checks}) + + def cut(self) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(TOOL), "--cut", str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True) + + def origin_git(self, *args: str) -> str: + return self.git(self.temp, "--git-dir", str(self.origin), *args) + + def assert_cut(self, ran: subprocess.CompletedProcess[str]) -> None: + """origin's main ends in the cut commit, tagged v0.2.0, and ~/.claude is on that tag.""" + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0") + changelog = self.origin_git("show", "main:CHANGELOG.md") + self.assertIn("## 0.2.0\n\n- Second.", changelog) + self.assertNotIn("Unreleased", changelog) + self.assertEqual(self.origin_git("rev-parse", "v0.2.0^{commit}"), self.origin_git("rev-parse", "main")) + self.assertEqual(self.origin_git("cat-file", "-t", "v0.2.0").strip(), "tag", "the tag is annotated") + self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.2.0").strip(), "Cut release 0.2.0") + self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.2.0") + + def test_cuts_the_next_release_through_a_tea_pull_request_merged_fast_forward_then_tags_and_deploys_it(self): + head = self.git(self.clone, "rev-parse", "HEAD") + ran = self.cut() + self.assert_cut(ran) + self.assertIn("v0.2.0", ran.stdout) + calls = self.forge_state()["calls"] + self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls]) + self.assertIn(["tea", "pulls", "merge", "--style", "fast-forward-only", "1"], calls) + self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was") + self.assertEqual(self.git(self.clone, "status", "--porcelain"), "") + + def test_cuts_through_gh_on_a_github_origin(self): + self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git") + self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git") + ran = self.cut() + self.assert_cut(ran) + calls = self.forge_state()["calls"] + self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls]) + self.assertIn(["gh", "pr", "merge", "1", "--rebase"], calls) + + def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self): + self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again") + self.git(self.clone, "push", "-q", "origin", "main") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("0.2.0", ran.stderr) + self.assertEqual(self.forge_state()["pulls"], []) + self.assertEqual(self.origin_git("branch", "--list", "release-*"), "") + + def test_refuses_changing_nothing_until_the_release_review_has_landed(self): + self.git(self.clone, "reset", "-q", "--hard", "HEAD~1") + self.git(self.clone, "push", "-q", "--force", "origin", "main") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("release review", ran.stderr) + self.assertEqual(self.forge_state()["pulls"], []) + + def test_stops_on_a_failing_check_leaving_the_pull_request_and_a_rerun_continues_it(self): + self.set_checks("failure") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("failure", ran.stderr) + self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"]) + self.assertNotEqual(self.origin_git("branch", "--list", "release-0.2.0"), "") + self.assertEqual(self.origin_git("tag", "-l", "v0.2.0"), "") + self.set_checks("success") + self.assert_cut(self.cut()) + self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request") + + def test_stops_with_the_forges_reason_where_the_pull_request_cannot_fast_forward(self): + self.set_checks("failure") + self.cut() + self.commit({"other.md": "Later.\n"}, "Later work") + self.git(self.clone, "push", "-q", "origin", "main") + self.set_checks("success") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("Not possible to fast-forward", ran.stderr) + self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"]) + + def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self): + self.git(self.clone, "switch", "-q", "-c", "side") + self.commit({"side.md": "Side.\n"}, "Side") + self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Wrong") + self.git(self.clone, "push", "-q", "origin", "side", "v0.2.0") + self.git(self.clone, "switch", "-q", "main") + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("v0.2.0", ran.stderr) + self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0") + self.git(self.clone, "tag", "-d", "v0.2.0") + self.origin_git("tag", "-d", "v0.2.0") + self.assert_cut(self.cut()) + self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request") + + +class ChecksPassed(unittest.TestCase): + def test_waits_on_tea_while_a_check_is_pending_and_takes_none_as_passed(self): + statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']) + slept = [] + self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append)) + self.assertEqual(len(slept), 1) + self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', slept.append)) + failed = checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', slept.append) + self.assertIsInstance(failed, Failure) + + if __name__ == "__main__": unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md index 25b94db2..65ae2170 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -32,6 +32,10 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the 2026-10-29, lilleman. Serves goal 1.3 and goal 2. `~/.claude` was this repo's development checkout, so every merge reached every session on the machine at once, its unfinished work included, while other machines took only tags. Now each machine takes only releases: what a release holds is what every session runs, and cutting one is the human's step that ships it. `deploy-release` automates README → Update. It refuses an uncommitted change to a tracked file that the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, and a move that would drop commits no release holds; a model pick, which the clean filter drops, is no change. Valid while Claude Code reads its configuration from one directory per machine. +## 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 + +2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and 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_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. 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. + ## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything 2026-09-20, lilleman. Serves goal 1. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats. diff --git a/todo.md b/todo.md index c1a0770d..b3b34180 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 271 | 0.6.0 | | owner | **Have `deploy-release --cut` cut the next release once it holds no item, through a PR it opens, waits for and merges, then tag and deploy it, and stop with git's or the forge's reason where a step fails.** | 4 | 2 | 3 | 7 | 5 | 1.5 by 6 | 2.3 | | 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | | 229 | 0.7.0 | | | **Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.** | 2 | 1 | 3 | 4 | 2 | code health by 3 | 18.0 | | 170 | 0.7.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 | @@ -79,20 +78,6 @@ ## Details -### 271. Have `deploy-release --cut` cut the next release once it holds no item, through a PR it opens, waits for and merges, then tag and deploy it, and stop with git's or the forge's reason where a step fails. - -`main` on the remote is now protected: nobody can push to it, and it merges only by fast-forward, with no merge commits. So README → Release, which commits on `main`, tags and pushes both, no longer works. - -`deploy-release --cut` runs in the development clone, `~/code/claude-config`. It works out the next release as `chunk-preflight` does, through `bin/release_standing.py`. It fails, changing nothing, unless that release holds no item in `todo.md`, its release review has landed and changes are unreleased. The version is that release: the tool doesn't choose one. - -It then makes the branch `release-` off a freshly fetched `origin/main`, renames `## Unreleased` in `CHANGELOG.md` to the version, and commits `Cut release `. It pushes the branch and opens a PR, with `tea` on a Gitea remote and `gh` on a GitHub one, as `forge_of` in `bin/chunk_preflight/choices.py` tells them apart. It waits for the PR's checks, where there are any, and merges the PR fast-forward only. Then it fetches, tags the merged commit `v`, annotated with the message `Cut release `, and pushes only the tag. Last, it moves `~/.claude` to that tag, as a bare `deploy-release` does. - -Where the PR can't merge, a check fails, the tag already exists on another commit or any step fails, it stops with git's or the forge's reason. It leaves the PR and the branch as they are. A rerun continues where the last run stopped: it finds an open or merged PR for the branch, and a tag already on the merged commit. - -The human runs it, since releases stay theirs; the publishing credentials are theirs too and out of scope. A bare `deploy-release` keeps moving `~/.claude` to the newest tag, and both keep refusing an uncommitted change to a tracked file. The first cut runs from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0. - -Write the tests first in `bin/deploy_release/test_deploy_release.py`, taking expected values from this item. Update README → Release, Update and Tools, `deploy-release --help`, and `CHANGELOG.md`. Record the choice under a new title in `docs/decisions.md` and list it in `AGENTS.md`. Where the change touches README → Tools' map of `bin/`'s shared modules, which a comprehension seat found hard, make it easier to read, such as naming what `deploy_release` imports. - ### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. -- 2.52.0 From f6e96da6750a0eb931dc2bd66a7522df5a293a02 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:47:36 +0100 Subject: [PATCH 2/7] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20take=20only?= =?UTF-8?q?=20origin's=20own=20pull=20request=20at=20the=20branch's=20head?= =?UTF-8?q?=20and=20merge=20it=20pinned=20to=20that=20head?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/deploy_release/cut.py | 32 +++++----- bin/deploy_release/forge.py | 69 +++++++++++++++------- bin/deploy_release/test_deploy_release.py | 71 ++++++++++++++++++----- bin/test_release.py | 2 +- docs/decisions.md | 2 +- todo.md | 2 +- 7 files changed, 122 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 99797e81..b691494a 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. The non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. -- `deploy_release` imports `chunk_preflight`'s forge commands, which list a branch's open pull request with `gh` or `tea`, and `release_standing.py`, which says whether the next release is ready to cut. +- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_standing.py`, which says whether the next release is ready to cut. - `judge_replay` imports `loop_claude`'s judge. - `larv_review` imports `rank_todo.py`'s ranking. - `loop_claude` runs `chunk-preflight` as a process of its own. diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index e17745ca..55320938 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -7,14 +7,14 @@ import re import shutil import tempfile -from chunk_preflight.choices import forge_of -from deploy_release import forge +from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned +from git_repo import default_ref, git from deploy_release.deploy import deploy from failure import Failure -from git_repo import default_ref, git -from release import newest_tag, Release, version -from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned +from deploy_release import forge +from chunk_preflight.choices import forge_of from todo_table import items +from release import newest_tag, Release, version def cut(clone: str, checkout: str) -> str | Failure: @@ -92,27 +92,23 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: if isinstance(url, Failure): return url on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/") - number = forge.open_pull(on, branch, run) - if isinstance(number, Failure): - return number head = branch_head(branch, clone) + if head is None: + if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure): + return pushed + head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") if isinstance(head, Failure): return head + number = forge.open_pull(on, branch, head, run) if number is None: - if head is None: - if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure): - return pushed if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure): return created - number = forge.open_pull(on, branch, run) - if number is None or isinstance(number, Failure): - return number or Failure(f"opened a pull request for {branch}, but the forge lists none") - head = branch_head(branch, clone) - if head is None or isinstance(head, Failure): - return head or Failure(f"origin holds no branch {branch}") + number = forge.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, Failure): + return number if isinstance(passed := forge.checks_passed(on, number, head, run), Failure): return passed - return forge.merge(on, number, run) + return forge.merge(on, number, head, run) def branch_head(branch: str, clone: str) -> str | None | Failure: diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 5433dfd5..35914697 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -1,12 +1,14 @@ -"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart.""" +"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart. + +Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges 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 to the branch after its checks passed, is never merged. +""" import json import subprocess import time import typing -from chunk_preflight.choices import Forge, pulls_command -from chunk_preflight.facts import open_pulls from failure import Failure +from chunk_preflight.choices import Forge # How long tea waits between two reads of the pull request's checks. POLL_SECONDS = 10 @@ -27,13 +29,36 @@ def runner(cwd: str) -> Run: return run -def open_pull(forge: Forge, branch: str, run: Run) -> str | None | Failure: - """The number of branch's open pull request; None where it has none.""" - listed = run(pulls_command(forge, branch)) - if isinstance(listed, Failure): - return listed - found = open_pulls(listed, forge, branch) - return found[0].split()[0].removeprefix("#") if found else None +def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure: + """What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer holding only Gitea's `message` is a Failure.""" + answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint]) + if isinstance(answered, Failure) or not answered.strip(): + return answered + try: + parsed = json.loads(answered) + except ValueError: + return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}") + if isinstance(parsed, dict) and "message" in parsed: + return Failure(f"tea api {endpoint}: {parsed['message']}") + return parsed + + +def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure: + """The number of the open pull request from origin's own branch whose head is head; None where there is none.""" + if forge == "gh": + listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"]) + if isinstance(listed, Failure): + return listed + rows = [line.split("\t") for line in listed.splitlines()] + return next((row[0] for row in rows if row[1:] == [head, "false"]), None) + # Gitea lists at most 50 a page; a release's pull request is among the newest. + pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50") + if isinstance(pulls, Failure): + return pulls + try: + return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None) + except (KeyError, TypeError): + return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}") def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None: @@ -51,15 +76,14 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing. return watched return None while True: - read = run(["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{head}/status"]) - if isinstance(read, Failure): - return read - # Gitea reads a commit with no status as pending, with total_count 0. + status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") + if isinstance(status, Failure): + return status try: - status = json.loads(read) count, state = status["total_count"], status["state"] - except (ValueError, KeyError, TypeError): - return Failure(f"tea api printed no commit status for {head}: {read.strip()[:200]}") + except (KeyError, TypeError): + return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") + # Gitea reads a commit with no status as pending, with total_count 0. if count == 0 or state == "success": return None if state != "pending": @@ -67,8 +91,11 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing. sleep(POLL_SECONDS) -def merge(forge: Forge, number: str, run: Run) -> Failure | None: - # GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title. - command = ["gh", "pr", "merge", number, "--rebase"] if forge == "gh" else ["tea", "pulls", "merge", "--style", "fast-forward-only", number] - merged = run(command) +def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None: + """Merge pull request number fast-forward only, refused by the forge where its head is no longer head.""" + if forge == "gh": + # GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title. + merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head]) + else: + merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}") return merged if isinstance(merged, Failure) else None diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 047bfddf..0fa80571 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -156,24 +156,30 @@ def git(*words): return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True) def pull(number): return next(found for found in state["pulls"] if str(found["number"]) == number) -def merge(number): - head = git("rev-parse", "refs/heads/" + pull(number)["head"]).stdout.strip() +def merge(number, guard): + head = pull(number)["sha"] + if head != guard: + save() + sys.exit("head commit changed") if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode: save() sys.exit("Not possible to fast-forward") git("update-ref", "refs/heads/main", head) pull(number)["state"] = "merged" opened = [found for found in state["pulls"] if found["state"] == "open"] -if forge == "tea" and args == ["pulls", "list", "--fields", "index,head,url", "--output", "tsv"]: - print("index\thead\turl") - for found in opened: - print(f"{found['number']}\t{found['head']}\thttps://forge/pulls/{found['number']}") -elif forge == "gh" and args[:3] == ["pr", "list", "--head"]: +if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]: + repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"} + print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": found["sha"], "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened])) +elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]: for found in opened: if found["head"] == args[3]: - print(f"{found['number']}\thttps://forge/pull/{found['number']}") + print(f"{found['number']}\t{found['sha']}\t{str(found['fork']).lower()}") elif args[:2] in (["pulls", "create"], ["pr", "create"]): - state["pulls"].append({"number": len(state["pulls"]) + 1, "head": args[args.index("--head") + 1], "state": "open"}) + head = args[args.index("--head") + 1] + if any(found["head"] == head and not found["fork"] for found in opened): + save() + sys.exit("pull request already exists for these targets") + state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "sha": git("rev-parse", "refs/heads/" + head).stdout.strip(), "fork": False, "state": "open"}) elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): checks = state["checks"] print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) @@ -184,10 +190,14 @@ elif forge == "gh" and args[:2] == ["pr", "checks"]: if state["checks"] == "failure": save() sys.exit("lint\tfail") -elif args[:3] == ["pulls", "merge", "--style"] and args[3] == "fast-forward-only": - merge(args[4]) -elif args[:2] == ["pr", "merge"] and args[3] == "--rebase": - merge(args[2]) +elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"): + try: + merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id=")) + except SystemExit as refused: + # Gitea answers an error with a message, and tea api exits 0 all the same. + print(json.dumps({"message": str(refused)})) +elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]: + merge(args[2], args[5]) else: save() sys.exit("unexpected call") @@ -264,7 +274,7 @@ class Cut(unittest.TestCase): self.assertIn("v0.2.0", ran.stdout) calls = self.forge_state()["calls"] self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls]) - self.assertIn(["tea", "pulls", "merge", "--style", "fast-forward-only", "1"], calls) + self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call]) self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was") self.assertEqual(self.git(self.clone, "status", "--porcelain"), "") @@ -275,7 +285,7 @@ class Cut(unittest.TestCase): self.assert_cut(ran) calls = self.forge_state()["calls"] self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls]) - self.assertIn(["gh", "pr", "merge", "1", "--rebase"], calls) + self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls]) def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self): self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again") @@ -332,6 +342,37 @@ class Cut(unittest.TestCase): self.assert_cut(self.cut()) self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request") + def test_merges_only_origins_own_pull_request_where_a_fork_opened_one_from_a_branch_of_the_same_name(self): + for forge_name in ("tea", "gh"): + with self.subTest(forge_name): + self.setUp() + if forge_name == "gh": + self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git") + self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git") + self.set_checks("failure") + self.cut() + self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0") + self.commit({"settings.json": "{\"hooks\": \"evil\"}\n"}, "Cut release 0.2.0") + self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0") + self.git(self.clone, "switch", "-q", "main") + state = self.forge_state() + fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"} + self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"}) + self.assert_cut(self.cut()) + self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"]) + self.assertNotIn("evil", self.origin_git("show", "main:settings.json") if "settings.json" in self.origin_git("ls-tree", "--name-only", "main") else "") + + def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self): + self.set_checks("failure") + self.cut() + state = self.forge_state() + state["pulls"][0]["sha"] = "0" * 40 + self.forge_state({**state, "checks": "success"}) + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("already exists", ran.stderr) + self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0") + class ChecksPassed(unittest.TestCase): def test_waits_on_tea_while_a_check_is_pending_and_takes_none_as_passed(self): diff --git a/bin/test_release.py b/bin/test_release.py index 05ca58ea..670415f4 100644 --- a/bin/test_release.py +++ b/bin/test_release.py @@ -6,8 +6,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from release import newest_tag, tagged from test_env import isolated_env +from release import newest_tag, tagged class NewestTag(unittest.TestCase): diff --git a/docs/decisions.md b/docs/decisions.md index 65ae2170..5eb03041 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -34,7 +34,7 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the ## 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 -2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and 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_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. 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-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and 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_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. ## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything diff --git a/todo.md b/todo.md index b3b34180..b5d3fc1f 100644 --- a/todo.md +++ b/todo.md @@ -142,7 +142,7 @@ DRY, in `principles/technical-principles.md`: the list is copied by hand, and se On 2026-11-08 the human answered yes, with a reserved list: a worker takes its own recommendation on a choice no rule reserves for the human, records it in the item or a decision, and interrupts only for a reserved choice or an ask it has no recommendation for. The reserved choices are a release, a change to the ladder or its steps, and a goal, listed in one place. -92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses. +92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Working loop", "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses. ### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose. -- 2.52.0 From 51f5f3be29a9fb16302a46cd768bd72a964573c3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:51:29 +0100 Subject: [PATCH 3/7] =?UTF-8?q?Answer=20product-owner=20round=201:=202=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20rebuild=20a?= =?UTF-8?q?=20branch=20main=20moved=20past,=20drop=20a=20tag=20whose=20pus?= =?UTF-8?q?h=20failed,=20refuse=20another=20project's=20clone,=20say=20whi?= =?UTF-8?q?ch=20pull=20request=20it=20waits=20for?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/deploy_release/cut.py | 62 +++++++++++++++++------ bin/deploy_release/forge.py | 8 +-- bin/deploy_release/main.py | 10 ++-- bin/deploy_release/test_deploy_release.py | 56 ++++++++++++++++---- docs/decisions.md | 2 +- 6 files changed, 103 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91b956dc..1545c947 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request it opens, waits for and merges fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. `main` on the remote now takes no push, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0. +- `deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request: it opens the pull request, waits for its checks and merges it fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. Nobody can push to `main` on the remote any more, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0. - The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none. - In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut. - `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file. diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 55320938..2437a667 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -5,6 +5,7 @@ Each step first checks whether an earlier run did it, so a rerun continues where import pathlib import re import shutil +import sys import tempfile from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned @@ -19,6 +20,8 @@ from release import newest_tag, Release, version def cut(clone: str, checkout: str) -> 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): + return same if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure): return fetched ref = default_ref(cwd=clone) @@ -41,17 +44,31 @@ def cut(clone: str, checkout: str) -> str | Failure: return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}") if isinstance(merged, Failure): return merged - tagged = tag_commit(tag, title, merged, clone) - if isinstance(tagged, Failure): - return tagged + made = tag_commit(tag, title, merged, clone) + if isinstance(made, Failure): + return made if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure): + # A tag only the clone holds would read as cut, so every rerun would refuse. + if made: + git("tag", "--delete", tag, cwd=clone) return pushed moved = deploy(checkout) if isinstance(moved, Failure): - return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}") + return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.") return f"Cut {tag}.\n\n{moved}" +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.""" + 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 None + + 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.""" plan = default_plan(clone, ref) @@ -68,7 +85,7 @@ def ready_release(clone: str, ref: str) -> Release | Failure: case ReviewDue(release=release): return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed") case Unplanned(): - return Failure("no change is unreleased since the last release cut") + return Failure("every change is released already: nothing has landed since the last release cut") case Cut(release=release): return Failure(f"todo.md files items under {version(release)}, which is cut already") case _: @@ -76,7 +93,7 @@ def ready_release(clone: str, ref: str) -> Release | Failure: def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: - """The commit on ref since the newest tag whose title is title; None where there is none.""" + """The commit titled title on ref, after the newest tag; None where there is none.""" tag = newest_tag(clone, merged_into=ref) if isinstance(tag, Failure): return tag @@ -93,8 +110,14 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: return url on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/") head = branch_head(branch, clone) - if head is None: - if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure): + if isinstance(head, Failure): + return head + behind = head is not None and behind_main(branch, head, ref, clone) + if isinstance(behind, Failure): + 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): return pushed head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch") if isinstance(head, Failure): @@ -106,6 +129,7 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: number = forge.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, Failure): return number + print(f"deploy-release: waiting for the checks of pull request {number}", file=sys.stderr) if isinstance(passed := forge.checks_passed(on, number, head, run), Failure): return passed return forge.merge(on, number, head, run) @@ -117,8 +141,15 @@ def branch_head(branch: str, clone: str) -> str | None | Failure: return listed if isinstance(listed, Failure) else next(iter(listed.split()), None) -def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str) -> 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.""" +def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure: + """Whether origin's branch, at head, lacks a commit ref holds.""" + if isinstance(fetched := git("fetch", "--quiet", "origin", f"refs/heads/{branch}", cwd=clone), Failure): + return fetched + return isinstance(git("merge-base", "--is-ancestor", ref, head, cwd=clone), 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): @@ -130,17 +161,18 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str) - changelog.write_text(renamed) if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure): return committed - pushed = git("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree)) + 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 tag_commit(tag: str, title: str, commit: str, clone: str) -> Failure | None: - """Tag commit as tag, annotated with title, unless an earlier run did; a Failure where tag already names another commit.""" +def tag_commit(tag: str, title: str, commit: str, clone: str) -> bool | Failure: + """Tag commit as tag, annotated with title, unless an earlier run did: whether this call made the tag. A Failure where tag already names another commit.""" existing = git("rev-parse", "--verify", "--quiet", f"refs/tags/{tag}^{{commit}}", cwd=clone) if not isinstance(existing, Failure): - return None if existing.strip() == commit else Failure(f"{tag} already tags {existing.strip()[:12]}, not the merged commit {commit[:12]}") + return False if existing.strip() == commit else Failure(f"{tag} already tags {existing.strip()[:12]}, not the merged commit {commit[:12]}") made = git("tag", "--annotate", "--message", title, tag, commit, cwd=clone) - return made if isinstance(made, Failure) else None + return made if isinstance(made, Failure) else True diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 35914697..cd117aa9 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -1,4 +1,4 @@ -"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart. +"""The pull request steps of a cut. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart. Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges 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 to the branch after its checks passed, is never merged. """ @@ -10,7 +10,7 @@ import typing from failure import Failure from chunk_preflight.choices import Forge -# How long tea waits between two reads of the pull request's checks. +# How long the cut waits between two reads of the head commit's status on Gitea. POLL_SECONDS = 10 # Runs a command in the clone: what it printed, or a Failure with its reason. @@ -30,7 +30,7 @@ def runner(cwd: str) -> Run: def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure: - """What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer holding only Gitea's `message` is a Failure.""" + """What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure.""" answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint]) if isinstance(answered, Failure) or not answered.strip(): return answered @@ -92,7 +92,7 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing. def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None: - """Merge pull request number fast-forward only, refused by the forge where its head is no longer head.""" + """Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head.""" if forge == "gh": # GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title. merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head]) diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 01f98a38..7241b123 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -1,4 +1,4 @@ -"""Move the checkout Claude Code reads its configuration from to this repo's newest release, and with --cut cut that release first. +"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release. usage: deploy-release [--cut] [] @@ -16,12 +16,12 @@ is no such change. It also refuses where the newest tag doesn't hold the checkou the move would drop work no release holds. Untracked files, such as Claude Code's sessions and memory, stay as they are. ---cut runs in the development clone. It cuts the next release, as chunk-preflight works it out, and +--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, changing nothing, 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. -1. It commits CHANGELOG.md with ## Unreleased renamed to the version, as `Cut release `, on - a fresh origin/main, and pushes it as the branch release-. The clone's own checkout - stays as it is. +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. 2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so there it rebase-merges the branch, which is already on top of main. diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 0fa80571..2250ce73 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -143,7 +143,7 @@ TODO = """# todo |---|---|---|---|---|---|---|---|---|---|---|---| """ ROW = "| {id} | {release} | | | **Do thing {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n" -# A forge holding origin's pull requests in /forge.json, as tea or gh, whichever name it runs under, reads and changes them. Its merge moves origin's main only by fast-forward. +# A fake forge, run as tea or as gh. It keeps origin's pull requests in /forge.json. Its merge moves origin's main only by fast-forward. FAKE_FORGE = """#!PYTHON import json, pathlib, subprocess, sys forge, args = pathlib.Path(sys.argv[0]).name, sys.argv[1:] @@ -156,8 +156,14 @@ def git(*words): return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True) def pull(number): return next(found for found in state["pulls"] if str(found["number"]) == number) +# A fork's head as given; origin's own pull request follows its branch, as a forge does. +def sha(found): + return found.get("sha") or git("rev-parse", "refs/heads/" + found["head"]).stdout.strip() def merge(number, guard): - head = pull(number)["sha"] + head = sha(pull(number)) + if state.get("refuse_merge"): + save() + sys.exit("Not possible to fast-forward") if head != guard: save() sys.exit("head commit changed") @@ -169,17 +175,17 @@ def merge(number, guard): opened = [found for found in state["pulls"] if found["state"] == "open"] if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]: repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"} - print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": found["sha"], "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened])) + print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened])) elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]: for found in opened: if found["head"] == args[3]: - print(f"{found['number']}\t{found['sha']}\t{str(found['fork']).lower()}") + print(f"{found['number']}\t{sha(found)}\t{str(found['fork']).lower()}") elif args[:2] in (["pulls", "create"], ["pr", "create"]): head = args[args.index("--head") + 1] if any(found["head"] == head and not found["fork"] for found in opened): save() sys.exit("pull request already exists for these targets") - state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "sha": git("rev-parse", "refs/heads/" + head).stdout.strip(), "fork": False, "state": "open"}) + state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"}) elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"): checks = state["checks"] print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1})) @@ -316,17 +322,45 @@ class Cut(unittest.TestCase): self.assert_cut(self.cut()) self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request") - def test_stops_with_the_forges_reason_where_the_pull_request_cannot_fast_forward(self): - self.set_checks("failure") - self.cut() - self.commit({"other.md": "Later.\n"}, "Later work") - self.git(self.clone, "push", "-q", "origin", "main") - self.set_checks("success") + def test_stops_with_the_forges_reason_where_it_refuses_the_merge(self): + self.forge_state({**self.forge_state(), "refuse_merge": True}) ran = self.cut() self.assertEqual(ran.returncode, 1) self.assertIn("Not possible to fast-forward", ran.stderr) self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"]) + def test_a_rerun_rebuilds_the_cut_commit_on_main_where_main_moved_past_the_branch(self): + self.set_checks("failure") + self.cut() + self.commit({"other.md": "Later.\n"}, "Fix the check") + self.git(self.clone, "push", "-q", "origin", "main") + self.set_checks("success") + self.assert_cut(self.cut()) + self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main~1").strip(), "Fix the check") + self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request") + + def test_deletes_the_tag_it_made_where_its_push_fails_so_a_rerun_tags_again(self): + hook = self.origin / "hooks" / "pre-receive" + hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then echo 'tags are refused' >&2; exit 1; fi\n") + hook.chmod(0o755) + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("tags are refused", ran.stderr) + self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0"), "") + hook.unlink() + self.assert_cut(self.cut()) + + def test_refuses_changing_nothing_where_the_clone_is_not_a_clone_of_the_checkouts_origin(self): + self.git(self.target, "remote", "set-url", "origin", str(self.temp / "other.git")) + ran = self.cut() + self.assertEqual(ran.returncode, 1) + self.assertIn("origin", ran.stderr) + self.assertEqual(self.forge_state()["pulls"], []) + + def test_says_which_pull_request_it_waits_for(self): + ran = self.cut() + self.assertIn("pull request 1", ran.stderr) + def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self): self.git(self.clone, "switch", "-q", "-c", "side") self.commit({"side.md": "Side.\n"}, "Side") diff --git a/docs/decisions.md b/docs/decisions.md index 5eb03041..34bd1e03 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -34,7 +34,7 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the ## 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 -2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and 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_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-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_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. ## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything -- 2.52.0 From db993f159efae7a295202144f56ff43d0a713802 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:51:29 +0100 Subject: [PATCH 4/7] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20the=20rewor?= =?UTF-8?q?ding=20landed=20with=20the=20product-owner=20round's=20fixes,?= =?UTF-8?q?=20and=20the=20rebuild=20answers=20the=20rerun=20finding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 10dd5fb527606bb1fa9df58bfe83fbe0df8cbc76 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:55:44 +0100 Subject: [PATCH 5/7] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20drop=20cut?= =?UTF-8?q?=20tags=20no=20run=20pushed,=20split=20the=20fork=20and=20check?= =?UTF-8?q?s=20tests,=20test=20the=20usage=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/deploy_release/cut.py | 36 ++++++---- bin/deploy_release/main.py | 4 +- bin/deploy_release/test_deploy_release.py | 83 +++++++++++++++-------- 3 files changed, 80 insertions(+), 43 deletions(-) diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index 2437a667..386408ec 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -24,6 +24,8 @@ def cut(clone: str, checkout: str) -> str | 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 @@ -44,13 +46,11 @@ def cut(clone: str, checkout: str) -> str | Failure: return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}") if isinstance(merged, Failure): return merged - made = tag_commit(tag, title, merged, clone) - if isinstance(made, Failure): + if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure): return made if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure): - # A tag only the clone holds would read as cut, so every rerun would refuse. - if made: - git("tag", "--delete", tag, cwd=clone) + # Until a rerun, chunk-preflight would read a tag only the clone holds as cut. + git("tag", "--delete", tag, cwd=clone) return pushed moved = deploy(checkout) if isinstance(moved, Failure): @@ -58,6 +58,23 @@ def cut(clone: str, checkout: str) -> str | Failure: return f"Cut {tag}.\n\n{moved}" +def drop_unpushed_cut_tags(clone: str) -> Failure | None: + """Delete each v* tag the clone holds but origin doesn't, where it tags a commit titled `Cut release `: one a run made and never pushed, such as a run that died between the two. The clone reads cut releases from its own tags, so such a tag would read as a cut nobody published.""" + local = git("tag", "--list", "v*", "--format=%(refname:short) %(*subject)", cwd=clone) + remote = git("ls-remote", "--tags", "--refs", "origin", "refs/tags/v*", cwd=clone) + if isinstance(local, Failure): + return local + if isinstance(remote, Failure): + return remote + pushed = {line.split("refs/tags/", 1)[-1] for line in remote.splitlines()} + for line in local.splitlines(): + tag, _, subject = line.partition(" ") + if tag not in pushed and subject == f"Cut release {tag.removeprefix('v')}": + if isinstance(deleted := git("tag", "--delete", tag, cwd=clone), Failure): + return deleted + return 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.""" urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)] @@ -167,12 +184,3 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r finally: git("worktree", "remove", "--force", str(worktree), cwd=clone) shutil.rmtree(worktree.parent, ignore_errors=True) - - -def tag_commit(tag: str, title: str, commit: str, clone: str) -> bool | Failure: - """Tag commit as tag, annotated with title, unless an earlier run did: whether this call made the tag. A Failure where tag already names another commit.""" - existing = git("rev-parse", "--verify", "--quiet", f"refs/tags/{tag}^{{commit}}", cwd=clone) - if not isinstance(existing, Failure): - return False if existing.strip() == commit else Failure(f"{tag} already tags {existing.strip()[:12]}, not the merged commit {commit[:12]}") - made = git("tag", "--annotate", "--message", title, tag, commit, cwd=clone) - return made if isinstance(made, Failure) else True diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 7241b123..3016ebfe 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -28,8 +28,8 @@ landed and changes are unreleased. The release names the version; the tool doesn 3. It tags the merged commit v, annotated `Cut release `, pushes only the tag, then moves to it as above. 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, a cut commit -already merged and a tag already on it. Once the tag is pushed, the release is cut: where only the +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. """ import os diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 2250ce73..3b775635 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -8,7 +8,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from deploy_release.forge import checks_passed +from deploy_release.forge import checks_passed, POLL_SECONDS from failure import Failure from test_env import isolated_env @@ -285,8 +285,7 @@ class Cut(unittest.TestCase): self.assertEqual(self.git(self.clone, "status", "--porcelain"), "") def test_cuts_through_gh_on_a_github_origin(self): - self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git") - self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git") + self.use_github() ran = self.cut() self.assert_cut(ran) calls = self.forge_state()["calls"] @@ -376,25 +375,52 @@ class Cut(unittest.TestCase): self.assert_cut(self.cut()) self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request") - def test_merges_only_origins_own_pull_request_where_a_fork_opened_one_from_a_branch_of_the_same_name(self): - for forge_name in ("tea", "gh"): - with self.subTest(forge_name): - self.setUp() - if forge_name == "gh": - self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git") - self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git") - self.set_checks("failure") - self.cut() - self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0") - self.commit({"settings.json": "{\"hooks\": \"evil\"}\n"}, "Cut release 0.2.0") - self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0") - self.git(self.clone, "switch", "-q", "main") - state = self.forge_state() - fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"} - self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"}) - self.assert_cut(self.cut()) - self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"]) - self.assertNotIn("evil", self.origin_git("show", "main:settings.json") if "settings.json" in self.origin_git("ls-tree", "--name-only", "main") else "") + def use_github(self) -> None: + """Point the clone's origin at a GitHub URL that git reads as the local origin, so the cut runs gh.""" + self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git") + self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git") + + def assert_fork_pull_ignored(self) -> None: + """After a failed first run, a fork opens a pull request from its own release-0.2.0, listed first; the rerun merges only origin's.""" + self.set_checks("failure") + self.cut() + self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0") + self.commit({"settings.json": "{}\n"}, "Cut release 0.2.0") + self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0") + self.git(self.clone, "switch", "-q", "main") + state = self.forge_state() + fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"} + self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"}) + self.assert_cut(self.cut()) + self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"]) + self.assertNotIn("settings.json", self.origin_git("ls-tree", "--name-only", "main")) + + def test_merges_only_origins_own_pull_request_on_tea_where_a_fork_opened_one_from_a_branch_of_the_same_name(self): + self.assert_fork_pull_ignored() + + def test_merges_only_origins_own_pull_request_on_gh_where_a_fork_opened_one_from_a_branch_of_the_same_name(self): + self.use_github() + self.assert_fork_pull_ignored() + + def test_a_rerun_drops_a_cut_tag_an_earlier_run_made_but_never_pushed(self): + self.set_checks("failure") + self.cut() + self.set_checks("success") + hook = self.origin / "hooks" / "pre-receive" + hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then exit 1; fi\n") + hook.chmod(0o755) + self.cut() + # A run that died between tagging and pushing left this tag behind. + self.git(self.clone, "fetch", "-q", "origin") + self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Cut release 0.2.0", "origin/main") + hook.unlink() + self.assert_cut(self.cut()) + + 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) + self.assertIn("usage", ran.stderr) + self.assertEqual(self.forge_state()["calls"], []) def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self): self.set_checks("failure") @@ -409,14 +435,17 @@ class Cut(unittest.TestCase): class ChecksPassed(unittest.TestCase): - def test_waits_on_tea_while_a_check_is_pending_and_takes_none_as_passed(self): + def test_waits_on_tea_while_a_check_is_pending(self): statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}']) slept = [] self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append)) - self.assertEqual(len(slept), 1) - self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', slept.append)) - failed = checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', slept.append) - self.assertIsInstance(failed, Failure) + self.assertEqual(slept, [POLL_SECONDS]) + + def test_takes_a_commit_with_no_status_on_tea_as_passed(self): + self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', self.fail)) + + def test_fails_on_tea_where_a_check_failed(self): + self.assertIsInstance(checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', self.fail), Failure) if __name__ == "__main__": -- 2.52.0 From 0bdea6503088b18c97b967ce535a8e7b9848b7e2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:58:13 +0100 Subject: [PATCH 6/7] =?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);=20test=20that?= =?UTF-8?q?=20a=20pushed=20cut=20tag=20and=20an=20unpushed=20tag=20elsewhe?= =?UTF-8?q?re=20survive?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/deploy_release/test_deploy_release.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 3b775635..cacc2c96 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -416,6 +416,15 @@ class Cut(unittest.TestCase): hook.unlink() self.assert_cut(self.cut()) + def test_keeps_a_pushed_cut_tag_and_an_unpushed_tag_on_any_other_commit(self): + self.git(self.clone, "switch", "-q", "-c", "side") + self.commit({"side.md": "Side.\n"}, "Side") + self.git(self.clone, "tag", "-a", "v9.9.9", "-m", "Mine") + self.git(self.clone, "switch", "-q", "main") + self.assert_cut(self.cut()) + self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses") + self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"]) + def test_takes_no_option_but_cut(self): 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) -- 2.52.0 From f134c6dede6708639a898de87d3fd7efccb95394 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:58:13 +0100 Subject: [PATCH 7/7] =?UTF-8?q?Answer=20product-owner=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0