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