From 29b986ca42222335db07def9d166fbbabca10241 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 10:43:54 +0100 Subject: [PATCH] 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.