From 8cc9a89265595c5f0cf61d6c824e7f41cc169684 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 10 Nov 2026 10:50:15 +0100 Subject: [PATCH 1/7] Remove a merged chunk's worktree and branch and fast-forward the main checkout with chunk-pr clean --- CHANGELOG.md | 1 + CLAUDE.md | 2 +- README.md | 2 +- bin/chunk_pr/main.py | 61 +++++++++++++++++++++++- bin/chunk_pr/test_chunk_pr.py | 88 +++++++++++++++++++++++++++++++++++ docs/reading-cost.md | 17 +++++++ skills/larv-review/SKILL.md | 3 +- todo.md | 5 -- 8 files changed, 169 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12efc979..2201f58d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `chunk-pr clean` removes a merged chunk's worktree and branch and fast-forwards the main checkout, which it leaves as it was, saying why, while that is dirty or on another branch. - `review-replay` now replays each round at the commit with the newest author time at or before the round's time, and takes the clone's base the same way by the time the chunk began. It took the first such commit in log order, so a commit authored early but merged late, such as a dependency bump, could win over the commits the round reviewed. - The shared goal every project pursues, code health, now asks that code stay easy to read, change safely and debug, tomorrow and after seven years of development. - `rank_todo.py` now lets an item that adds a test, a gate leg or a probe name the maintain goal it guards, by how much more confident the project becomes that the goal holds, 1 to 10. Each point is worth 0.5. diff --git a/CLAUDE.md b/CLAUDE.md index 5f93b145..fab61046 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -95,7 +95,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. - Branch for a `todo.md` item without a ticket: `item-`, in the worktree `-item-` beside the checkout, as `chunk-preflight` makes them. - Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. -- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. +- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout. ## Handoffs - Write no handoff document. The repo holds everything the next session needs: the plan, the decisions, and every script, sketch or measurement those depend on. A file outside the repo is unreachable from another machine's checkout. diff --git a/README.md b/README.md index e0db2139..b52ad66d 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro 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-pr open|ready|merge` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; `chunk-pr --help` states the steps. +- `chunk-pr open|ready|merge|clean` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps. - `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts. - `command-patterns []` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release; `command-patterns --help` states its columns. - `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. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 453988b0..60ac5c6f 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -1,8 +1,9 @@ -"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere. +"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; then clean up after it. usage: chunk-pr open [<body>] chunk-pr ready chunk-pr merge --gate-passed + chunk-pr clean Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open pull request only while its head is the commit checked out, so push before you run them. @@ -18,6 +19,11 @@ merge merges the pull request, and only while its head is still the commit ch a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the merge gate passed on that commit; without it, chunk-pr refuses. +clean fetches origin and, once origin's default branch holds the commit checked out, removes + the chunk's worktree and its branch, then fast-forwards the main checkout to origin's + default branch. It leaves the main checkout as it was where that has uncommitted or + untracked files or another branch checked out, and fails saying so: a dirty checkout is + for its owner to look at. A worktree with uncommitted changes git keeps, branch and all. It prints what it did, exit 0, or why it failed, exit 1. """ @@ -30,7 +36,7 @@ from chunk_preflight.gathered import Forge from chunk_preflight.choices import forge_of from deploy_release.forge import gitea, open_pull, Run, runner -USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed" +USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean" # Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them. METHODS: dict[Forge, tuple[tuple[str, str], ...]] = { @@ -64,6 +70,8 @@ def step(argv: list[str], run: Run) -> str | Failure: return merged(run) case ["merge"]: return Failure("merge only once the gate has passed, and say so with --gate-passed") + case ["clean"]: + return cleaned(run) return Failure(USAGE) @@ -156,3 +164,52 @@ def merge_method(forge: Forge, run: Run) -> str | Failure: return settings allowed = next((method for setting, method in METHODS[forge] if isinstance(settings, dict) and settings.get(setting) is True), None) return allowed if allowed is not None else Failure(f"the repository allows none of the merge methods chunk-pr knows: {', '.join(method for _, method in METHODS[forge])}") + + +def cleaned(run: Run) -> str | Failure: + found = checkout(run) + if isinstance(found, Failure): + return found + _, branch, head = found + answers = [run(["git", *args]) for args in (["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], ["worktree", "list", "--porcelain"], ["rev-parse", "--show-toplevel"])] + failed = next((answer for answer in answers if isinstance(answer, Failure)), None) + if failed is not None: + return failed + base, listed, worktree = (str(answer).strip() for answer in answers) + # git lists the main checkout first. + main = listed.splitlines()[0].removeprefix("worktree ") + if worktree == main: + return Failure(f"{main} is the main checkout; run clean in the chunk's worktree") + fetched = run(["git", "fetch", "--quiet", "origin"]) + if isinstance(fetched, Failure): + return fetched + if isinstance(run(["git", "merge-base", "--is-ancestor", head, base]), Failure): + return Failure(f"{base} doesn't hold {head[:12]}: {branch} is not merged, so its worktree and branch stay") + at_main = runner(main) + left = kept_as_it_was(at_main, base.removeprefix("origin/")) + if left is None: + forwarded = at_main(["git", "merge", "--quiet", "--ff-only", base]) + if isinstance(forwarded, Failure): + return forwarded + removed = at_main(["git", "worktree", "remove", worktree]) + if isinstance(removed, Failure): + return removed + # Not -d: the check above already found the branch merged, and -d would compare it with the main checkout's HEAD or a stale upstream instead. + deleted = at_main(["git", "branch", "--quiet", "-D", branch]) + if isinstance(deleted, Failure): + return deleted + done = f"Removed worktree {worktree} and branch {branch}" + if left is not None: + return Failure(f"{done}, but left {main} as it was: {left}") + return f"{done}, and fast-forwarded {main} to {base}." + + +def kept_as_it_was(at_main: Run, default: str) -> str | None: + """Why the main checkout must not move, or None where it may fast-forward.""" + branch = at_main(["git", "symbolic-ref", "--quiet", "--short", "HEAD"]) + if isinstance(branch, Failure) or branch.strip() != default: + return f"it has {'no branch' if isinstance(branch, Failure) else branch.strip()} checked out, not {default}" + status = at_main(["git", "status", "--porcelain"]) + if isinstance(status, Failure): + return status.reason + return f"it has uncommitted or untracked files:\n{status.rstrip()}" if status.strip() else None diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index efa3189e..abb6cbb2 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -2,6 +2,7 @@ import json import pathlib import subprocess import sys +import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -172,6 +173,93 @@ class Merge(unittest.TestCase): self.assertEqual(checkout.acted(), []) +class Clean(unittest.TestCase): + """A real origin whose default branch is main, its clone project, and the worktree project-item-7 on item-7, one commit ahead and pushed.""" + + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + root = pathlib.Path(folder.name) + self.origin, self.project, self.worktree = root / "origin.git", root / "project", root / "project-item-7" + self.git(root, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin)) + self.git(root, "clone", "--quiet", str(self.origin), str(self.project)) + self.commit(self.project, "first") + self.git(self.project, "push", "--quiet", "origin", "main") + self.git(self.project, "remote", "set-head", "origin", "--auto") + self.git(self.project, "worktree", "add", "--quiet", "-b", "item-7", str(self.worktree), "origin/main") + self.commit(self.worktree, "the chunk") + self.git(self.worktree, "push", "--quiet", "--set-upstream", "origin", "item-7") + + def git(self, folder: pathlib.Path, *args: str) -> str: + return subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", *args], cwd=folder, check=True, capture_output=True, encoding="utf-8", env=isolated_env()).stdout.strip() + + def commit(self, folder: pathlib.Path, message: str): + self.git(folder, "commit", "--quiet", "--allow-empty", "-m", message) + + def merge_on_origin(self): + self.git(self.worktree, "push", "--quiet", "origin", "item-7:main") + + def clean(self) -> subprocess.CompletedProcess: + return subprocess.run([str(TOOL), "clean"], cwd=self.worktree, capture_output=True, encoding="utf-8", env=isolated_env()) + + def branches(self) -> list[str]: + return self.git(self.project, "branch", "--format=%(refname:short)").splitlines() + + def test_a_merged_chunk_loses_its_worktree_and_branch_and_the_checkout_fast_forwards(self): + self.merge_on_origin() + merged = self.git(self.worktree, "rev-parse", "HEAD") + done = self.clean() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertFalse(self.worktree.exists()) + self.assertEqual(self.branches(), ["main"]) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), merged) + self.assertIn("item-7", done.stdout) + + def test_an_unmerged_chunk_keeps_everything(self): + done = self.clean() + self.assertEqual(done.returncode, 1) + self.assertIn("not merged", done.stderr) + self.assertTrue(self.worktree.exists()) + self.assertEqual(sorted(self.branches()), ["item-7", "main"]) + + def test_a_dirty_checkout_is_left_as_it_was_and_reported(self): + self.merge_on_origin() + before = self.git(self.project, "rev-parse", "HEAD") + (self.project / "notes.txt").write_text("mine\n") + done = self.clean() + self.assertEqual(done.returncode, 1) + self.assertIn("uncommitted", done.stderr) + self.assertIn(str(self.project), done.stderr) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), before) + self.assertEqual((self.project / "notes.txt").read_text(), "mine\n") + self.assertFalse(self.worktree.exists()) + self.assertEqual(self.branches(), ["main"]) + + def test_a_checkout_on_another_branch_is_left_as_it_was_and_reported(self): + self.merge_on_origin() + self.git(self.project, "switch", "--quiet", "-c", "elsewhere") + before = self.git(self.project, "rev-parse", "HEAD") + done = self.clean() + self.assertEqual(done.returncode, 1) + self.assertIn("elsewhere", done.stderr) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), before) + self.assertFalse(self.worktree.exists()) + + def test_a_worktree_with_uncommitted_changes_is_kept(self): + self.merge_on_origin() + (self.worktree / "draft.txt").write_text("unsaved\n") + done = self.clean() + self.assertEqual(done.returncode, 1) + self.assertTrue((self.worktree / "draft.txt").exists()) + self.assertIn("item-7", self.branches()) + + def test_the_main_checkout_itself_is_refused(self): + done = subprocess.run([str(TOOL), "clean"], cwd=self.project, capture_output=True, encoding="utf-8", env=isolated_env()) + self.assertEqual(done.returncode, 1) + self.assertIn("worktree", done.stderr) + self.assertTrue(self.worktree.exists()) + + class Launcher(unittest.TestCase): def test_help_exits_0_and_a_wrong_step_exits_1(self): self.assertEqual(subprocess.run([str(TOOL), "--help"], capture_output=True, env=isolated_env()).returncode, 0) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index ccd0c7a4..756ad9bc 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1453,3 +1453,20 @@ Read most (opens and searches): - `bin/chunk_preflight/main.py` 2 - `bin/release_plan/todo_table.py` 2 - `docs/decisions.md` 2 + +## Reading cost, chunk db83bf6d8fd5, finished 2026-11-10T09:46:42Z + +83308 new input tokens before the first commit. + +Read most (opens and searches): + +- `docs/decisions.md` 11 +- `AGENTS.md` 2 +- `CHANGELOG.md` 2 +- `README.md` 2 +- `bin/review_replay/main.py` 2 +- `ci.sh` 2 +- `bin/loop_claude/effects.py` 1 +- `bin/review-replay` 1 +- `bin/review_replay/rounds.py` 1 +- `bin/review_replay/test_review_replay.py` 1 diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index f5f68619..d0509529 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -195,7 +195,8 @@ Launch prose-reviewer with what the diff touched and every section this review c 2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded. 3. Aligned, every pass done and everything green → **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. 4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". -5. Stop. The next chunk gets a fresh session. +5. Run `~/.claude/bin/chunk-pr clean` in the chunk's worktree. It removes the worktree and the branch and fast-forwards the main checkout; a failure it prints, such as a dirty main checkout, goes in the summary. +6. Stop. The next chunk gets a fresh session. ## 6. Wrap up diff --git a/todo.md b/todo.md index f6d4a2ab..03461b56 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +14,6 @@ |---|---|---|---|---|---|---|---|---|---|---|---| | 277 | 0.7.0 | | question | **Map the size of the code an item names onto S, on a scale the human picks, and have `score-outcomes` print that S for the item being scored and for each finished item it lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 4, 1.4 by 3 | 2.4 | | 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 | -| 281 | 0.7.0 | | | **Remove a merged chunk's worktree and branch and fast-forward the main checkout with one command.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 | | 290 | 0.7.0 | | defect | **Have `rule-hook overrides` read the branch's reflog when a file or folder shares the branch's name.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 | | 286 | 0.7.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 4 | 1.0 | | 287 | 0.8.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 | @@ -72,10 +71,6 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3). -### 281. Remove a merged chunk's worktree and branch and fast-forward the main checkout with one command. - -Audit of release 0.2.0's chunks (item 162): 31 chunks ran `git worktree remove`, `git branch -d` and `git pull --ff-only` by hand, 56 calls and about 5k command tokens. The program refuses a dirty main checkout, as `CLAUDE.md` → "Working with the codebase" says, and reports it. - ### 290. Have `rule-hook overrides` read the branch's reflog when a file or folder shares the branch's name. `bin/rule_hook/override_log.py:98` runs `git reflog show --format=%H <branch>` without a `--` after the branch. When a tracked path has the branch's name, git stops with "ambiguous argument … both revision and filename", and `rule-hook overrides` exits saying it cannot tell which overrides are the chunk's. larv-review's Overrides pass then has no list to judge, so an override in such a chunk would go unreviewed. Found on 2026-11-09 in PR #456, whose branch and new folder were both `reviewer-merge-trials`. Fix by passing `--` after the branch, and test it with a branch named after a tracked folder. -- 2.52.0 From a49a59f7ff9d3baaf84333186db61a4b514a88bc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:05:05 +0100 Subject: [PATCH 2/7] =?UTF-8?q?Answer=20product-owner=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20count=20a?= =?UTF-8?q?=20pull=20request=20the=20forge=20reports=20merged=20by=20any?= =?UTF-8?q?=20method,=20check=20the=20worktree=20and=20main=20checkout=20b?= =?UTF-8?q?efore=20acting,=20remove=20todo=20items=20before=20the=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/chunk_pr/main.py | 166 +++++++++++++++++++++---------- bin/chunk_pr/test_chunk_pr.py | 180 ++++++++++++++++++++++++---------- bin/deploy_release/forge.py | 18 +++- skills/larv-review/SKILL.md | 6 +- 5 files changed, 260 insertions(+), 112 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2201f58d..ac0e0997 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `chunk-pr clean` removes a merged chunk's worktree and branch and fast-forwards the main checkout, which it leaves as it was, saying why, while that is dirty or on another branch. +- `chunk-pr clean` removes a merged chunk's worktree and local branch and fast-forwards the main checkout. It leaves a main checkout with uncommitted files, another branch or commits of its own as it was, and says why. - `review-replay` now replays each round at the commit with the newest author time at or before the round's time, and takes the clone's base the same way by the time the chunk began. It took the first such commit in log order, so a commit authored early but merged late, such as a dependency bump, could win over the commits the round reviewed. - The shared goal every project pursues, code health, now asks that code stay easy to read, change safely and debug, tomorrow and after seven years of development. - `rank_todo.py` now lets an item that adds a test, a gate leg or a probe name the maintain goal it guards, by how much more confident the project becomes that the goal holds, 1 to 10. Each point is worth 0.5. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 60ac5c6f..c2fed835 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -1,4 +1,4 @@ -"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; then clean up after it. +"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch. usage: chunk-pr open <title> [<body>] chunk-pr ready @@ -19,22 +19,26 @@ merge merges the pull request, and only while its head is still the commit ch a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the merge gate passed on that commit; without it, chunk-pr refuses. -clean fetches origin and, once origin's default branch holds the commit checked out, removes - the chunk's worktree and its branch, then fast-forwards the main checkout to origin's - default branch. It leaves the main checkout as it was where that has uncommitted or - untracked files or another branch checked out, and fails saying so: a dirty checkout is - for its owner to look at. A worktree with uncommitted changes git keeps, branch and all. +clean acts once the forge reports the branch's pull request merged at the commit checked out, + by any merge method. It fetches origin, fast-forwards the main checkout to origin's + default branch, removes the chunk's worktree, then deletes the local branch; origin's + branch stays. Where the worktree has uncommitted or untracked files, it refuses and + touches nothing. Where the main checkout has uncommitted or untracked files, another + branch checked out, or commits origin's default branch lacks, it leaves that as it was, + still removes the worktree and the branch, and fails saying why. It prints what it did, exit 0, or why it failed, exit 1. """ +import dataclasses import json import os import sys +import typing from failure import Failure from chunk_preflight.gathered import Forge from chunk_preflight.choices import forge_of -from deploy_release.forge import gitea, open_pull, Run, runner +from deploy_release.forge import gitea, merged_pull, open_pull, Run, runner USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean" @@ -75,16 +79,30 @@ def step(argv: list[str], run: Run) -> str | Failure: return Failure(USAGE) +def answers(run: Run, *commands: list[str]) -> list[str] | Failure: + """What each git command printed, stripped, or the first Failure.""" + answered = [run(["git", *args]) for args in commands] + failed = next((answer for answer in answered if isinstance(answer, Failure)), None) + return failed if failed is not None else [str(answer).strip() for answer in answered] + + def checkout(run: Run) -> tuple[Forge, str, str] | Failure: """The forge, the branch checked out and its head commit.""" - answers = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["symbolic-ref", "--short", "HEAD"], ["rev-parse", "HEAD"])] - failed = next((answer for answer in answers if isinstance(answer, Failure)), None) - if failed is not None: - return failed - origin, branch, head = (str(answer).strip() for answer in answers) + found = answers(run, ["remote", "get-url", "origin"], ["symbolic-ref", "--short", "HEAD"], ["rev-parse", "HEAD"]) + if isinstance(found, Failure): + return found + origin, branch, head = found return forge_of(origin), branch, head +def default_branch(run: Run) -> str | Failure: + """origin's default branch, such as main.""" + default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) + if isinstance(default, Failure): + return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}") + return default.strip().removeprefix("origin/") + + def pull(run: Run) -> tuple[Forge, str, str] | Failure: """The forge, the number of the branch's open pull request at its head, and that head.""" found = checkout(run) @@ -102,10 +120,9 @@ def opened(title: str, body: str, run: Run) -> str | Failure: if isinstance(found, Failure): return found forge, branch, head = found - default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) - if isinstance(default, Failure): - return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}") - base = default.strip().removeprefix("origin/") + base = default_branch(run) + if isinstance(base, Failure): + return base if branch == base: return Failure(f"{branch} is origin's default branch; open the pull request from the chunk's branch") pushed = run(["git", "push", "--quiet", "--set-upstream", "origin", branch]) @@ -166,50 +183,93 @@ def merge_method(forge: Forge, run: Run) -> str | Failure: return allowed if allowed is not None else Failure(f"the repository allows none of the merge methods chunk-pr knows: {', '.join(method for _, method in METHODS[forge])}") -def cleaned(run: Run) -> str | Failure: +@dataclasses.dataclass(frozen=True) +class Chunk: + """A merged chunk's worktree and branch, the main checkout of their repository, and origin's default branch.""" + worktree: str + branch: str + main: str + default: str + + +def cleaned(run: Run, at: typing.Callable[[str], Run] = runner) -> str | Failure: + """Remove the worktree and branch of the merged chunk run is in, and fast-forward the main checkout; at(folder) runs commands in folder, here the main checkout.""" + chunk = merged_chunk(run) + if isinstance(chunk, Failure): + return chunk + at_main = at(chunk.main) + left = kept_as_it_was(at_main, chunk.default) + files = unsaved(run) + if isinstance(files, Failure): + return files + if files: + also = f"\nIt would also have left {chunk.main} as it was: {left}" if left else "" + return Failure(f"left everything as it was: {chunk.worktree} has uncommitted or untracked files:\n{files}{also}") + return removed(chunk, at_main, left) + + +def merged_chunk(run: Run) -> Chunk | Failure: + """The chunk run is in, once the forge reports its pull request merged at its head. It fetches origin, so the main checkout can fast-forward to the merge.""" found = checkout(run) if isinstance(found, Failure): return found - _, branch, head = found - answers = [run(["git", *args]) for args in (["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], ["worktree", "list", "--porcelain"], ["rev-parse", "--show-toplevel"])] - failed = next((answer for answer in answers if isinstance(answer, Failure)), None) - if failed is not None: - return failed - base, listed, worktree = (str(answer).strip() for answer in answers) + forge, branch, head = found + default = default_branch(run) + if isinstance(default, Failure): + return default + folders = worktree_and_main(run) + if isinstance(folders, Failure): + return folders + number = merged_pull(forge, branch, head, run) + if number is None: + return Failure(f"no merged pull request from {branch} at {head[:12]}, so its worktree and branch stay") + fetched = number if isinstance(number, Failure) else run(["git", "fetch", "--quiet", "origin"]) + return fetched if isinstance(fetched, Failure) else Chunk(folders[0], branch, folders[1], default) + + +def worktree_and_main(run: Run) -> tuple[str, str] | Failure: + """The worktree run is in, and the main checkout of its repository. Run in the main checkout itself, it fails.""" + folders = answers(run, ["rev-parse", "--show-toplevel"], ["worktree", "list", "--porcelain"]) + if isinstance(folders, Failure): + return folders # git lists the main checkout first. - main = listed.splitlines()[0].removeprefix("worktree ") - if worktree == main: - return Failure(f"{main} is the main checkout; run clean in the chunk's worktree") - fetched = run(["git", "fetch", "--quiet", "origin"]) - if isinstance(fetched, Failure): - return fetched - if isinstance(run(["git", "merge-base", "--is-ancestor", head, base]), Failure): - return Failure(f"{base} doesn't hold {head[:12]}: {branch} is not merged, so its worktree and branch stay") - at_main = runner(main) - left = kept_as_it_was(at_main, base.removeprefix("origin/")) - if left is None: - forwarded = at_main(["git", "merge", "--quiet", "--ff-only", base]) - if isinstance(forwarded, Failure): - return forwarded - removed = at_main(["git", "worktree", "remove", worktree]) - if isinstance(removed, Failure): - return removed - # Not -d: the check above already found the branch merged, and -d would compare it with the main checkout's HEAD or a stale upstream instead. - deleted = at_main(["git", "branch", "--quiet", "-D", branch]) - if isinstance(deleted, Failure): - return deleted - done = f"Removed worktree {worktree} and branch {branch}" - if left is not None: - return Failure(f"{done}, but left {main} as it was: {left}") - return f"{done}, and fast-forwarded {main} to {base}." + worktree, main = folders[0], folders[1].splitlines()[0].removeprefix("worktree ") + return Failure(f"{main} is the main checkout; run clean in the chunk's worktree") if worktree == main else (worktree, main) + + +def unsaved(run: Run) -> str | Failure: + """The uncommitted and untracked files of the checkout run is in, as git status lists them; empty where there are none.""" + status = run(["git", "status", "--porcelain"]) + return status if isinstance(status, Failure) else status.rstrip() def kept_as_it_was(at_main: Run, default: str) -> str | None: - """Why the main checkout must not move, or None where it may fast-forward.""" + """Why the main checkout must not move, or None where it may fast-forward to origin's default.""" branch = at_main(["git", "symbolic-ref", "--quiet", "--short", "HEAD"]) if isinstance(branch, Failure) or branch.strip() != default: return f"it has {'no branch' if isinstance(branch, Failure) else branch.strip()} checked out, not {default}" - status = at_main(["git", "status", "--porcelain"]) - if isinstance(status, Failure): - return status.reason - return f"it has uncommitted or untracked files:\n{status.rstrip()}" if status.strip() else None + files = unsaved(at_main) + if isinstance(files, Failure): + return files.reason + if files: + return f"it has uncommitted or untracked files:\n{files}" + if isinstance(at_main(["git", "merge-base", "--is-ancestor", "HEAD", f"origin/{default}"]), Failure): + return f"it holds commits origin/{default} lacks" + return None + + +def removed(chunk: Chunk, at_main: Run, left: str | None) -> str | Failure: + """Fast-forward the main checkout unless left says why not, then remove the chunk's worktree and branch. Every command runs in the main checkout, since the worktree is gone after the removal.""" + if left is None: + forwarded = at_main(["git", "merge", "--quiet", "--ff-only", f"origin/{chunk.default}"]) + if isinstance(forwarded, Failure): + return forwarded + removal = at_main(["git", "worktree", "remove", chunk.worktree]) + # Not -d: merged_chunk found the forge's pull request merged at the branch's head. -d would compare the branch with the main checkout's HEAD or its upstream instead, and after a rebase or squash merge neither need hold its commits. + deleted = removal if isinstance(removal, Failure) else at_main(["git", "branch", "--quiet", "-D", chunk.branch]) + if isinstance(deleted, Failure): + return deleted + done = f"Removed worktree {chunk.worktree} and branch {chunk.branch}" + if left is not None: + return Failure(f"{done}, but left {chunk.main} as it was: {left}") + return f"{done}, and fast-forwarded {chunk.main} to origin/{chunk.default}." diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index abb6cbb2..9b52ba48 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -7,9 +7,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from chunk_pr.main import cleaned, step from failure import Failure from test_env import isolated_env -from chunk_pr.main import step +from deploy_release.forge import Run TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr" GITHUB = "git@github.com:me/project.git" @@ -174,21 +175,31 @@ class Merge(unittest.TestCase): class Clean(unittest.TestCase): - """A real origin whose default branch is main, its clone project, and the worktree project-item-7 on item-7, one commit ahead and pushed.""" + """A real bare repository origin whose default branch is main; the clone project of it; and the worktree project-item-7 on branch item-7, one commit ahead of main and pushed. + + cleaned runs git for real, but the forge is faked: origin's URL reads as GitHub's, or Gitea's where self.url says so, and pull request #12 from item-7 is merged at self.merged_at where that is set.""" def setUp(self): folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) root = pathlib.Path(folder.name) - self.origin, self.project, self.worktree = root / "origin.git", root / "project", root / "project-item-7" + self.origin, self.project, self.worktree, self.forge_clone = root / "origin.git", root / "project", root / "project-item-7", root / "forge" self.git(root, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin)) self.git(root, "clone", "--quiet", str(self.origin), str(self.project)) self.commit(self.project, "first") self.git(self.project, "push", "--quiet", "origin", "main") self.git(self.project, "remote", "set-head", "origin", "--auto") self.git(self.project, "worktree", "add", "--quiet", "-b", "item-7", str(self.worktree), "origin/main") + (self.worktree / "chunk.txt").write_text("the chunk\n") + self.git(self.worktree, "add", "chunk.txt") self.commit(self.worktree, "the chunk") self.git(self.worktree, "push", "--quiet", "--set-upstream", "origin", "item-7") + self.head = self.git(self.worktree, "rev-parse", "HEAD") + self.before = self.git(self.project, "rev-parse", "HEAD") + self.url = GITHUB + self.merged_at: str | None = None + # The forge merges in a clone of its own, so the project's origin/main stays stale until clean fetches. + self.git(root, "clone", "--quiet", str(self.origin), str(self.forge_clone)) def git(self, folder: pathlib.Path, *args: str) -> str: return subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", *args], cwd=folder, check=True, capture_output=True, encoding="utf-8", env=isolated_env()).stdout.strip() @@ -196,68 +207,127 @@ class Clean(unittest.TestCase): def commit(self, folder: pathlib.Path, message: str): self.git(folder, "commit", "--quiet", "--allow-empty", "-m", message) - def merge_on_origin(self): - self.git(self.worktree, "push", "--quiet", "origin", "item-7:main") + def merge_commit_on_origin(self) -> str: + self.git(self.forge_clone, "fetch", "--quiet", "origin", "item-7") + self.git(self.forge_clone, "merge", "--quiet", "--no-ff", "-m", "Merge item-7", "FETCH_HEAD") + return self.publish() - def clean(self) -> subprocess.CompletedProcess: - return subprocess.run([str(TOOL), "clean"], cwd=self.worktree, capture_output=True, encoding="utf-8", env=isolated_env()) + def rebase_on_origin(self) -> str: + """Put the chunk's change on origin's main as another commit, as a rebase or a squash merge does.""" + (self.forge_clone / "chunk.txt").write_text("the chunk\n") + self.git(self.forge_clone, "add", "chunk.txt") + self.commit(self.forge_clone, "the chunk, rebased") + return self.publish() + + def publish(self) -> str: + self.git(self.forge_clone, "push", "--quiet", "origin", "main") + self.merged_at = self.head + return self.git(self.forge_clone, "rev-parse", "HEAD") + + def at(self, folder: str) -> Run: + def run(command: list[str]) -> str | Failure: + if command == ["git", "remote", "get-url", "origin"]: + return f"{self.url}\n" + if command == ["gh", "pr", "list", "--head", "item-7", "--state", "merged", *GH_LIST[5:]] and self.url == GITHUB: + return f"12\t{self.merged_at}\tfalse\n" if self.merged_at else "" + if command == ["tea", "api", "repos/{owner}/{repo}/pulls?state=closed&limit=50"] and self.url == GITEA: + return json.dumps([{"number": 12, "merged": self.merged_at is not None, "head": {"ref": "item-7", "sha": self.merged_at or self.head, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}]) + if command[0] != "git": + return Failure(f"the fake forge doesn't answer {command}") + done = subprocess.run(command, cwd=folder, capture_output=True, encoding="utf-8", env=isolated_env()) + return Failure(f"{' '.join(command[:3])}: {done.stderr.strip()}") if done.returncode else done.stdout + return run + + def clean(self, folder: pathlib.Path | None = None) -> str | Failure: + return cleaned(self.at(str(folder or self.worktree)), self.at) def branches(self) -> list[str]: - return self.git(self.project, "branch", "--format=%(refname:short)").splitlines() + return sorted(self.git(self.project, "branch", "--format=%(refname:short)").splitlines()) - def test_a_merged_chunk_loses_its_worktree_and_branch_and_the_checkout_fast_forwards(self): - self.merge_on_origin() - merged = self.git(self.worktree, "rev-parse", "HEAD") - done = self.clean() - self.assertEqual(done.returncode, 0, done.stderr) - self.assertFalse(self.worktree.exists()) + def assert_kept(self): + """Worktree, branch and main checkout are as setUp left them.""" + self.assertTrue(self.worktree.exists()) + self.assertEqual(self.branches(), ["item-7", "main"]) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), self.before) + + def test_a_chunk_merged_with_a_merge_commit_loses_its_worktree_and_branch_and_the_checkout_fast_forwards(self): + for url in (GITHUB, GITEA): + with self.subTest(url): + if url == GITEA: + self.setUp() + self.url = url + merged = self.merge_commit_on_origin() + self.assertEqual(self.clean(), f"Removed worktree {self.worktree} and branch item-7, and fast-forwarded {self.project} to origin/main.") + self.assertFalse(self.worktree.exists()) + self.assertEqual(self.branches(), ["main"]) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), merged) + + def test_a_rebased_chunk_is_cleaned_though_main_lacks_its_commit(self): + # Without an upstream, git branch -d would compare item-7 with the main checkout's HEAD, which lacks its commit. + self.git(self.project, "branch", "--unset-upstream", "item-7") + merged = self.rebase_on_origin() + self.assertEqual(self.clean(), f"Removed worktree {self.worktree} and branch item-7, and fast-forwarded {self.project} to origin/main.") self.assertEqual(self.branches(), ["main"]) self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), merged) - self.assertIn("item-7", done.stdout) def test_an_unmerged_chunk_keeps_everything(self): - done = self.clean() - self.assertEqual(done.returncode, 1) - self.assertIn("not merged", done.stderr) - self.assertTrue(self.worktree.exists()) - self.assertEqual(sorted(self.branches()), ["item-7", "main"]) + for url in (GITHUB, GITEA): + with self.subTest(url): + self.url = url + self.assertEqual(self.clean(), Failure(f"no merged pull request from item-7 at {self.head[:12]}, so its worktree and branch stay")) + self.assert_kept() - def test_a_dirty_checkout_is_left_as_it_was_and_reported(self): - self.merge_on_origin() - before = self.git(self.project, "rev-parse", "HEAD") - (self.project / "notes.txt").write_text("mine\n") - done = self.clean() - self.assertEqual(done.returncode, 1) - self.assertIn("uncommitted", done.stderr) - self.assertIn(str(self.project), done.stderr) - self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), before) - self.assertEqual((self.project / "notes.txt").read_text(), "mine\n") - self.assertFalse(self.worktree.exists()) - self.assertEqual(self.branches(), ["main"]) + def test_a_pull_request_merged_at_another_head_keeps_everything(self): + self.merge_commit_on_origin() + self.merged_at = "0" * 40 + self.assertIsInstance(self.clean(), Failure) + self.assert_kept() - def test_a_checkout_on_another_branch_is_left_as_it_was_and_reported(self): - self.merge_on_origin() - self.git(self.project, "switch", "--quiet", "-c", "elsewhere") - before = self.git(self.project, "rev-parse", "HEAD") - done = self.clean() - self.assertEqual(done.returncode, 1) - self.assertIn("elsewhere", done.stderr) - self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), before) - self.assertFalse(self.worktree.exists()) + def test_a_main_checkout_that_cannot_fast_forward_is_left_as_it_was_and_named(self): + cases = { + "dirty": ("it has uncommitted or untracked files:\n?? notes.txt", lambda: (self.project / "notes.txt").write_text("mine\n")), + "on another branch": ("it has elsewhere checked out, not main", lambda: self.git(self.project, "switch", "--quiet", "-c", "elsewhere")), + "ahead of origin": ("it holds commits origin/main lacks", lambda: self.commit(self.project, "mine")), + } + for case, (why, spoil) in cases.items(): + with self.subTest(case): + self.setUp() + self.git(self.project, "branch", "--unset-upstream", "item-7") + self.merge_commit_on_origin() + spoil() + before = self.git(self.project, "rev-parse", "HEAD") + self.assertEqual(self.clean(), Failure(f"Removed worktree {self.worktree} and branch item-7, but left {self.project} as it was: {why}")) + self.assertEqual(self.git(self.project, "rev-parse", "HEAD"), before) + self.assertFalse(self.worktree.exists()) + self.assertEqual(self.branches(), ["elsewhere", "main"] if case == "on another branch" else ["main"]) - def test_a_worktree_with_uncommitted_changes_is_kept(self): - self.merge_on_origin() + def test_a_worktree_with_uncommitted_or_untracked_files_keeps_everything(self): + self.merge_commit_on_origin() + (self.worktree / "chunk.txt").write_text("changed\n") (self.worktree / "draft.txt").write_text("unsaved\n") - done = self.clean() - self.assertEqual(done.returncode, 1) - self.assertTrue((self.worktree / "draft.txt").exists()) - self.assertIn("item-7", self.branches()) + self.assertEqual(self.clean(), Failure(f"left everything as it was: {self.worktree} has uncommitted or untracked files:\n M chunk.txt\n?? draft.txt")) + self.assert_kept() + self.assertEqual((self.worktree / "draft.txt").read_text(), "unsaved\n") + + def test_a_dirty_worktree_also_reports_a_main_checkout_it_would_have_left(self): + self.merge_commit_on_origin() + (self.worktree / "draft.txt").write_text("unsaved\n") + (self.project / "notes.txt").write_text("mine\n") + self.assertEqual(self.clean(), Failure(f"left everything as it was: {self.worktree} has uncommitted or untracked files:\n?? draft.txt\nIt would also have left {self.project} as it was: it has uncommitted or untracked files:\n?? notes.txt")) + self.assert_kept() def test_the_main_checkout_itself_is_refused(self): - done = subprocess.run([str(TOOL), "clean"], cwd=self.project, capture_output=True, encoding="utf-8", env=isolated_env()) - self.assertEqual(done.returncode, 1) - self.assertIn("worktree", done.stderr) - self.assertTrue(self.worktree.exists()) + self.merge_commit_on_origin() + self.assertEqual(self.clean(self.project), Failure(f"{self.project} is the main checkout; run clean in the chunk's worktree")) + self.assert_kept() + + def test_without_a_default_branch_on_record_it_says_how_to_set_one(self): + self.merge_commit_on_origin() + self.git(self.project, "remote", "set-head", "origin", "--delete") + cleaned_up = self.clean() + self.assertIsInstance(cleaned_up, Failure) + self.assertTrue(cleaned_up.reason.startswith("origin records no default branch; set it with `git remote set-head origin --auto`: "), cleaned_up) + self.assert_kept() class Launcher(unittest.TestCase): @@ -267,6 +337,14 @@ class Launcher(unittest.TestCase): self.assertEqual((wrong.returncode, wrong.stdout), (1, "")) self.assertIn("usage", wrong.stderr) + def test_clean_runs_in_the_folder_it_is_started_in(self): + with tempfile.TemporaryDirectory() as folder: + for args in (["init", "--quiet"], ["remote", "add", "origin", GITHUB], ["-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "--quiet", "--allow-empty", "-m", "first"]): + subprocess.run(["git", *args], cwd=folder, check=True, env=isolated_env()) + done = subprocess.run([str(TOOL), "clean"], cwd=folder, capture_output=True, encoding="utf-8", env=isolated_env()) + self.assertEqual((done.returncode, done.stdout), (1, "")) + self.assertTrue(done.stderr.startswith("chunk-pr: origin records no default branch"), done.stderr) + if __name__ == "__main__": unittest.main() diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index cb94b0f1..924c027d 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -48,18 +48,28 @@ def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure: 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.""" + return pull_at(forge, branch, head, "open", run) + + +def merged_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure: + """The number of the merged pull request from origin's own branch whose head was head; None where there is none. A rebase or a squash merge counts: the pull request keeps the head it had.""" + return pull_at(forge, branch, head, "merged", run) + + +def pull_at(forge: Forge, branch: str, head: str, state: typing.Literal["open", "merged"], run: Run) -> str | None | Failure: if forge == "gh": - listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"]) + # gh lists the open pull requests unless told another state. + listed = run(["gh", "pr", "list", "--head", branch, *(["--state", "merged"] if state == "merged" else []), "--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; the pull request sought is among the newest. - pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50") + # Gitea lists at most 50 a page; the pull request sought is among the newest. Gitea has no merged state: a merged pull request is a closed one marked merged. + pulls = gitea(run, f"repos/{{owner}}/{{repo}}/pulls?state={'open' if state == 'open' else 'closed'}&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) + 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"] and (state == "open" or pull["merged"] is True)), None) except (KeyError, TypeError): return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d0509529..c18e27e4 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -193,9 +193,9 @@ Launch prose-reviewer with what the diff touched and every section this review c 1. Read the finished PR against the README goals and code health, unless the README voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict. 2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded. -3. Aligned, every pass done and everything green → **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". -5. Run `~/.claude/bin/chunk-pr clean` in the chunk's worktree. It removes the worktree and the branch and fast-forwards the main checkout; a failure it prints, such as a dirty main checkout, goes in the summary. +3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch, commit and push that, and wait for the forge's checks (§4 step 4); the commit re-enters no pass. +4. Aligned, every pass done and everything green → **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. +5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary. 6. Stop. The next chunk gets a fresh session. ## 6. Wrap up -- 2.52.0 From 8efb1fe50fb3c5ea38bd3a27bc5a7d994d520a79 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:05:06 +0100 Subject: [PATCH 3/7] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20fixed=20in?= =?UTF-8?q?=20the=20product-owner=20answer:=20refusals=20checked=20before?= =?UTF-8?q?=20acting,=20both=20dirt=20reasons=20reported,=20clean=20split?= =?UTF-8?q?=20up,=20tests=20merge=20from=20a=20separate=20clone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 7a93e58f70c461852d11e8cffd582ac222e0c9b5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:05:06 +0100 Subject: [PATCH 4/7] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20fixed=20in?= =?UTF-8?q?=20the=20product-owner=20answer:=20help=20states=20the=20order?= =?UTF-8?q?=20and=20the=20refusals,=20false=20not-merged=20claim=20gone,?= =?UTF-8?q?=20todo=20removal=20before=20the=20merge,=20changelog=20bullet?= =?UTF-8?q?=20rewritten?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 67c7c979a032bbc64b77488cac2ee607965fca2e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:07:08 +0100 Subject: [PATCH 5/7] =?UTF-8?q?Answer=20architecture=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20name=20merg?= =?UTF-8?q?ed=5Fpull=20and=20pull=5Fat=20in=20item=20287?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- todo.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/todo.md b/todo.md index 03461b56..030833ee 100644 --- a/todo.md +++ b/todo.md @@ -16,7 +16,7 @@ | 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 | | 290 | 0.7.0 | | defect | **Have `rule-hook overrides` read the branch's reflog when a file or folder shares the branch's name.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 | | 286 | 0.7.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 4 | 1.0 | -| 287 | 0.8.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 | +| 287 | 0.8.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 | | 284 | 0.8.0 | | owner | **Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 | | 288 | 0.8.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 | | 77 | 0.8.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 | @@ -81,7 +81,7 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go Item 285 removed the `todo.md` reads for a joining item's detail; the rest are for edits. Find why a worker opens each of them before its first commit, and cut that cause, such as a test file too large to read in parts. -### 287. Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them. +### 287. Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them. Today the helpers live in two tools. `Forge` is defined in `bin/chunk_preflight/gathered.py` and imported by `bin/chunk_preflight/choices.py`, `bin/chunk_preflight/facts.py`, `bin/chunk_preflight/main.py` and `bin/chunk_pr/main.py`, and again through `choices` by `bin/deploy_release/forge.py`. `forge_of` lives in `choices.py`, which `bin/chunk_pr/main.py`, `bin/deploy_release/cut.py` and `bin/larv_review/reviewer_header.py` import. `open_pull`, `runner` and `gitea` live in `bin/deploy_release/forge.py`, which `bin/chunk_pr/main.py` and `bin/larv_review/reviewer_header.py` import. So `deploy_release` imports `chunk_preflight`, and `chunk_pr` and `larv_review` import both. -- 2.52.0 From 23b7848be6adea68ce96ece7c615bb9bf6737add Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:13:26 +0100 Subject: [PATCH 6/7] =?UTF-8?q?Answer=20stability=20round=202:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20match=20Git?= =?UTF-8?q?ea=20pull=20requests=20by=20head=20label,=20which=20survives=20?= =?UTF-8?q?origin=20deleting=20a=20merged=20branch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_pr/test_chunk_pr.py | 4 ++-- bin/deploy_release/forge.py | 3 ++- bin/deploy_release/test_deploy_release.py | 2 +- bin/larv_review/test_larv_review.py | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index 9b52ba48..6efed6e0 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -51,7 +51,7 @@ class Checkout: if command == GH_LIST: return f"12\t{HEAD}\tfalse\n" if self.open else "" if command == TEA_LIST: - return json.dumps([{"number": 12, "head": {"ref": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else []) + return json.dumps([{"number": 12, "head": {"ref": "item-7", "label": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else []) if command in (GH_SETTINGS, TEA_SETTINGS): return json.dumps({setting: True for setting in self.allowed}) return "" @@ -231,7 +231,7 @@ class Clean(unittest.TestCase): if command == ["gh", "pr", "list", "--head", "item-7", "--state", "merged", *GH_LIST[5:]] and self.url == GITHUB: return f"12\t{self.merged_at}\tfalse\n" if self.merged_at else "" if command == ["tea", "api", "repos/{owner}/{repo}/pulls?state=closed&limit=50"] and self.url == GITEA: - return json.dumps([{"number": 12, "merged": self.merged_at is not None, "head": {"ref": "item-7", "sha": self.merged_at or self.head, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}]) + return json.dumps([{"number": 12, "merged": self.merged_at is not None, "head": {"ref": "refs/pull/12/head" if self.merged_at else "item-7", "label": "item-7", "sha": self.merged_at or self.head, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}]) if command[0] != "git": return Failure(f"the fake forge doesn't answer {command}") done = subprocess.run(command, cwd=folder, capture_output=True, encoding="utf-8", env=isolated_env()) diff --git a/bin/deploy_release/forge.py b/bin/deploy_release/forge.py index 924c027d..7aa44caa 100644 --- a/bin/deploy_release/forge.py +++ b/bin/deploy_release/forge.py @@ -69,7 +69,8 @@ def pull_at(forge: Forge, branch: str, head: str, state: typing.Literal["open", 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"] and (state == "open" or pull["merged"] is True)), None) + # Match the label, not the ref: once origin deletes a merged branch, Gitea reports its ref as refs/pull/<N>/head. + return next((str(pull["number"]) for pull in pulls if pull["head"]["label"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and (state == "open" or pull["merged"] is True)), None) except (KeyError, TypeError): return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index 008bd0f2..4c12e95c 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -177,7 +177,7 @@ 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": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened])) + print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "label": 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]: diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 26709d66..f7a8a488 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -736,7 +736,7 @@ class LarvReviewTool(unittest.TestCase): def fake_tea(self, number, head): """Puts a tea on PATH whose API lists one open pull request, number, from origin's chunk at head.""" - pull = f'{{"number": {number}, "head": {{"ref": "chunk", "sha": "{head}", "repo": {{"full_name": "a/b"}}}}, "base": {{"repo": {{"full_name": "a/b"}}}}}}' + pull = f'{{"number": {number}, "head": {{"ref": "chunk", "label": "chunk", "sha": "{head}", "repo": {{"full_name": "a/b"}}}}, "base": {{"repo": {{"full_name": "a/b"}}}}}}' self.fake_tea_script(f"echo '[{pull}]'") def fake_tea_script(self, body): -- 2.52.0 From cda45a931c7127910e664d241987ccae28d497cc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Tue, 10 Nov 2026 11:13:26 +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);=20clean?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0