From 06a1398196f53667ec48fde6e83e63594aac7660 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 21:38:20 +0100 Subject: [PATCH 01/14] Re-score item 457: scores hold, Touches names the shared pick and the forge --- todo.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/todo.md b/todo.md index b00f61c3..aaea4d2e 100644 --- a/todo.md +++ b/todo.md @@ -178,12 +178,25 @@ Under `merge = "human"`, `chunk-pr merge` leaves a chunk's pull request ready, w Touches: +- `bin/forge/commands.py` +- `bin/forge/pulls.py` +- `bin/forge/test_forge.py` +- `bin/release_plan/release_standing.py`: `chunk_item`, `picked`, `pick_from` +- `bin/release_plan/next_chunk.py`: `planned`, `NoItem` (small) +- `bin/release_plan/test_release_standing.py` - `bin/chunk_preflight/main.py` -- `bin/chunk_preflight/facts.py`: `item_lines`, `pulls_text` +- `bin/chunk_preflight/gathered.py`: `Gathered`, `ItemFacts` (small) +- `bin/chunk_preflight/facts.py`: `render`, `item_lines`, `pulls_text` +- `bin/chunk_preflight/choices.py` - `bin/chunk_preflight/test_chunk_preflight.py` +- `bin/loop_claude/routed_item.py`: `routed_item` +- `bin/loop_claude/loop/chunk_start.py`: `plan_item` +- `bin/loop_claude/test_routed_item.py` +- `bin/loop_claude/loop/test_chunk_start.py` +- `bin/deploy_release/cut.py`: `ready_release` (small) - `bin/chunk_pr/main.py`: `levelled_and_finished`, `finished` (small) - `bin/chunk_pr/test_chunk_pr.py` -- `README.md`: `### Set up a project` (small) +- `README.md`: `### Set up a project` (small), `## Tools` (small) ### 450. Add `do-epic --dry-run`, which prints every Jira write planning would make and each chunk that would start, and makes none of them. -- 2.52.0 From 00975177ad13faef5e42982755b3995e82dd5d65 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 21:54:43 +0100 Subject: [PATCH 02/14] Pass over an item whose pull request awaits a person's merge, and hold a sentence about several named things to each --- README.md | 2 +- bin/chunk_pr/main.py | 1 + bin/chunk_preflight/choices.py | 12 +++-- bin/chunk_preflight/facts.py | 12 ++++- bin/chunk_preflight/gathered.py | 12 +++++ bin/chunk_preflight/main.py | 36 +++++++++++-- bin/chunk_preflight/test_chunk_preflight.py | 40 ++++++++++++++- bin/forge/pulls.py | 31 +++++++++++ bin/forge/test_forge.py | 27 +++++++++- bin/judge_replay/test_judge_replay.py | 4 +- bin/loop_claude/loop/chunk_start.py | 2 +- bin/loop_claude/loop/chunk_windows.py | 2 +- bin/loop_claude/loop/test_chunk_start.py | 19 +++++++ bin/loop_effects/doubles.py | 5 +- bin/loop_effects/effects.py | 4 ++ bin/plan/todo_table.py | 6 ++- bin/release_plan/awaiting_merge.py | 30 +++++++++++ bin/release_plan/next_chunk.py | 15 +++++- bin/release_plan/release_standing.py | 19 +++++-- bin/release_plan/test_release_standing.py | 57 +++++++++++++++++++++ bin/review_replay/test_review_replay.py | 2 +- skills/larv-review/standards/prose.md | 1 + 22 files changed, 312 insertions(+), 27 deletions(-) create mode 100644 bin/release_plan/awaiting_merge.py diff --git a/README.md b/README.md index 0cafcbbf..dec76e07 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ A legacy project with no container setup sets `tooling-on-host = true`, so the l A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. While it waits, other chunks merge. It stops where a reviewer's comment waits for an answer, on an approved pull request too; answer it and run it again. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false. -A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. Left out, the setting is `"chunk"`: the chunk merges. +A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. loop-claude starts no chunk from an item such a pull request finishes. Once every item left in the release waits and one waits for a merge, the loop stops and names the pull requests to merge. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged one left. Nobody works on a pull request that awaits your merge: to have a reviewer's comment answered, turn it back into a draft, and a chunk takes its item up again. Left out, the setting is `"chunk"`: the chunk merges. For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 7ba95125..7a6f736f 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -476,6 +476,7 @@ def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> if isinstance(finishing, Failure): return finishing title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan") + # Under `merge = "human"` a plan or changelog outside the checkout is finished here, before the person merges, since no run follows that merge; where they close the pull request unmerged, they file the item again. # A plan in Jira, or a changelog on a Confluence page, is no file to commit. records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()] return committed(run, title, records) diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index c3468b8a..fd6e316d 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -9,11 +9,13 @@ PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ( def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: """The worktree on branch, in what `git worktree list --porcelain` printed; None where none is.""" - for block in porcelain.split("\n\n"): - fields = dict(line.partition(" ")[::2] for line in block.splitlines()) - if fields.get("branch") == f"refs/heads/{branch}": - return pathlib.Path(fields["worktree"]) - return None + return next((path for path, on, _ in worktrees(porcelain) if on == branch), None) + + +def worktrees(porcelain: str) -> list[tuple[pathlib.Path, str, str]]: + """Each worktree on a branch, in what `git worktree list --porcelain` printed: its path, its branch and its head commit.""" + blocks = [dict(line.partition(" ")[::2] for line in block.splitlines()) for block in porcelain.split("\n\n")] + return [(pathlib.Path(fields["worktree"]), fields["branch"].removeprefix("refs/heads/"), fields.get("HEAD", "")) for fields in blocks if fields.get("branch", "").startswith("refs/heads/")] def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]: diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index f99ea8cf..d95fca2c 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -19,7 +19,7 @@ def render(found: Gathered) -> list[str]: """One `- ` line per fact, then the item's tagline and detail, the detail of each item that may join its chunk, and what each tool printed.""" note = [f"- {found.note}"] if found.note else [] unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else [] - head = [*note, f"- {last_release(found.default, found.cut)}", *unseen] + head = [*note, f"- {last_release(found.default, found.cut)}", *unseen, *merge_lines(found)] paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}." texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}." if isinstance(found.item, NoItem): @@ -28,6 +28,16 @@ def render(found: Gathered) -> list[str]: return [*head, *lines[:2], paths, texts, *lines[2:]] +def merge_lines(found: Gathered) -> list[str]: + """What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, and why those could not be read.""" + left = [f"- The worktree {worktree.path}, on the branch {worktree.branch}, is left from pull request #{worktree.pull}, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step." for worktree in found.left] + items = found.item.plan.items if isinstance(found.item, ItemFacts) else [] + passed = [f"item {item.id}, by pull request {item.awaits_merge}" for item in items if item.awaits_merge] + over = [f"- Passed over, since each is finished on a branch whose pull request is ready and awaits a person's merge: {'; '.join(passed)}. No chunk takes one."] if passed else [] + unread = [f"- The pull requests that await a person's merge cannot be read, so no item is passed over for one: {found.merges_unread.reason}"] if found.merges_unread else [] + return [*left, *over, *unread] + + def last_release(default: str, release: LastCut) -> str: if isinstance(release.tag, Failure): return f"Last version cut: cannot be read: {release.tag.reason}" diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index ba81bdbe..b6008c01 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -44,6 +44,14 @@ class ItemFacts: tools: list[tuple[str, Ran | Failure]] +@dataclasses.dataclass(frozen=True) +class LeftWorktree: + """A worktree on a branch whose pull request, of this number, has merged.""" + path: pathlib.Path + branch: str + pull: str + + @dataclasses.dataclass(frozen=True) class Gathered: """Everything the preflight read and ran, for facts.render to state.""" @@ -62,3 +70,7 @@ class Gathered: plan_outside: bool # The language and the templates the project's config names, by their settings. texts: dict[str, str] + # Why the pull requests that await a person's merge could not be read; None where they were read, or the chunk merges its own. + merges_unread: Failure | None = None + # Each other worktree whose pull request a person has merged, which `chunk-pr clean` is still to remove. + left: tuple[LeftWorktree, ...] = () diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index daeb8a96..e38bf979 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -16,6 +16,11 @@ and prints that the release reviews and the cuts are the human's to call. It pri newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count. Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how many commits followed the cut: the tag, or the commit that added that heading; +- under `merge = "human"` (`project-config --help`), each other worktree whose pull request has + merged, for the worker to run `chunk-pr clean` in, and each item passed over: one that an open + pull request, no draft, finished on its branch, where the checkout holds the plan. Such an item + waits until a person merges. Where every item left in the release waits and one awaits a merge, + it names those pull requests and says the working loop stops there; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I; with --item , the plan item of that ID instead, which loop-claude names in a window named for an item. An item waits while it is marked question, or while an item still in todo.md @@ -78,14 +83,15 @@ import typing from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from failure import Failure -from forge.commands import Forge, forge_of -from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree +from forge.commands import Forge, forge_of, Run +from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree from chunk_preflight.facts import JOINING_DETAILS, render from project_config.main import located +from forge.pulls import merged_pull from plan.named_paths import named_paths from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned from release_plan.release_standing import project_plan -from chunk_preflight.choices import pulls_command, worktree_add, worktree_on +from chunk_preflight.choices import pulls_command, worktree_add, worktree_on, worktrees BIN = pathlib.Path(__file__).resolve().parents[1] # Each tool run in the item's worktree, {item} standing for the item's ID. @@ -143,12 +149,13 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non if isinstance(config, Failure): return config outside = None if config.tracked("plan") else config.plan_label - held = project_plan(config, ref, str(root)) + forge_run = forge_runner(root, timeout) + held = project_plan(config, ref, str(root), forge_run=forge_run) plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) # A `checkout:` path lands in the worktree the chunk works in. made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config - return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts)) + return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, held.merges_unread, left_worktrees(root, forge_run) if config.merge == "human" else ())) def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts: @@ -173,6 +180,25 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | F return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how) +def left_worktrees(root: pathlib.Path, forge_run: Run) -> tuple[LeftWorktree, ...]: + """Each worktree beside the checkout whose branch's pull request has merged at the worktree's head: under `merge = "human"` a person merges after the chunk's run has ended, so its worker never ran `chunk-pr clean`. A worktree whose forge can't be asked counts as not left.""" + listing, url = git("worktree", "list", "--porcelain"), git("remote", "get-url", "origin") + if isinstance(listing, Failure) or isinstance(url, Failure): + return () + merged = [(path, branch, merged_pull(forge_of(url), branch, head, forge_run)) for path, branch, head in worktrees(listing) if path != root] + return tuple(LeftWorktree(path, branch, pull) for path, branch, pull in merged if isinstance(pull, str)) + + +def forge_runner(root: pathlib.Path, timeout: float) -> Run: + """Runs the forge's CLI at root, stopped after timeout seconds: what it printed, or a Failure with why it failed.""" + def run(command: list[str]) -> str | Failure: + done = ran(command, root, timeout) + if isinstance(done, Failure): + return Failure(f"`{' '.join(command[:3])}` {done.reason}") + return Failure(f"`{' '.join(command[:3])}` exited {done.code}: {done.stderr.strip()}") if done.code else done.stdout + return run + + def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None: url = git("remote", "get-url", "origin") if isinstance(url, Failure): diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 137aa08f..0c03d951 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -12,10 +12,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.templates import BRANCH from release_plan.next_chunk import CarriedOver, NoItem from failure import Failure -from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree +from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree from test_env import isolated_env from release_plan.release_standing import LastCut, UNSEEN_RELEASES from chunk_preflight.main import line_count, ran, seconds, TIMEOUT +from release_plan.awaiting_merge import marked from release_plan import next_chunk from chunk_preflight.facts import open_pulls, render from plan_store.todo_md import plan_of @@ -135,6 +136,34 @@ class Repo: class ChunkPreflightTool(unittest.TestCase): + def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_and_names_a_worktree_a_merged_one_left(self): + repo = Repo(self, origin="github.com/o/r.git") + config = repo.temp / "home" / ".claude-projects" / "proj" / "config.toml" + config.write_text(config.read_text() + 'merge = "human"\n') + repo.git(repo.root, "worktree", "add", "--quiet", "-b", "item-3", str(repo.temp / "proj-item-3"), "main") + repo.write(repo.temp / "proj-item-3", "todo.md", TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "")) + repo.commit(repo.temp / "proj-item-3", "Finish item 3 in the plan") + ready = repo.git(repo.temp / "proj-item-3", "rev-parse", "HEAD").strip() + repo.git(repo.root, "worktree", "add", "--quiet", "-b", "item-2", str(repo.temp / "proj-item-2"), "main") + left = repo.git(repo.temp / "proj-item-2", "rev-parse", "HEAD").strip() + (repo.fake / "gh").write_text(f"""#!{sys.executable} +import sys +args = sys.argv[1:] +if args[:4] == ["pr", "list", "--limit", "100"]: + print("12\\thttps://github.com/o/r/pull/12\\t{ready}\\tfalse\\tfalse") +elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: + print("11\\t{left}\\tfalse") +""") + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn(f"- The worktree {repo.temp}/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.\n", done.stdout) + self.assertNotIn("proj-item-3, on the branch", done.stdout, "an open pull request leaves no worktree to clean") + self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, a person's merge is awaited of pull request #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here until one is merged.", done.stdout) + (repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n") + unread = repo.preflight() + self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: not logged in\n", unread.stdout) + self.assertIn("Its first item that does not wait: item 3,", unread.stdout) + def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self): repo = Repo(self) folder = repo.temp / "home" / ".claude-projects" / "proj" @@ -408,6 +437,15 @@ def rendered(item, release=CUT, note=None): class Render(unittest.TestCase): + def test_states_what_a_persons_merge_leaves_only_where_there_is_something(self): + self.assertNotIn("merge", rendered(item_facts())) + found = gathered(NoItem("the plan holds none.")) + left = dataclasses.replace(found, left=(LeftWorktree(pathlib.Path("/c/proj-item-2"), "item-2", "11"),), merges_unread=Failure("`gh pr list` exited 1: no")) + passed = "\n".join(render(gathered(item_facts(marked(plan_of(TODO), {7: "#12 https://github.com/o/r/pull/12"}))))) + self.assertIn("\n- Passed over, since each is finished on a branch whose pull request is ready and awaits a person's merge: item 7, by pull request #12 https://github.com/o/r/pull/12. No chunk takes one.\n", passed) + self.assertIn("- No other item of release 0.2.0 may join item 3's chunk.", passed) + self.assertEqual(render(left)[1:3], ["- The worktree /c/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.", "- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: no"]) + def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self): said = rendered(item_facts()) self.assertIn("origin/main's todo.md: 0.2.0", said) diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 42b1bd31..7655748c 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -2,10 +2,12 @@ import dataclasses import fnmatch import json +import re import typing from failure import Failure from forge.commands import Forge, gitea, Run +from forge.reviews import GITEA_DRAFT # How long checks_passed waits between two reads: of the head commit's status on Gitea, or of gh's watch while it reports no checks. POLL_SECONDS = 10 @@ -44,6 +46,35 @@ def pull_at(forge: Forge, branch: str, head: str, state: typing.Literal["open", return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") +@dataclasses.dataclass(frozen=True) +class ReadyPull: + """An open pull request from one of origin's own branches that is no draft.""" + number: str + url: str + # The commit ID of its head. + head: str + + +def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: + """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row whose number or head is no number or commit ID is left out, since callers pass them to git.""" + if forge == "gh": + # 100 is the most GitHub's API lists a page; gh lists 30 unless told. + listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]) + if isinstance(listed, Failure): + return listed + rows = [line.split("\t") for line in listed.splitlines()] + found = [ReadyPull(*row[:3]) for row in rows if row[3:] == ["false", "false"]] + else: + pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50") + if isinstance(pulls, Failure): + return pulls + try: + found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)] + except (AttributeError, KeyError, TypeError): + return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") + return [pull for pull in found if pull.number.isascii() and pull.number.isdigit() and isinstance(pull.head, str) and re.fullmatch(r"[0-9a-f]{40,64}", pull.head)] + + def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure: """The checks, or glob patterns of checks, that the forge's protection of the branch base requires before a merge. None on GitHub, where gh's watch covers them. diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index da917564..6002ad95 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -1,4 +1,5 @@ import itertools +import json import pathlib import sys import typing @@ -6,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, required_checks, WAIT_SECONDS +from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, ready_pulls, ReadyPull, required_checks, WAIT_SECONDS from failure import Failure from forge.commands import forge_of, gitea, url_beside @@ -138,3 +139,27 @@ class ChecksPassed(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +SHA = "a" * 40 +GITEA_PULL = {"number": 7, "html_url": "https://gitea.example/o/r/pulls/7", "title": "Do 7", "head": {"sha": SHA, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}} + + +class ReadyPulls(unittest.TestCase): + def test_lists_on_gh_each_open_pull_request_from_origins_own_branches_that_is_no_draft(self): + commands: list[list[str]] = [] + listed = f"7\thttps://github.com/o/r/pull/7\t{SHA}\tfalse\tfalse\n8\thttps://github.com/o/r/pull/8\t{SHA}\ttrue\tfalse\n9\thttps://github.com/o/r/pull/9\t{SHA}\tfalse\ttrue\n" + self.assertEqual(ready_pulls("gh", lambda command: commands.append(command) or listed), [ReadyPull("7", "https://github.com/o/r/pull/7", SHA)]) + self.assertEqual(commands[0][:5], ["gh", "pr", "list", "--limit", "100"]) + + def test_leaves_out_on_gh_a_row_whose_head_is_no_commit_id(self): + self.assertEqual(ready_pulls("gh", lambda command: "7\thttps://github.com/o/r/pull/7\t--upload-pack=x\tfalse\tfalse\n"), []) + + def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self): + fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}} + draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"} + self.assertEqual(ready_pulls("tea", lambda command: json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) + + def test_fails_where_the_forge_cannot_list_them(self): + self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network") + self.assertEqual(ready_pulls("tea", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}") diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 90a26fc4..04a1a11d 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -145,7 +145,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) @@ -387,7 +387,7 @@ class JudgeArchivedRuns(unittest.TestCase): cwds.append(cwd) return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) grounds = grounds_of(prompt, self.ENTRIES) return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, LOOP_CLAUDE, effects)), cwds diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index e99fdf49..d2aff2bc 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -49,7 +49,7 @@ def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure: if announce and config.tracked("plan") is None: say(UNSEEN_RELEASES, loop.effects) ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git) - return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git) + return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git, loop.effects.forge(loop.root)) def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None: diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 8531209e..b9f9be65 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -104,7 +104,7 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | No ref = default_ref(root, FETCH_TIMEOUT, run=effects.git) if isinstance(ref, Failure): return ref - held = project_plan(config, ref, root, effects.git) + held = project_plan(config, ref, root, effects.git, effects.forge(root)) return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label) diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index ea8ffbef..65f7ea75 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -79,6 +79,25 @@ class RouteSources(unittest.TestCase): held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1]))) self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n") + def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_as_the_loops_forge_lists_them(self): + head = "a" * 40 + finished = TODO.replace("| 3 | 0.2.0 | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n", "") + + def git(*args, **options): + if args[:2] == ("remote", "get-url"): + return "https://github.com/o/r\n" + answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "merge-base": "base\n", "show": finished if args[-1] == f"{head}:todo.md" else TODO} + return answers.get(args[0], "1\n") + + with tempfile.TemporaryDirectory() as root: + folder = configured(self, pathlib.Path(root)) + (folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n') + fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"]) + held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1]))) + self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")]) + self.assertEqual(fake.made("forge")[0][:3], ["gh", "pr", "list"]) + self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk") + def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): with tempfile.TemporaryDirectory() as root: folder = configured(self, pathlib.Path(root)) diff --git a/bin/loop_effects/doubles.py b/bin/loop_effects/doubles.py index 1fd91b7a..7226ac89 100644 --- a/bin/loop_effects/doubles.py +++ b/bin/loop_effects/doubles.py @@ -29,7 +29,7 @@ def human(content: typing.Any) -> dict[str, typing.Any]: class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude: typing.Iterable[typing.Any] = (), on_terminal_claude: typing.Iterable[typing.Any] = (), git: typing.Iterable[typing.Any] = (), inputs: typing.Iterable[typing.Any] = (), python: typing.Iterable[typing.Any] = (), streams: typing.Iterable[typing.Any] = (), on_terminal: bool = True, free_memory: typing.Iterable[memory.Memory | None] = (), dm_failures: typing.Iterable[Failure | None] = (), tmux_version: str = "tmux 3.2", windows: str | None = None, owner: str = "/r") -> None: + def __init__(self, claude: typing.Iterable[typing.Any] = (), on_terminal_claude: typing.Iterable[typing.Any] = (), git: typing.Iterable[typing.Any] = (), forge: typing.Iterable[typing.Any] = (), inputs: typing.Iterable[typing.Any] = (), python: typing.Iterable[typing.Any] = (), streams: typing.Iterable[typing.Any] = (), on_terminal: bool = True, free_memory: typing.Iterable[memory.Memory | None] = (), dm_failures: typing.Iterable[Failure | None] = (), tmux_version: str = "tmux 3.2", windows: str | None = None, owner: str = "/r") -> None: self.calls: list[tuple[str, typing.Any]] = [] # Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session. self.tmux_calls: list[list[str]] = [] @@ -42,7 +42,7 @@ class FakeEffects: # The directory each DM named, in the order of self.dms; None where it named none. self.dm_directories: list[str | None] = [] self.dm_failures = list(dm_failures) - self.scripts: dict[str, list[typing.Any]] = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} + self.scripts: dict[str, list[typing.Any]] = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "forge": list(forge), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} # Without a script, every read finds all memory available. self.free_memory = list(free_memory) self.terminal = on_terminal @@ -62,6 +62,7 @@ class FakeEffects: discard_typed=lambda: self.calls.append(("discard_typed", None)), dm=self.dm, execv=self.execv, + forge=lambda cwd: lambda command: self.answer("forge", command), git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), local_time=lambda seconds: f"<{seconds}>", diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index d7d011f8..d0d9481d 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -21,6 +21,7 @@ from git_cli import git_repo from machine_load.memory import Memory, read_memory from project_config.settings import Notifier from text_files.file_writes import replace_file +from forge.commands import Run, runner from machine_load.slots import slot_folder # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. @@ -54,6 +55,8 @@ class Effects: # Sends the human a direct message through the notifier the project's config names, as `notify` does, for the project whose checkout holds the given directory, else the current directory; a Failure where it could not. dm: typing.Callable[[str, str | None], Failure | None] execv: typing.Callable[[str, list[str]], None] + # Runs the CLI of a checkout's forge in that checkout, as forge.commands.runner does. + forge: typing.Callable[[str], Run] git: git_repo.Git input: typing.Callable[[str], str] # A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock. @@ -120,6 +123,7 @@ def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), dm=lambda text, directory: notify(text, directory, home, backends), execv=os.execv, + forge=runner, git=git_repo.git, input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)), diff --git a/bin/plan/todo_table.py b/bin/plan/todo_table.py index f6df5018..6bc7605b 100644 --- a/bin/plan/todo_table.py +++ b/bin/plan/todo_table.py @@ -107,6 +107,8 @@ class Item: blocked_by: tuple[int, ...] # Empty where the item has none, and where a reader took only the table. detail: str = "" + # The pull request, as `# `, whose merge by a person the item awaits, finished on that branch only; empty where it awaits none, and where the reader asked no forge. release_plan.awaiting_merge sets it. + awaits_merge: str = "" @property def likelihood(self) -> int: @@ -181,9 +183,9 @@ def items_table(lines: list[str]) -> Table | None | Failure: def waiting(found: list[Item], done: set[int]) -> set[int]: - """The IDs of the items that wait: each marked question, or blocked by an item the table still holds and done does not name. Row order does not change the result.""" + """The IDs of the items that wait: each marked question, each that awaits a person's merge of its pull request, and each blocked by an item the table still holds and done does not name. Row order does not change the result.""" held = {item.id for item in found} - done - return {item.id for item in found if item.exempt == "question" or held.intersection(item.blocked_by)} + return {item.id for item in found if item.exempt == "question" or item.awaits_merge or held.intersection(item.blocked_by)} def next_item(found: list[Item]) -> Item | None: diff --git a/bin/release_plan/awaiting_merge.py b/bin/release_plan/awaiting_merge.py new file mode 100644 index 00000000..7f6c92ea --- /dev/null +++ b/bin/release_plan/awaiting_merge.py @@ -0,0 +1,30 @@ +"""The plan items whose chunk left its pull request ready for a person's merge, under `merge = "human"`. The chunk finished them on its branch only, so the default branch's plan holds each until that merge, and no chunk may start from one.""" +import dataclasses + +from failure import Failure +from forge.commands import Forge, Run +from forge.pulls import ready_pulls +from git_cli.git_repo import Git, git +from plan_store import stores +from plan_store.plans import Plan, PlanStore + + +def awaiting(ref: str, plan: PlanStore, root: str, forge: Forge, forge_run: Run, run: Git = git) -> dict[int, str] | Failure: + """Each plan item, by ID, that awaits a person's merge, with its pull request as `# `: an item the plan held where the pull request's branch left ref, the default branch, and no longer holds at its head. A pull request whose head the checkout hasn't fetched, or whose plan can't be read, names none.""" + pulls = ready_pulls(forge, forge_run) + if isinstance(pulls, Failure): + return pulls + found: dict[int, str] = {} + for pull in pulls: + base = run("merge-base", ref, pull.head, cwd=root) + if isinstance(base, Failure): + continue + before, after = stores.held_at(base.strip(), plan, root, run), stores.held_at(pull.head, plan, root, run) + if isinstance(before, Plan) and isinstance(after, Plan): + found.update(dict.fromkeys({item.id for item in before.items} - {item.id for item in after.items}, f"#{pull.number} {pull.url}")) + return found + + +def marked(plan: Plan, awaited: dict[int, str]) -> Plan: + """plan with each item awaited names marked as awaiting its pull request's merge, so it waits.""" + return dataclasses.replace(plan, items=[dataclasses.replace(item, awaits_merge=awaited.get(item.id, "")) for item in plan.items]) diff --git a/bin/release_plan/next_chunk.py b/bin/release_plan/next_chunk.py index c881e128..e9c7deb9 100644 --- a/bin/release_plan/next_chunk.py +++ b/bin/release_plan/next_chunk.py @@ -4,6 +4,7 @@ import dataclasses from release_plan.release_standing import Cut, dated_cut, LastCut, picked, ReadyToCut, ReviewDue, standing_of, Unknown, Unplanned from failure import Failure from plan.todo_table import Item, NoItemsTable +from text_files.markdown_text import listed from plan_store.plans import Plan from plan.release import Release, version from project_config import templates @@ -81,7 +82,7 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.") first = pick.item if first is None: - return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.") + return NoItem(f"every item of release {version(pick.release)} in {where} waits.{awaited_merges(weighed.carried, pick.release)}" if pick.release is not None else f"{where}'s items table holds no item.") held = weighed.carried # Every carried item takes one release, the next. over = CarriedOver(next(item.release for item in held if item.id == weighed.moved[0]), weighed.moved) if weighed.moved else None @@ -90,3 +91,15 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi if first is None: return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.") return NextChunk(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None) + + +def awaited_merges(found: list[Item], release: Release) -> str: + """The sentences that stop the working loop where items of release await a person's merge, naming each pull request with the items it finishes; empty where none does.""" + pulls: dict[str, list[str]] = {} + for item in found: + if item.release == release and item.awaits_merge: + pulls.setdefault(item.awaits_merge, []).append(str(item.id)) + if not pulls: + return "" + named = listed([f"{pull}, which finishes item{'s' if len(ids) > 1 else ''} {listed(ids, 'and')}" for pull, ids in pulls.items()], "and") + return f" Under `merge = \"human\"`, a person's merge is awaited of pull request {named}. The working loop stops here until one is merged." diff --git a/bin/release_plan/release_standing.py b/bin/release_plan/release_standing.py index 2f3d60f7..89bbfce5 100644 --- a/bin/release_plan/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -1,9 +1,11 @@ """How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick.""" import dataclasses +from release_plan.awaiting_merge import awaiting, marked from git_cli.git_repo import commits_since, file_at, git, Git from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE from failure import Failure +from forge.commands import forge_of, Run from plan.todo_table import Item, items, next_item, renames from plan_store.plans import Plan from plan_store import stores as plan_stores, plans @@ -95,11 +97,22 @@ class DefaultPlan: # The plan, a NoItemsTable where the branch holds none. plan: Plan | Failure cut: LastCut + # Why the pull requests that await a person's merge could not be read, so the plan passes over none of their items; None where they were read or not asked for. + merges_unread: Failure | None = None -def project_plan(config: ProjectConfig, ref: str, root: str, run: Git = git) -> DefaultPlan: - """default_plan for the project config describes: its plan, its changelog and its title templates.""" - return default_plan(root, ref, plan_stores.store(config), stores.store(config, "changelog"), config.titles, run) +def project_plan(config: ProjectConfig, ref: str, root: str, run: Git = git, forge_run: Run | None = None) -> DefaultPlan: + """default_plan for the project config describes: its plan, its changelog and its title templates. With forge_run, which runs the forge's CLI in the checkout, and under `merge = "human"`, the plan's items that await a person's merge are marked so, as awaiting_merge says, and so wait.""" + plan = plan_stores.store(config) + held = default_plan(root, ref, plan, stores.store(config, "changelog"), config.titles, run) + # A plan no commit holds is finished at once (chunk-pr merge --finish), so none of its items awaits a merge. + if forge_run is None or config.merge != "human" or plan.tracked is None or not isinstance(held.plan, Plan): + return held + origin = run("remote", "get-url", "origin", cwd=root) + awaited = origin if isinstance(origin, Failure) else awaiting(ref, plan, root, forge_of(origin), forge_run, run) + if isinstance(awaited, Failure): + return dataclasses.replace(held, merges_unread=awaited) + return dataclasses.replace(held, plan=marked(held.plan, awaited)) def default_plan(root: str, ref: str, plan: plans.PlanStore, changelog: stores.RecordStore, titles: templates.Titles, run: Git = git) -> DefaultPlan: diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 82b6ae99..78ed47b2 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -7,6 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from release_plan import awaiting_merge from project_config.templates import BARE, Titles from project_config.settings import DEFAULT_FLOOR, ProjectConfig, SETTINGS from failure import Failure @@ -393,3 +394,59 @@ class NextChunk(unittest.TestCase): planned = next_chunk.planned(Plan([later, carried, next_one]), release_standing.LastCut("v0.2.0", "", 4, []), "origin/main", "item-{id}") assert isinstance(planned, next_chunk.NextChunk), planned self.assertEqual(planned.carried, next_chunk.CarriedOver((0, 3, 0), (5,))) + + +class AwaitingMerge(unittest.TestCase): + """A repo whose branch item-1 finished item 1 of three, and whose default branch has since filed item 4.""" + + def setUp(self): + self.repo = tempfile.mkdtemp() + self.addCleanup(subprocess.run, ["rm", "-rf", self.repo]) + run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout.strip() + rows = lambda *ids: HEADER + "".join(ROW.format(id=id_, release="0.1.0") for id_ in ids) + run("init", "-q", "-b", "main") + run("remote", "add", "origin", "https://github.com/o/r") + pathlib.Path(self.repo, "todo.md").write_text(rows(1, 2, 3)) + run("add", "todo.md") + run("commit", "-q", "-m", "Plan") + run("checkout", "-q", "-b", "item-1") + pathlib.Path(self.repo, "todo.md").write_text(rows(2, 3)) + run("commit", "-q", "-a", "-m", "Finish item 1 in the plan") + self.head = run("rev-parse", "HEAD") + run("checkout", "-q", "main") + pathlib.Path(self.repo, "todo.md").write_text(rows(1, 2, 3, 4)) + run("commit", "-q", "-a", "-m", "File item 4") + self.listed = f"7\thttps://github.com/o/r/pull/7\t{self.head}\tfalse\tfalse\n" + paths = {setting: pathlib.Path(self.repo, setting) for setting in SETTINGS} | {"plan": pathlib.Path(self.repo, "todo.md"), "changelog": pathlib.Path(self.repo, "CHANGELOG.md")} + self.config = ProjectConfig("acme", pathlib.Path(self.repo, "folder"), pathlib.Path(self.repo), paths, merge="human") + + def test_names_the_items_a_ready_pull_request_finished_on_its_branch(self): + self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "item 4, filed after the branch left main, is not finished on it") + + def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks_and_fails_where_the_forge_does(self): + unfetched = f"7\thttps://github.com/o/r/pull/7\t{'b' * 40}\tfalse\tfalse\n" + self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched), {}) + self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: Failure("gh: no network")).reason, "gh: no network") + + def test_the_projects_plan_passes_over_an_item_that_awaits_a_persons_merge(self): + held = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: self.listed) + self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(1, "#7 https://github.com/o/r/pull/7"), (2, ""), (3, ""), (4, "")]) + self.assertIsNone(held.merges_unread) + self.assertEqual(release_standing.chunk_item(held.plan.items, held.cut).item.id, 2) + self.assertEqual([item.id for item in todo_table.bundle_candidates(held.plan.items, held.plan.items[1])], [3, 4]) + + def test_the_projects_plan_asks_no_forge_where_the_chunk_merges_or_no_forge_is_given(self): + asked: list[list[str]] = [] + chunk = release_standing.project_plan(dataclasses.replace(self.config, merge="chunk"), "main", self.repo, forge_run=lambda command: asked.append(command) or self.listed) + self.assertEqual((asked, [item.awaits_merge for item in chunk.plan.items]), ([], [""] * 4)) + self.assertEqual([item.awaits_merge for item in release_standing.project_plan(self.config, "main", self.repo).plan.items], [""] * 4) + + def test_the_projects_plan_says_why_where_the_forge_cannot_list_the_pull_requests(self): + held = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: Failure("gh: no network")) + self.assertEqual(([item.awaits_merge for item in held.plan.items], held.merges_unread.reason), ([""] * 4, "gh: no network")) + + def test_says_which_pull_requests_await_a_merge_where_every_item_left_waits(self): + held = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: self.listed) + items = [dataclasses.replace(item, awaits_merge="#8 https://github.com/o/r/pull/8" if item.id != 1 else item.awaits_merge) for item in held.plan.items] + none = next_chunk.planned(Plan(items), held.cut, "main", "item-{id}") + self.assertEqual(none.why, "every item of release 0.1.0 in main's todo.md waits. Under `merge = \"human\"`, a person's merge is awaited of pull request #7 https://github.com/o/r/pull/7, which finishes item 1 and #8 https://github.com/o/r/pull/8, which finishes items 2, 3 and 4. The working loop stops here until one is merged.") diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 74421fad..97c9ce1f 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -269,7 +269,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects(pathlib.Path.home(), os.environ).git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=unused, git=system_effects(pathlib.Path.home(), os.environ).git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, env, self.home, effects, **self.limits) diff --git a/skills/larv-review/standards/prose.md b/skills/larv-review/standards/prose.md index 43316a18..87aec594 100644 --- a/skills/larv-review/standards/prose.md +++ b/skills/larv-review/standards/prose.md @@ -12,3 +12,4 @@ Everything written — chat, commit messages, comments, docs, code — is in **E - **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, doesn't carry anything — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. - **Write negations as people say them.** After a verb, or after its preposition, write `doesn't anything` or `anyone`, never ` nothing` or `no one`; each breach is a 🟡. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`. - **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader choosing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. +- **A sentence about several named things holds for each.** Where a sentence gives one property to several named tables, fields or flags, check the property in each one's source. Where it fails for one, split the sentence. BANNED, where only `users` has the column: `Each row of users and groups has a name`. GOOD: `Each row of users has a name. A row of groups has only an id`. -- 2.52.0 From ceacc86a88a35c23900293efcdc0693eb9d338d6 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 21:56:07 +0100 Subject: [PATCH 03/14] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20nothing=20f?= =?UTF-8?q?ound?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 470be28759658d6632b99956438bc69e5b9831a2 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 22:20:43 +0100 Subject: [PATCH 04/14] =?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);=20take=20the?= =?UTF-8?q?=20reviewer's=20rewrites?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/chunk_pr/main.py | 2 +- bin/chunk_preflight/facts.py | 4 ++-- bin/chunk_preflight/gathered.py | 7 ++++--- bin/chunk_preflight/main.py | 16 ++++++++-------- bin/forge/pulls.py | 2 +- bin/plan/todo_table.py | 2 +- bin/release_plan/awaiting_merge.py | 8 ++++---- skills/larv-review/standards/prose.md | 2 +- 9 files changed, 23 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index dec76e07..9734d1d0 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ A legacy project with no container setup sets `tooling-on-host = true`, so the l A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. While it waits, other chunks merge. It stops where a reviewer's comment waits for an answer, on an approved pull request too; answer it and run it again. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false. -A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. loop-claude starts no chunk from an item such a pull request finishes. Once every item left in the release waits and one waits for a merge, the loop stops and names the pull requests to merge. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged one left. Nobody works on a pull request that awaits your merge: to have a reviewer's comment answered, turn it back into a draft, and a chunk takes its item up again. Left out, the setting is `"chunk"`: the chunk merges. +A project whose team merges its pull requests itself sets `merge = "human"`. `chunk-pr merge` then brings the branch level with origin's default branch, finishes the chunk's plan items, waits for the checks and marks the pull request ready, but leaves the merge to a person. A plan or changelog kept in the checkout is finished on the branch, so it lands with that merge; one kept in Jira, or in the config's folder, is finished at once; where you close the pull request unmerged, file the item again. A do-epic chunk parks until the pull request is merged, and its window's name says `awaits your merge`. loop-claude doesn't start a chunk for an item that a ready pull request finishes. Once no item left in the release can start and one awaits a merge, loop-claude stops and names the pull requests to merge; run it again after you merge one. The first chunk after a merge runs `chunk-pr clean` in the worktree the merged pull request left, where nobody pushed to the pull request after the chunk did. Nobody works on a pull request that awaits your merge. To have a reviewer's comment answered, turn the pull request back into a draft: a chunk then takes its item up again. Left out, the setting is `"chunk"`: the chunk merges. For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed. diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 7a6f736f..6b249149 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -476,7 +476,7 @@ def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> if isinstance(finishing, Failure): return finishing title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan") - # Under `merge = "human"` a plan or changelog outside the checkout is finished here, before the person merges, since no run follows that merge; where they close the pull request unmerged, they file the item again. + # Under `merge = "human"` a plan or changelog outside the checkout is finished here, before the person merges, since no run follows that merge. # A plan in Jira, or a changelog on a Confluence page, is no file to commit. records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()] return committed(run, title, records) diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index d95fca2c..806b0029 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -29,11 +29,11 @@ def render(found: Gathered) -> list[str]: def merge_lines(found: Gathered) -> list[str]: - """What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, and why those could not be read.""" + """What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, or why those pull requests could not be read.""" left = [f"- The worktree {worktree.path}, on the branch {worktree.branch}, is left from pull request #{worktree.pull}, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step." for worktree in found.left] items = found.item.plan.items if isinstance(found.item, ItemFacts) else [] passed = [f"item {item.id}, by pull request {item.awaits_merge}" for item in items if item.awaits_merge] - over = [f"- Passed over, since each is finished on a branch whose pull request is ready and awaits a person's merge: {'; '.join(passed)}. No chunk takes one."] if passed else [] + over = [f"- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: {'; '.join(passed)}. No chunk takes one."] if passed else [] unread = [f"- The pull requests that await a person's merge cannot be read, so no item is passed over for one: {found.merges_unread.reason}"] if found.merges_unread else [] return [*left, *over, *unread] diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index b6008c01..00f81899 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -46,9 +46,10 @@ class ItemFacts: @dataclasses.dataclass(frozen=True) class LeftWorktree: - """A worktree on a branch whose pull request, of this number, has merged.""" + """A worktree on a branch whose pull request has merged.""" path: pathlib.Path branch: str + # The merged pull request's number. pull: str @@ -70,7 +71,7 @@ class Gathered: plan_outside: bool # The language and the templates the project's config names, by their settings. texts: dict[str, str] - # Why the pull requests that await a person's merge could not be read; None where they were read, or the chunk merges its own. + # Why the pull requests that await a person's merge could not be read; None where they were read or not asked for. merges_unread: Failure | None = None - # Each other worktree whose pull request a person has merged, which `chunk-pr clean` is still to remove. + # The worktrees `chunk-pr clean` is still to remove. left: tuple[LeftWorktree, ...] = () diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index e38bf979..86e00ba6 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -16,15 +16,15 @@ and prints that the release reviews and the cuts are the human's to call. It pri newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count. Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how many commits followed the cut: the tag, or the commit that added that heading; -- under `merge = "human"` (`project-config --help`), each other worktree whose pull request has - merged, for the worker to run `chunk-pr clean` in, and each item passed over: one that an open - pull request, no draft, finished on its branch, where the checkout holds the plan. Such an item - waits until a person merges. Where every item left in the release waits and one awaits a merge, - it names those pull requests and says the working loop stops there; +- under `merge = "human"` (`project-config --help`), each worktree beside the checkout whose pull + request has merged, for the worker to run `chunk-pr clean` in, and each item passed over: one + finished on the branch of an open pull request that is not a draft, where the checkout holds + the plan. Where no item of the release can start and one awaits such a merge, it names those + pull requests and says the working loop stops there; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I; with --item , the plan item of that ID instead, which loop-claude names in a window - named for an item. An item waits while it is marked question, or while an item still in todo.md - blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z + named for an item. An item waits while it is marked question, while an item still in todo.md + blocks it, or while it awaits such a merge. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a release whose items are all done still reads as next. @@ -181,7 +181,7 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | F def left_worktrees(root: pathlib.Path, forge_run: Run) -> tuple[LeftWorktree, ...]: - """Each worktree beside the checkout whose branch's pull request has merged at the worktree's head: under `merge = "human"` a person merges after the chunk's run has ended, so its worker never ran `chunk-pr clean`. A worktree whose forge can't be asked counts as not left.""" + """Each worktree but root that is on a branch whose pull request merged with the worktree's head commit as its head: under `merge = "human"` a person merges after the chunk's run has ended, so its worker never ran `chunk-pr clean`. Where the forge can't be asked, no worktree counts as left.""" listing, url = git("worktree", "list", "--porcelain"), git("remote", "get-url", "origin") if isinstance(listing, Failure) or isinstance(url, Failure): return () diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 7655748c..2c641471 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -56,7 +56,7 @@ class ReadyPull: def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: - """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row whose number or head is no number or commit ID is left out, since callers pass them to git.""" + """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it.""" if forge == "gh": # 100 is the most GitHub's API lists a page; gh lists 30 unless told. listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]) diff --git a/bin/plan/todo_table.py b/bin/plan/todo_table.py index 6bc7605b..38731980 100644 --- a/bin/plan/todo_table.py +++ b/bin/plan/todo_table.py @@ -107,7 +107,7 @@ class Item: blocked_by: tuple[int, ...] # Empty where the item has none, and where a reader took only the table. detail: str = "" - # The pull request, as `# `, whose merge by a person the item awaits, finished on that branch only; empty where it awaits none, and where the reader asked no forge. release_plan.awaiting_merge sets it. + # The pull request, as `# `, whose merge by a person the item awaits; empty where it awaits none, and where the reader asked no forge. release_plan.awaiting_merge sets it. awaits_merge: str = "" @property diff --git a/bin/release_plan/awaiting_merge.py b/bin/release_plan/awaiting_merge.py index 7f6c92ea..6e36e01a 100644 --- a/bin/release_plan/awaiting_merge.py +++ b/bin/release_plan/awaiting_merge.py @@ -3,14 +3,14 @@ import dataclasses from failure import Failure from forge.commands import Forge, Run -from forge.pulls import ready_pulls from git_cli.git_repo import Git, git -from plan_store import stores from plan_store.plans import Plan, PlanStore +from forge.pulls import ready_pulls +from plan_store import stores def awaiting(ref: str, plan: PlanStore, root: str, forge: Forge, forge_run: Run, run: Git = git) -> dict[int, str] | Failure: - """Each plan item, by ID, that awaits a person's merge, with its pull request as `# `: an item the plan held where the pull request's branch left ref, the default branch, and no longer holds at its head. A pull request whose head the checkout hasn't fetched, or whose plan can't be read, names none.""" + """Each plan item, by ID, that awaits a person's merge, with its pull request as `# `: an item that the plan held at the commit where the pull request's branch left ref, the default branch, and that the plan at the pull request's head no longer holds. A pull request whose head the checkout hasn't fetched, or whose plan can't be read, names none.""" pulls = ready_pulls(forge, forge_run) if isinstance(pulls, Failure): return pulls @@ -26,5 +26,5 @@ def awaiting(ref: str, plan: PlanStore, root: str, forge: Forge, forge_run: Run, def marked(plan: Plan, awaited: dict[int, str]) -> Plan: - """plan with each item awaited names marked as awaiting its pull request's merge, so it waits.""" + """plan, with each item whose ID awaited holds marked as awaiting that pull request's merge, so the item waits.""" return dataclasses.replace(plan, items=[dataclasses.replace(item, awaits_merge=awaited.get(item.id, "")) for item in plan.items]) diff --git a/skills/larv-review/standards/prose.md b/skills/larv-review/standards/prose.md index 87aec594..a362c13c 100644 --- a/skills/larv-review/standards/prose.md +++ b/skills/larv-review/standards/prose.md @@ -12,4 +12,4 @@ Everything written — chat, commit messages, comments, docs, code — is in **E - **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, doesn't carry anything — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. - **Write negations as people say them.** After a verb, or after its preposition, write `doesn't anything` or `anyone`, never ` nothing` or `no one`; each breach is a 🟡. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`. - **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader choosing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. -- **A sentence about several named things holds for each.** Where a sentence gives one property to several named tables, fields or flags, check the property in each one's source. Where it fails for one, split the sentence. BANNED, where only `users` has the column: `Each row of users and groups has a name`. GOOD: `Each row of users has a name. A row of groups has only an id`. +- **A sentence about several named things holds for each.** Where a sentence gives one property to several named fields, flags or tables, check the property in each one's source. Where it fails for one, split the sentence. BANNED, where only `users` has the column: `Each row of users and groups has a name`. GOOD: `Each row of users has a name. A row of groups has only an id`. -- 2.52.0 From 56c579bd54199853509c13d2111c3b6fbdd9fd72 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 22:20:43 +0100 Subject: [PATCH 05/14] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20stop=20l?= =?UTF-8?q?oop-claude=20where=20every=20item=20left=20awaits=20a=20person'?= =?UTF-8?q?s=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/test_chunk_preflight.py | 13 ++++++--- bin/forge/test_forge.py | 6 ++-- bin/loop_claude/loop/chunk_windows.py | 16 +++++++---- bin/loop_claude/loop/test_chunk_start.py | 8 ++++-- bin/loop_claude/loop/test_chunk_windows.py | 5 ++++ bin/loop_effects/doubles.py | 2 +- bin/release_plan/next_chunk.py | 13 +++++++-- bin/release_plan/test_release_standing.py | 32 +++++++++++++++++++-- 8 files changed, 74 insertions(+), 21 deletions(-) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 0c03d951..f93753cb 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -20,7 +20,7 @@ from release_plan.awaiting_merge import marked from release_plan import next_chunk from chunk_preflight.facts import open_pulls, render from plan_store.todo_md import plan_of -from chunk_preflight.choices import worktree_add +from chunk_preflight.choices import worktree_add, worktree_on, worktrees from project_config.doubles import write_config BIN = pathlib.Path(__file__).resolve().parents[1] @@ -158,7 +158,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: self.assertEqual(done.returncode, 0, done.stderr) self.assertIn(f"- The worktree {repo.temp}/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.\n", done.stdout) self.assertNotIn("proj-item-3, on the branch", done.stdout, "an open pull request leaves no worktree to clean") - self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, a person's merge is awaited of pull request #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here until one is merged.", done.stdout) + self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.", done.stdout) (repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n") unread = repo.preflight() self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: not logged in\n", unread.stdout) @@ -437,12 +437,17 @@ def rendered(item, release=CUT, note=None): class Render(unittest.TestCase): + def test_reads_each_worktree_on_a_branch_from_gits_listing(self): + porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n" + self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/proj-item-2"), "item-2", "bbb")]) + self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/proj-item-2"), None)) + def test_states_what_a_persons_merge_leaves_only_where_there_is_something(self): self.assertNotIn("merge", rendered(item_facts())) found = gathered(NoItem("the plan holds none.")) left = dataclasses.replace(found, left=(LeftWorktree(pathlib.Path("/c/proj-item-2"), "item-2", "11"),), merges_unread=Failure("`gh pr list` exited 1: no")) - passed = "\n".join(render(gathered(item_facts(marked(plan_of(TODO), {7: "#12 https://github.com/o/r/pull/12"}))))) - self.assertIn("\n- Passed over, since each is finished on a branch whose pull request is ready and awaits a person's merge: item 7, by pull request #12 https://github.com/o/r/pull/12. No chunk takes one.\n", passed) + passed = "\n".join(render(gathered(item_facts(marked(plan_of(TODO), {7: "#12 https://github.com/o/r/pull/12", 8: "#13 https://github.com/o/r/pull/13"}))))) + self.assertIn("\n- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: item 7, by pull request #12 https://github.com/o/r/pull/12; item 8, by pull request #13 https://github.com/o/r/pull/13. No chunk takes one.\n", passed) self.assertIn("- No other item of release 0.2.0 may join item 3's chunk.", passed) self.assertEqual(render(left)[1:3], ["- The worktree /c/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step.", "- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: no"]) diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index 6002ad95..e2a4ee68 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -150,7 +150,7 @@ class ReadyPulls(unittest.TestCase): commands: list[list[str]] = [] listed = f"7\thttps://github.com/o/r/pull/7\t{SHA}\tfalse\tfalse\n8\thttps://github.com/o/r/pull/8\t{SHA}\ttrue\tfalse\n9\thttps://github.com/o/r/pull/9\t{SHA}\tfalse\ttrue\n" self.assertEqual(ready_pulls("gh", lambda command: commands.append(command) or listed), [ReadyPull("7", "https://github.com/o/r/pull/7", SHA)]) - self.assertEqual(commands[0][:5], ["gh", "pr", "list", "--limit", "100"]) + self.assertEqual(commands, [["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]]) def test_leaves_out_on_gh_a_row_whose_head_is_no_commit_id(self): self.assertEqual(ready_pulls("gh", lambda command: "7\thttps://github.com/o/r/pull/7\t--upload-pack=x\tfalse\tfalse\n"), []) @@ -158,7 +158,9 @@ class ReadyPulls(unittest.TestCase): def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self): fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}} draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"} - self.assertEqual(ready_pulls("tea", lambda command: json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) + commands: list[list[str]] = [] + self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) + self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]]) def test_fails_where_the_forge_cannot_list_them(self): self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network") diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index b9f9be65..7de34517 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -76,8 +76,11 @@ def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: i return Room(running, stopped, restart, room - len(restart)) -def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]: - """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone.""" +def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str] | Failure: + """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone. A plan whose NoItem names pull requests that await a person's merge starts none: where nothing runs, a Failure names them.""" + if isinstance(plan, NoItem) and plan.awaits_merge: + # Where nothing runs, the loop stops on the pull requests plan.why names, rather than start a worker only to report them. + return [] if running else Failure(plan.why) if isinstance(plan, NoItem): return [] if running or room < 1 else [NO_ITEM] beside = chunks_beside(plan.items, plan.first) @@ -122,6 +125,8 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map if refused := refusal(session, windows, loop_run.root, effects.tmux): return refused chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects) + if isinstance(chunks, Failure): + return chunks for chunk in chunks: started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux) if isinstance(started, Failure): @@ -139,8 +144,8 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) return None -def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str]: - """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does.""" +def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | Failure: + """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure where no chunk runs or restarts and every item left waits on a person's merge: it names the pull requests.""" room = room_of(windows, loop_run.chunk, leaving, limit) if not room.left: return room.restart @@ -150,7 +155,8 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) plan = NoItem(plan.reason) held = held_items(room.running + room.stopped, project_key(loop_run.root, paths.home), paths.claude_code_transcripts) - return room.restart + [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.stopped] + picked = may_start(plan, room.running + room.restart, held, room.left) + return picked if isinstance(picked, Failure) else room.restart + [chunk for chunk in picked if chunk not in room.stopped] def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index 65f7ea75..277a4209 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -9,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from chunk_driver.doubles import a_loop -from loop_claude.loop import chunk_start +from loop_claude.loop import chunk_start, chunk_windows from project_config.doubles import configured from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES from failure import Failure @@ -92,11 +92,13 @@ class RouteSources(unittest.TestCase): with tempfile.TemporaryDirectory() as root: folder = configured(self, pathlib.Path(root)) (folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n') - fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"]) + fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 2) held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1]))) self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")]) - self.assertEqual(fake.made("forge")[0][:3], ["gh", "pr", "list"]) + self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"]) self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk") + window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git)) + self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick") def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): with tempfile.TemporaryDirectory() as root: diff --git a/bin/loop_claude/loop/test_chunk_windows.py b/bin/loop_claude/loop/test_chunk_windows.py index 71099dfa..ee35d0fa 100644 --- a/bin/loop_claude/loop/test_chunk_windows.py +++ b/bin/loop_claude/loop/test_chunk_windows.py @@ -61,6 +61,11 @@ class ChunkWindows(unittest.TestCase): windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) + def test_stops_on_the_pull_requests_where_every_item_left_awaits_a_persons_merge_and_nothing_runs(self): + awaited = next_chunk.NoItem("every item of release 1.0.0 waits. Pull request #7 awaits a person's merge.", True) + self.assertEqual(chunk_windows.may_start(awaited, [], set(), 1), Failure(awaited.why)) + self.assertEqual(chunk_windows.may_start(awaited, ["item-5"], set(), 1), [], "a running or restarted chunk goes on, and no chunk without an item joins it") + def test_starts_no_item_that_overlaps_a_running_chunks_items(self): # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) diff --git a/bin/loop_effects/doubles.py b/bin/loop_effects/doubles.py index 7226ac89..84e3b4ee 100644 --- a/bin/loop_effects/doubles.py +++ b/bin/loop_effects/doubles.py @@ -62,7 +62,7 @@ class FakeEffects: discard_typed=lambda: self.calls.append(("discard_typed", None)), dm=self.dm, execv=self.execv, - forge=lambda cwd: lambda command: self.answer("forge", command), + forge=lambda cwd: lambda command: self.answer("forge", [cwd, *command]), git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), local_time=lambda seconds: f"<{seconds}>", diff --git a/bin/release_plan/next_chunk.py b/bin/release_plan/next_chunk.py index e9c7deb9..67c6dfe3 100644 --- a/bin/release_plan/next_chunk.py +++ b/bin/release_plan/next_chunk.py @@ -40,6 +40,8 @@ class NextChunk: class NoItem: """Why the plan names no item for the next chunk, as a sentence the worker reads.""" why: str + # Whether why names pull requests that await a person's merge, so that no chunk starts until one is merged. + awaits_merge: bool = False def cut_name(cut: LastCut) -> str | None: @@ -81,8 +83,11 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- renamed to ` to todo.md's `## Renamed` section.") return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.") first = pick.item + if first is None and pick.release is not None: + merges = awaited_merges(weighed.carried, pick.release) + return NoItem(f"every item of release {version(pick.release)} in {where} waits.{merges}", bool(merges)) if first is None: - return NoItem(f"every item of release {version(pick.release)} in {where} waits.{awaited_merges(weighed.carried, pick.release)}" if pick.release is not None else f"{where}'s items table holds no item.") + return NoItem(f"{where}'s items table holds no item.") held = weighed.carried # Every carried item takes one release, the next. over = CarriedOver(next(item.release for item in held if item.id == weighed.moved[0]), weighed.moved) if weighed.moved else None @@ -90,6 +95,8 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi first = next((item for item in held if item.id == item_id), None) if first is None: return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.") + if first.awaits_merge: + return NoItem(f"item {item_id}, the one --item names, is finished on the branch of pull request {first.awaits_merge}, which awaits a person's merge.") return NextChunk(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None) @@ -101,5 +108,5 @@ def awaited_merges(found: list[Item], release: Release) -> str: pulls.setdefault(item.awaits_merge, []).append(str(item.id)) if not pulls: return "" - named = listed([f"{pull}, which finishes item{'s' if len(ids) > 1 else ''} {listed(ids, 'and')}" for pull, ids in pulls.items()], "and") - return f" Under `merge = \"human\"`, a person's merge is awaited of pull request {named}. The working loop stops here until one is merged." + named = "; ".join(f"{pull}, which finishes item{'s' if len(ids) > 1 else ''} {listed(ids, 'and')}" for pull, ids in pulls.items()) + return f" Under `merge = \"human\"`, these pull requests await a person's merge: {named}. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again." diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 78ed47b2..3be9fc38 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -402,7 +402,7 @@ class AwaitingMerge(unittest.TestCase): def setUp(self): self.repo = tempfile.mkdtemp() self.addCleanup(subprocess.run, ["rm", "-rf", self.repo]) - run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout.strip() + run = self.run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=self.repo, env=isolated_env(), text=True).stdout.strip() rows = lambda *ids: HEADER + "".join(ROW.format(id=id_, release="0.1.0") for id_ in ids) run("init", "-q", "-b", "main") run("remote", "add", "origin", "https://github.com/o/r") @@ -426,6 +426,15 @@ class AwaitingMerge(unittest.TestCase): def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks_and_fails_where_the_forge_does(self): unfetched = f"7\thttps://github.com/o/r/pull/7\t{'b' * 40}\tfalse\tfalse\n" self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched), {}) + self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched + self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "the pull request listed after it still counts") + + def test_names_none_for_a_pull_request_whose_head_holds_no_plan(self): + self.run("checkout", "-q", "-b", "planless") + self.run("rm", "-q", "todo.md") + self.run("commit", "-q", "-m", "Drop the plan") + planless = f"9\thttps://github.com/o/r/pull/9\t{self.run('rev-parse', 'HEAD')}\tfalse\tfalse\n" + self.run("checkout", "-q", "main") + self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: planless), {}) self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: Failure("gh: no network")).reason, "gh: no network") def test_the_projects_plan_passes_over_an_item_that_awaits_a_persons_merge(self): @@ -433,6 +442,8 @@ class AwaitingMerge(unittest.TestCase): self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(1, "#7 https://github.com/o/r/pull/7"), (2, ""), (3, ""), (4, "")]) self.assertIsNone(held.merges_unread) self.assertEqual(release_standing.chunk_item(held.plan.items, held.cut).item.id, 2) + self.assertEqual(next_chunk.planned(held.plan, held.cut, "main", "item-{id}", item_id=1), next_chunk.NoItem("item 1, the one --item names, is finished on the branch of pull request #7 https://github.com/o/r/pull/7, which awaits a person's merge.")) + self.assertEqual(next_chunk.planned(held.plan, held.cut, "main", "item-{id}", item_id=2).first.id, 2) self.assertEqual([item.id for item in todo_table.bundle_candidates(held.plan.items, held.plan.items[1])], [3, 4]) def test_the_projects_plan_asks_no_forge_where_the_chunk_merges_or_no_forge_is_given(self): @@ -441,12 +452,27 @@ class AwaitingMerge(unittest.TestCase): self.assertEqual((asked, [item.awaits_merge for item in chunk.plan.items]), ([], [""] * 4)) self.assertEqual([item.awaits_merge for item in release_standing.project_plan(self.config, "main", self.repo).plan.items], [""] * 4) + def test_the_projects_plan_asks_no_forge_about_a_plan_kept_outside_the_checkout(self): + outside = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", str(outside)]) + (outside / "todo.md").write_text(pathlib.Path(self.repo, "todo.md").read_text()) + asked: list[list[str]] = [] + held = release_standing.project_plan(dataclasses.replace(self.config, paths=self.config.paths | {"plan": outside / "todo.md"}), "main", self.repo, forge_run=lambda command: asked.append(command) or self.listed) + self.assertEqual((asked, [item.awaits_merge for item in held.plan.items]), ([], [""] * 4)) + def test_the_projects_plan_says_why_where_the_forge_cannot_list_the_pull_requests(self): held = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: Failure("gh: no network")) self.assertEqual(([item.awaits_merge for item in held.plan.items], held.merges_unread.reason), ([""] * 4, "gh: no network")) + self.run("remote", "remove", "origin") + remoteless = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: self.listed) + self.assertEqual([item.awaits_merge for item in remoteless.plan.items], [""] * 4) + self.assertIsInstance(remoteless.merges_unread, Failure) def test_says_which_pull_requests_await_a_merge_where_every_item_left_waits(self): held = release_standing.project_plan(self.config, "main", self.repo, forge_run=lambda command: self.listed) - items = [dataclasses.replace(item, awaits_merge="#8 https://github.com/o/r/pull/8" if item.id != 1 else item.awaits_merge) for item in held.plan.items] + items = [dataclasses.replace(item, awaits_merge="#8 https://github.com/o/r/pull/8" if item.id in (2, 3) else item.awaits_merge) for item in held.plan.items] + items[3] = dataclasses.replace(items[3], exempt="question") none = next_chunk.planned(Plan(items), held.cut, "main", "item-{id}") - self.assertEqual(none.why, "every item of release 0.1.0 in main's todo.md waits. Under `merge = \"human\"`, a person's merge is awaited of pull request #7 https://github.com/o/r/pull/7, which finishes item 1 and #8 https://github.com/o/r/pull/8, which finishes items 2, 3 and 4. The working loop stops here until one is merged.") + self.assertEqual(none.why, "every item of release 0.1.0 in main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #7 https://github.com/o/r/pull/7, which finishes item 1; #8 https://github.com/o/r/pull/8, which finishes items 2 and 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.") + self.assertTrue(none.awaits_merge) + self.assertFalse(next_chunk.planned(Plan([dataclasses.replace(item, awaits_merge="", exempt="question") for item in items]), held.cut, "main", "item-{id}").awaits_merge) -- 2.52.0 From 1a23aa05b0b4c50bb0c70d57699804ff67ed3081 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 23:17:04 +0100 Subject: [PATCH 06/14] Test that loop-claude starts no chunk where every item left awaits a person's merge --- bin/loop_claude/loop/test_chunk_start.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index 277a4209..addc76cf 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -9,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from chunk_driver.doubles import a_loop -from loop_claude.loop import chunk_start, chunk_windows +from loop_claude.loop import chunk_start, chunk_windows, reload from project_config.doubles import configured from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES from failure import Failure @@ -92,13 +92,15 @@ class RouteSources(unittest.TestCase): with tempfile.TemporaryDirectory() as root: folder = configured(self, pathlib.Path(root)) (folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n') - fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 2) + fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 3) held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1]))) self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")]) self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"]) self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk") window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git)) self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick") + stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git)) + self.assertEqual(stopped, Failure(window.why), "so the loop starts no chunk, and says which pull requests it waits on") def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): with tempfile.TemporaryDirectory() as root: -- 2.52.0 From 356ae263e1711d11ed4297c59e596ad64a3910e2 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 23:30:30 +0100 Subject: [PATCH 07/14] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20exit=200?= =?UTF-8?q?=20on=20awaited=20merges,=20so=20the=20finished=20chunk's=20win?= =?UTF-8?q?dow=20closes=20and=20the=20next=20run=20reads=20the=20plan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/loop/chunk_windows.py | 29 +++++++++++++--------- bin/loop_claude/loop/main.py | 8 ++++-- bin/loop_claude/loop/test_chunk_start.py | 2 +- bin/loop_claude/loop/test_chunk_windows.py | 4 +-- bin/loop_claude/loop/test_main.py | 6 +++-- bin/loop_claude/loop/usage.py | 4 +++ 6 files changed, 34 insertions(+), 19 deletions(-) diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 7de34517..92a4acea 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -76,13 +76,16 @@ def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: i return Room(running, stopped, restart, room - len(restart)) -def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str] | Failure: - """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone. A plan whose NoItem names pull requests that await a person's merge starts none: where nothing runs, a Failure names them.""" - if isinstance(plan, NoItem) and plan.awaits_merge: - # Where nothing runs, the loop stops on the pull requests plan.why names, rather than start a worker only to report them. - return [] if running else Failure(plan.why) +@dataclasses.dataclass(frozen=True) +class AwaitedMerges: + """Why no chunk starts and none runs: every item left awaits a person's merge of the pull requests that why names.""" + why: str + + +def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]: + """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone; none where its NoItem names pull requests that await a person's merge.""" if isinstance(plan, NoItem): - return [] if running or room < 1 else [NO_ITEM] + return [] if running or room < 1 or plan.awaits_merge else [NO_ITEM] beside = chunks_beside(plan.items, plan.first) picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])] details = {item.id: item.detail for item in plan.items} @@ -111,8 +114,8 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | No return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label) -def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure: - """Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. A Failure says why no chunk may start, or why one could not; those before it run.""" +def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | AwaitedMerges | Failure: + """Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run.""" config = located(loop_run.root, paths.home) if isinstance(config, Failure): return config @@ -125,7 +128,7 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map if refused := refusal(session, windows, loop_run.root, effects.tmux): return refused chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects) - if isinstance(chunks, Failure): + if isinstance(chunks, AwaitedMerges): return chunks for chunk in chunks: started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux) @@ -144,8 +147,8 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) return None -def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | Failure: - """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure where no chunk runs or restarts and every item left waits on a person's merge: it names the pull requests.""" +def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges: + """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge.""" room = room_of(windows, loop_run.chunk, leaving, limit) if not room.left: return room.restart @@ -155,8 +158,10 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) plan = NoItem(plan.reason) held = held_items(room.running + room.stopped, project_key(loop_run.root, paths.home), paths.claude_code_transcripts) + if isinstance(plan, NoItem) and plan.awaits_merge and not room.running + room.restart: + return AwaitedMerges(plan.why) picked = may_start(plan, room.running + room.restart, held, room.left) - return picked if isinstance(picked, Failure) else room.restart + [chunk for chunk in picked if chunk not in room.stopped] + return room.restart + [chunk for chunk in picked if chunk not in room.stopped] def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 8cf9a848..d85ef18b 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,11 +4,11 @@ import typing from chunk_driver.cycle_start import announced_route, cycle_of, project_routing from transcript_archive.location import archive_root, project_archive +from loop_claude.loop.chunk_windows import AwaitedMerges, chunk_session, item_of, start_chunks from loop_claude.loop.routing_check import check_routing from loop_claude.loop.checkout import checkout_root from chunk_driver.claims import CHUNK_FLAG, loop_session from loop_claude.chunk import chunk_items, fresh_prompt -from loop_claude.loop.chunk_windows import chunk_session, item_of, start_chunks from loop_claude.loop.chunk_start import chunk_start, plan_item, scored_plan from chunk_driver.chunk_run import closed_cycle from agent_cycle.run import Concluded, Cycle, run_cycle @@ -30,7 +30,7 @@ from agent_cycle import tmux # Starts the chunks that may start now, as chunk_windows.start_chunks does. -StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | Failure] +StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | AwaitedMerges | Failure] @dataclasses.dataclass(frozen=True) @@ -107,6 +107,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, start: StartChunks) -> Stop: """What the loop-claude the human runs does: starts, through start, each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches.""" started = start(loop_run, False, paths, env, launcher, effects) + if isinstance(started, AwaitedMerges): + return Stop(0, started.why) if isinstance(started, Failure): return Stop(1, started.reason) session = loop_session(loop_run.root, paths.home) @@ -121,6 +123,8 @@ def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Path def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop: """The stop of a loop whose chunk finished, once it has started, through start, each chunk that may start now. Its window closes as it exits.""" started = start(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects) + if isinstance(started, AwaitedMerges): + return Stop(0, f"the chunk finished; {started.why}") if isinstance(started, Failure): return Stop(1, f"the chunk finished, but the next could not start: {started.reason}") say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True) diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index addc76cf..a0eccaa1 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -100,7 +100,7 @@ class RouteSources(unittest.TestCase): window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git)) self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick") stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git)) - self.assertEqual(stopped, Failure(window.why), "so the loop starts no chunk, and says which pull requests it waits on") + self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on") def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): with tempfile.TemporaryDirectory() as root: diff --git a/bin/loop_claude/loop/test_chunk_windows.py b/bin/loop_claude/loop/test_chunk_windows.py index ee35d0fa..53733a5a 100644 --- a/bin/loop_claude/loop/test_chunk_windows.py +++ b/bin/loop_claude/loop/test_chunk_windows.py @@ -61,9 +61,9 @@ class ChunkWindows(unittest.TestCase): windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) - def test_stops_on_the_pull_requests_where_every_item_left_awaits_a_persons_merge_and_nothing_runs(self): + def test_starts_no_chunk_without_an_item_where_every_item_left_awaits_a_persons_merge(self): awaited = next_chunk.NoItem("every item of release 1.0.0 waits. Pull request #7 awaits a person's merge.", True) - self.assertEqual(chunk_windows.may_start(awaited, [], set(), 1), Failure(awaited.why)) + self.assertEqual(chunk_windows.may_start(awaited, [], set(), 1), [], "chunks_to_start stops the loop there") self.assertEqual(chunk_windows.may_start(awaited, ["item-5"], set(), 1), [], "a running or restarted chunk goes on, and no chunk without an item joins it") def test_starts_no_item_that_overlaps_a_running_chunks_items(self): diff --git a/bin/loop_claude/loop/test_main.py b/bin/loop_claude/loop/test_main.py index ba5a6346..a0bf48db 100644 --- a/bin/loop_claude/loop/test_main.py +++ b/bin/loop_claude/loop/test_main.py @@ -11,10 +11,10 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from chunk_driver.doubles import a_loop +from loop_claude.loop import chunk_windows, main, reload, usage from loop_effects.doubles import CWD, FakeEffects, ran, STAMP from failure import Failure from agent_cycle.verdicts import Finished, Unfinished -from loop_claude.loop import main, reload, usage from loop_claude.doubles import OPUS_PROJECT from loop_state import paths from model_routing.route import Route @@ -240,6 +240,7 @@ class WindowStarts(unittest.TestCase): def test_stops_where_no_chunk_could_start(self): self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan")) + self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=chunk_windows.AwaitedMerges("#7 awaits a merge."))[0], Stop(0, "#7 awaits a merge."), "nothing failed, so the stop exits 0") def test_stops_where_tmux_cannot_show_the_session(self): fake = FakeEffects(git=["/r\n"]) @@ -260,7 +261,8 @@ class WindowStarts(unittest.TestCase): def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self): loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7") for started, said, stop in ((["item-9", "item-12"], "the chunk finished; started item-9, item-12", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")), - (Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan"))): + (Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan")), + (chunk_windows.AwaitedMerges("#7 awaits a merge."), "", Stop(0, "the chunk finished; #7 awaits a merge."))): with self.subTest(started=started), contextlib.redirect_stdout(io.StringIO()) as printed: loop, asked = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"}), [] self.assertEqual(main.handed_on(loop_run, loop, lambda *args: asked.append(args) or started), stop) diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index 0b73d47f..e008f98e 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -160,6 +160,10 @@ measurement. A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds: the loop reloads into the edited script. +Under merge = "human", where no chunk runs and every item left awaits a person's merge, loop-claude +doesn't start a chunk: it names those pull requests, in a DM too, and exits 0. Its window closes, +so the next loop-claude reads the plan again. + Exit 1, saying why, when: - no task is given - git cannot start or finds no checkout -- 2.52.0 From 0c52688ff881c7eaf548c0e1361021cf0f2f11b4 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 23:30:30 +0100 Subject: [PATCH 08/14] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20bound=20the?= =?UTF-8?q?=20forge's=20CLI=20with=20a=20timeout=20in=20one=20runner,=20an?= =?UTF-8?q?d=20read=20a=20pull=20request=20from=20a=20deleted=20fork?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/main.py | 14 ++---------- bin/chunk_preflight/test_chunk_preflight.py | 8 +++---- bin/forge/commands.py | 7 ++++-- bin/forge/pulls.py | 6 +++--- bin/forge/test_forge.py | 24 +++++++++++++++------ bin/loop_effects/effects.py | 4 +++- bin/release_plan/test_release_standing.py | 2 +- 7 files changed, 35 insertions(+), 30 deletions(-) diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 86e00ba6..567c9e7d 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -83,7 +83,7 @@ import typing from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from failure import Failure -from forge.commands import Forge, forge_of, Run +from forge.commands import Forge, forge_of, Run, runner from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree from chunk_preflight.facts import JOINING_DETAILS, render from project_config.main import located @@ -149,7 +149,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non if isinstance(config, Failure): return config outside = None if config.tracked("plan") else config.plan_label - forge_run = forge_runner(root, timeout) + forge_run = runner(str(root), timeout) held = project_plan(config, ref, str(root), forge_run=forge_run) plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) @@ -189,16 +189,6 @@ def left_worktrees(root: pathlib.Path, forge_run: Run) -> tuple[LeftWorktree, .. return tuple(LeftWorktree(path, branch, pull) for path, branch, pull in merged if isinstance(pull, str)) -def forge_runner(root: pathlib.Path, timeout: float) -> Run: - """Runs the forge's CLI at root, stopped after timeout seconds: what it printed, or a Failure with why it failed.""" - def run(command: list[str]) -> str | Failure: - done = ran(command, root, timeout) - if isinstance(done, Failure): - return Failure(f"`{' '.join(command[:3])}` {done.reason}") - return Failure(f"`{' '.join(command[:3])}` exited {done.code}: {done.stderr.strip()}") if done.code else done.stdout - return run - - def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None: url = git("remote", "get-url", "origin") if isinstance(url, Failure): diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index f93753cb..e017fdc7 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -161,7 +161,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.", done.stdout) (repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n") unread = repo.preflight() - self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: `gh pr list` exited 1: not logged in\n", unread.stdout) + self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: gh pr list: not logged in\n", unread.stdout) self.assertIn("Its first item that does not wait: item 3,", unread.stdout) def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self): @@ -438,9 +438,9 @@ def rendered(item, release=CUT, note=None): class Render(unittest.TestCase): def test_reads_each_worktree_on_a_branch_from_gits_listing(self): - porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n" - self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/proj-item-2"), "item-2", "bbb")]) - self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/proj-item-2"), None)) + porcelain = "worktree /c/proj\nHEAD aaa\nbranch refs/heads/main\n\nworktree /c/my proj-item-2\nHEAD bbb\nbranch refs/heads/item-2\n\nworktree /c/detached\nHEAD ccc\ndetached\n" + self.assertEqual(worktrees(porcelain), [(pathlib.Path("/c/proj"), "main", "aaa"), (pathlib.Path("/c/my proj-item-2"), "item-2", "bbb")]) + self.assertEqual((worktree_on(porcelain, "item-2"), worktree_on(porcelain, "item-3")), (pathlib.Path("/c/my proj-item-2"), None)) def test_states_what_a_persons_merge_leaves_only_where_there_is_something(self): self.assertNotIn("merge", rendered(item_facts())) diff --git a/bin/forge/commands.py b/bin/forge/commands.py index 762461ac..88ec0ac2 100644 --- a/bin/forge/commands.py +++ b/bin/forge/commands.py @@ -24,12 +24,15 @@ def url_beside(origin_url: str, name: str) -> str | None: return place.group(1) + name if place and not place.group(1).endswith("//") else None -def runner(cwd: str) -> Run: +def runner(cwd: str, timeout: float | None = None) -> Run: + """Runs a command in cwd, stopped after timeout seconds where one is given.""" 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) + done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout) except OSError as failure: return Failure(f"{command[0]} could not start: {failure}") + except subprocess.TimeoutExpired: + return Failure(f"{' '.join(command[:3])}: stopped after {timeout} s") if done.returncode: return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}") return done.stdout diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 2c641471..aea166a3 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -56,9 +56,9 @@ class ReadyPull: def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: - """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT). A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it.""" + """Each open pull request from origin's own branches that is no draft, which Gitea tells by its title (GITEA_DRAFT); Gitea names no head repo for a fork that was deleted. A row is left out where its head is no commit ID, since the caller passes the head to git, or where its number is not all digits, since the caller prints it.""" if forge == "gh": - # 100 is the most GitHub's API lists a page; gh lists 30 unless told. + # A limit: an awaited pull request past the first 100 open ones, drafts and forks counted, is not seen. `--draft=false` would make gh search, and GitHub's search index lags a pull request just marked ready. listed = run(["gh", "pr", "list", "--limit", "100", "--json", "number,url,headRefOid,isDraft,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.url}}\t{{.headRefOid}}\t{{.isDraft}}\t{{.isCrossRepository}}\n{{end}}"]) if isinstance(listed, Failure): return listed @@ -69,7 +69,7 @@ def ready_pulls(forge: Forge, run: Run) -> list[ReadyPull] | Failure: if isinstance(pulls, Failure): return pulls try: - found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)] + found = [ReadyPull(str(pull["number"]), pull["html_url"], pull["head"]["sha"]) for pull in pulls if (pull["head"]["repo"] or {}).get("full_name") == pull["base"]["repo"]["full_name"] and not pull["title"].upper().startswith(GITEA_DRAFT)] except (AttributeError, KeyError, TypeError): return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}") return [pull for pull in found if pull.number.isascii() and pull.number.isdigit() and isinstance(pull.head, str) and re.fullmatch(r"[0-9a-f]{40,64}", pull.head)] diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index e2a4ee68..a026343f 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, ready_pulls, ReadyPull, required_checks, WAIT_SECONDS from failure import Failure -from forge.commands import forge_of, gitea, url_beside +from forge.commands import forge_of, gitea, runner, url_beside class ForgeOf(unittest.TestCase): @@ -136,11 +136,6 @@ class ChecksPassed(unittest.TestCase): self.assertEqual(checks_passed("tea", "1", "abc", set(), tea([LONG]), self.fail).reason, f"tea api printed no commit status for abc: {LONG[:200]}") - -if __name__ == "__main__": - unittest.main() - - SHA = "a" * 40 GITEA_PULL = {"number": 7, "html_url": "https://gitea.example/o/r/pulls/7", "title": "Do 7", "head": {"sha": SHA, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}} @@ -158,10 +153,25 @@ class ReadyPulls(unittest.TestCase): def test_lists_on_tea_each_open_pull_request_from_origins_own_branches_whose_title_marks_no_draft(self): fork = {**GITEA_PULL, "number": 8, "head": {"sha": SHA, "repo": {"full_name": "other/r"}}} draft = {**GITEA_PULL, "number": 9, "title": "wip: Do 9"} + deleted_fork = {**GITEA_PULL, "number": 10, "head": {"sha": SHA, "repo": None}} commands: list[list[str]] = [] - self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) + self.assertEqual(ready_pulls("tea", lambda command: commands.append(command) or json.dumps([GITEA_PULL, fork, draft, deleted_fork])), [ReadyPull("7", "https://gitea.example/o/r/pulls/7", SHA)]) self.assertEqual(commands, [["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]]) def test_fails_where_the_forge_cannot_list_them(self): self.assertEqual(ready_pulls("gh", lambda command: Failure("gh: no network")).reason, "gh: no network") self.assertEqual(ready_pulls("tea", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}") + + +class Runner(unittest.TestCase): + def test_prints_what_a_command_printed_and_fails_where_it_exits_nonzero_cannot_start_or_outlasts_its_timeout(self): + self.assertEqual(runner("/")(["echo", "hello"]), "hello\n") + self.assertEqual(runner("/")(["sh", "-c", "echo no >&2; exit 3"]), Failure("sh -c echo no >&2; exit 3: no")) + failed = runner("/")(["no-such-forge-cli", "pr", "list"]) + self.assertIsInstance(failed, Failure) + self.assertTrue(failed.reason.startswith("no-such-forge-cli could not start: "), failed.reason) + self.assertEqual(runner("/", 0.05)(["sleep", "5"]), Failure("sleep 5: stopped after 0.05 s")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index d0d9481d..6d58130c 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -26,6 +26,8 @@ from machine_load.slots import slot_folder # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 +# Seconds a command of the forge's CLI may take, so a stalled one cannot hold the loop. +FORGE_TIMEOUT = 60 class Streaming(typing.Protocol): @@ -123,7 +125,7 @@ def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), dm=lambda text, directory: notify(text, directory, home, backends), execv=os.execv, - forge=runner, + forge=lambda cwd: runner(cwd, FORGE_TIMEOUT), git=git_repo.git, input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)), diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 3be9fc38..faefb665 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -423,7 +423,7 @@ class AwaitingMerge(unittest.TestCase): def test_names_the_items_a_ready_pull_request_finished_on_its_branch(self): self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "item 4, filed after the branch left main, is not finished on it") - def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks_and_fails_where_the_forge_does(self): + def test_names_none_for_a_pull_request_whose_head_the_checkout_lacks(self): unfetched = f"7\thttps://github.com/o/r/pull/7\t{'b' * 40}\tfalse\tfalse\n" self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched), {}) self.assertEqual(awaiting_merge.awaiting("main", plan_in(self.repo), self.repo, "gh", lambda command: unfetched + self.listed), {1: "#7 https://github.com/o/r/pull/7"}, "the pull request listed after it still counts") -- 2.52.0 From 7f9237e91ead03066b0a0b2d84a1e858704277b4 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:12:55 +0100 Subject: [PATCH 09/14] Test the forge runner's folder and timeout message, and the loop's forge effect --- bin/forge/test_forge.py | 6 +++++- bin/loop_effects/test_effects.py | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index a026343f..44c49f23 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -1,7 +1,9 @@ import itertools import json +import os import pathlib import sys +import tempfile import typing import unittest @@ -170,7 +172,9 @@ class Runner(unittest.TestCase): failed = runner("/")(["no-such-forge-cli", "pr", "list"]) self.assertIsInstance(failed, Failure) self.assertTrue(failed.reason.startswith("no-such-forge-cli could not start: "), failed.reason) - self.assertEqual(runner("/", 0.05)(["sleep", "5"]), Failure("sleep 5: stopped after 0.05 s")) + self.assertEqual(runner("/", 0.05)(["sh", "-c", "sleep 5", "later"]), Failure("sh -c sleep 5: stopped after 0.05 s")) + with tempfile.TemporaryDirectory() as folder: + self.assertEqual(runner(folder)(["pwd", "-P"]), os.path.realpath(folder) + "\n") if __name__ == "__main__": diff --git a/bin/loop_effects/test_effects.py b/bin/loop_effects/test_effects.py index de024575..38efc268 100644 --- a/bin/loop_effects/test_effects.py +++ b/bin/loop_effects/test_effects.py @@ -99,6 +99,12 @@ class ClaudeOnTerminal(unittest.TestCase): +class ForgeEffect(unittest.TestCase): + def test_runs_the_forges_cli_in_the_checkout_it_is_given(self): + with tempfile.TemporaryDirectory() as folder: + self.assertEqual(system_effects(pathlib.Path.home(), os.environ).forge(folder)(["pwd", "-P"]), os.path.realpath(folder) + "\n") + + class TmuxEffect(unittest.TestCase): """Each test runs a fake tmux off its own PATH, without $TMUX, so the human's tmux server is never reached.""" -- 2.52.0 From fb0a7ac8cf7f3df9d8f8b387df034de6a06facd2 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:16:35 +0100 Subject: [PATCH 10/14] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20every=20ans?= =?UTF-8?q?wer=20holds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 2797e11080f2ce0ec70a144939bcc6d2827d188d Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:25:37 +0100 Subject: [PATCH 11/14] Check the awaited-merges stop in one place and name the pull-request listing in the package notes --- README.md | 4 ++-- bin/chunk_preflight/main.py | 2 +- bin/forge/pulls.py | 2 +- bin/loop_claude/loop/chunk_windows.py | 4 ++-- bin/loop_claude/loop/test_chunk_windows.py | 5 ----- bin/release_plan/next_chunk.py | 2 +- 6 files changed, 7 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 7d35948d..b59f1447 100644 --- a/README.md +++ b/README.md @@ -235,7 +235,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. -- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. +- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request, lists the ready ones and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. @@ -247,7 +247,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass; `jira_epic.py` doesn't yet, and its own tests stand in for Jira. `fakes.py` holds a plan in memory. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use. -- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, and picks the item the next chunk takes first (`next_chunk.py`), for `chunk_preflight` and `loop_claude`. +- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, picks the item the next chunk takes first (`next_chunk.py`), and marks each item that a ready pull request finishes (`awaiting_merge.py`), for `chunk_preflight` and `loop_claude`. - `repo_checks/` tests the repo itself. - `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 567c9e7d..5a8f009e 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -155,7 +155,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) # A `checkout:` path lands in the worktree the chunk works in. made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config - return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, held.merges_unread, left_worktrees(root, forge_run) if config.merge == "human" else ())) + return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, merges_unread=held.merges_unread, left=left_worktrees(root, forge_run) if config.merge == "human" else ())) def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts: diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index fe56681a..dba37458 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -1,4 +1,4 @@ -"""Finding a pull request from origin's own branch, reading whether it merges into its base, and waiting for the checks on its head commit.""" +"""Finding a pull request from origin's own branch, listing the ready ones, reading whether one merges into its base, and waiting for the checks on its head commit.""" import dataclasses import fnmatch import json diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 92a4acea..83f181b7 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -83,9 +83,9 @@ class AwaitedMerges: def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]: - """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone; none where its NoItem names pull requests that await a person's merge.""" + """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone.""" if isinstance(plan, NoItem): - return [] if running or room < 1 or plan.awaits_merge else [NO_ITEM] + return [] if running or room < 1 else [NO_ITEM] beside = chunks_beside(plan.items, plan.first) picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])] details = {item.id: item.detail for item in plan.items} diff --git a/bin/loop_claude/loop/test_chunk_windows.py b/bin/loop_claude/loop/test_chunk_windows.py index 53733a5a..71099dfa 100644 --- a/bin/loop_claude/loop/test_chunk_windows.py +++ b/bin/loop_claude/loop/test_chunk_windows.py @@ -61,11 +61,6 @@ class ChunkWindows(unittest.TestCase): windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) - def test_starts_no_chunk_without_an_item_where_every_item_left_awaits_a_persons_merge(self): - awaited = next_chunk.NoItem("every item of release 1.0.0 waits. Pull request #7 awaits a person's merge.", True) - self.assertEqual(chunk_windows.may_start(awaited, [], set(), 1), [], "chunks_to_start stops the loop there") - self.assertEqual(chunk_windows.may_start(awaited, ["item-5"], set(), 1), [], "a running or restarted chunk goes on, and no chunk without an item joins it") - def test_starts_no_item_that_overlaps_a_running_chunks_items(self): # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) diff --git a/bin/release_plan/next_chunk.py b/bin/release_plan/next_chunk.py index 67c6dfe3..bbed2388 100644 --- a/bin/release_plan/next_chunk.py +++ b/bin/release_plan/next_chunk.py @@ -85,7 +85,7 @@ def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outsi first = pick.item if first is None and pick.release is not None: merges = awaited_merges(weighed.carried, pick.release) - return NoItem(f"every item of release {version(pick.release)} in {where} waits.{merges}", bool(merges)) + return NoItem(f"every item of release {version(pick.release)} in {where} waits.{merges}", awaits_merge=bool(merges)) if first is None: return NoItem(f"{where}'s items table holds no item.") held = weighed.carried -- 2.52.0 From 45115ef5e4b5c19e8c5ce8bf2b093bd5e6a743b1 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:28:29 +0100 Subject: [PATCH 12/14] Record the comprehension check: same --- docs/comprehension-history.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index e828902c..24dd2685 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -4206,3 +4206,25 @@ Inherited architect, would restructure first: - Navigation: `bin/do_epic/status.py:1` the module: in no map, and the package's `__init__.py` is empty like 40 others - Locality: `reviewer-merge-trials/driver.py:4` the imports: a frozen trial imports live code under `bin/`, so a refactor there breaks a record - Self-sufficiency: `bin/agent_cycle/routing.py:92` the comment: one of 109 citations of the decision log that carry a unit's reason + +## 2026-11-19T23:28:20Z, PR #645 at 2797e110, against a9bdef6 + +Ruling: same + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | same | worse | same | same | same | +| Inherited architect | same | worse | same | same | same | + +Mid A, decided by: + +- Locality: `bin/plan/todo_table.py:110` `Item.awaits_merge`: the plan core's item carries a mark that release_plan.awaiting_merge sets from forge state, so whether an item waits depends on whether project_plan's caller passed a forge_run. +- Locality: `bin/release_plan/next_chunk.py:88` `planned`: the loop's stop is the truthiness of a sentence, and travels through chunks_to_start, AwaitedMerges, start_chunks, windows_opened and handed_on. +- Locality: `bin/do_epic/main.py:431` `handed_on`: one straight path became two booleans that three call sites set, branching three ways against config.automation_moves. + +Inherited architect, decided by: + +- Locality: `bin/release_plan/release_standing.py:104` `project_plan`: a one-line delegate that read git now calls the forge behind a four-part guard, while the module docstring speaks only of the default branch. +- Locality: `bin/plan/todo_table.py:110` `Item.awaits_merge`: a field nothing in its own package sets; waiting reads it, so it depends on a caller three packages out having run the marking. +- Locality: `bin/loop_claude/loop/chunk_windows.py:161` `chunks_to_start`: the stop condition is split across two packages, and one half is a string's truthiness. +- Locality: `bin/do_epic/scheduler.py:96` `open_blockers`: four functions gained a defaulted `unblocking`, so a caller that forgets it silently gets the old behaviour. -- 2.52.0 From 20b13065ea3f769268815d43803922328c3b49a3 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:28:29 +0100 Subject: [PATCH 13/14] Name the forge read in release_standing's docstring --- bin/release_plan/release_standing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/release_plan/release_standing.py b/bin/release_plan/release_standing.py index 89bbfce5..427b5371 100644 --- a/bin/release_plan/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -1,4 +1,4 @@ -"""How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick.""" +"""How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick, and, under `merge = "human"`, what the forge says of the pull requests that await a person's merge.""" import dataclasses from release_plan.awaiting_merge import awaiting, marked -- 2.52.0 From d516a287504b2b5efe2d98d346a38e00d2a50466 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Fri, 20 Nov 2026 00:28:46 +0100 Subject: [PATCH 14/14] Finish item 457 in the plan --- CHANGELOG.md | 1 + todo.md | 33 --------------------------------- 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3febc411..40144548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Under `merge = "human"`, `loop-claude` and `chunk-preflight` pass over an item whose ready pull request awaits a person's merge, and `loop-claude` stops, naming those pull requests, once every item left awaits one. - do-epic reads two new settings from a project's config: `jira-unblocking-statuses` names the statuses at which an issue unblocks the issues it blocks, and `jira-automation-moves-issues` leaves the move out of "In Progress" to the team's own automation. - The prose standard asks that a sentence about several named things holds for each of them. - `do-epic` resumes a chunk parked on `your merge` when its pull request no longer merges into its base, so the worker runs `chunk-pr merge` again to level the branch; a finished chunk in that state stays open until its pull request merges. diff --git a/todo.md b/todo.md index d81d16d2..c20c1333 100644 --- a/todo.md +++ b/todo.md @@ -15,7 +15,6 @@ | 463 | 0.14.0 | | defect | **Show the judge the transcript's tail whatever the size of the records.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 6, 1.5 by 4, 1.4 by 2 | 4.2 | | 449 | 0.14.0 | | | **Record do-epic's repo picks and sub-task summaries in the team's own spelling, such as `core-4` and `core-4: Bygg …`, as its config sets them.** | 2 | 2 | 2 | 4 | 3 | 1.6 by 6 | 2.0 | | 453 | 0.14.0 | | | **Make the issue types that do-epic and `todo-item add` file in Jira settings, since a Jira project such as TW has no Task type.** | 2 | 2 | 1 | 3 | 2 | 1.6 by 5 | 1.8 | -| 457 | 0.14.0 | | | **Keep loop-claude from starting a chunk for an item whose pull request is ready and awaits a person's merge under `merge = "human"`.** | 3 | 2 | 2 | 5 | 5 | 1.6 by 5, 1.4 by 3 | 1.7 | | 450 | 0.14.0 | | | **Add `do-epic --dry-run`, which prints every Jira write planning would make and each chunk that would start, and makes none of them.** | 2 | 2 | 2 | 4 | 3 | 1.6 by 5 | 1.6 | | 454 | 0.14.0 | | | **Start a do-epic chunk's issue as the team's board expects, by settings: assigned to the account do-epic works as, moved by a start transition and added to a board's active sprint.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 4 | 1.1 | | 446 | 0.15.0 | | question | **Kill the process a stuck check names where its verdict is `stuck`, once the human says the recorded verdicts match what they would have done.** | 2 | 2 | 3 | 5 | 3 | 1.5 by 3 | 1.0 | @@ -127,38 +126,6 @@ Touches: - `bin/do_epic/backend/test_jira.py` - `README.md`: `### Set up a project` (small) -### 457. Keep loop-claude from starting a chunk for an item whose pull request is ready and awaits a person's merge under `merge = "human"`. - -Under `merge = "human"`, `chunk-pr merge` leaves a chunk's pull request ready, with its item finished only on the branch. Until a person merges it, the default branch's plan still holds the item, so `chunk-preflight` names it as the next item again. loop-claude then starts a cycle that can only run `chunk-pr merge` once more and end, and it does so every cycle until the merge. - -- `chunk-preflight` passes over an item whose branch has an open pull request that isn't a draft, where the project's config sets `merge = "human"`, and says so in its facts. -- Where every remaining item of the release waits like that, loop-claude stops and says which pull requests await a merge. -- Once the pull request is merged, the next chunk's preflight runs `chunk-pr clean` for the worktree it left, or tells the worker to. -- Under `merge = "human"`, `chunk-pr merge --finish` finishes a plan kept in Jira, or a plan or changelog kept in the config's folder, at once, before the person merges; where the pull request is closed unmerged, the item stays finished. Settle whether loop-claude finishes such an item only after the merge. -- Under loop-claude nobody answers a reviewer's comment on a pull request that awaits a person's merge, since the chunk's run has ended. Settle who does, or say in README that the person asks for it. - -Touches: - -- `bin/forge/commands.py` -- `bin/forge/pulls.py` -- `bin/forge/test_forge.py` -- `bin/release_plan/release_standing.py`: `chunk_item`, `picked`, `pick_from` -- `bin/release_plan/next_chunk.py`: `planned`, `NoItem` (small) -- `bin/release_plan/test_release_standing.py` -- `bin/chunk_preflight/main.py` -- `bin/chunk_preflight/gathered.py`: `Gathered`, `ItemFacts` (small) -- `bin/chunk_preflight/facts.py`: `render`, `item_lines`, `pulls_text` -- `bin/chunk_preflight/choices.py` -- `bin/chunk_preflight/test_chunk_preflight.py` -- `bin/loop_claude/routed_item.py`: `routed_item` -- `bin/loop_claude/loop/chunk_start.py`: `plan_item` -- `bin/loop_claude/test_routed_item.py` -- `bin/loop_claude/loop/test_chunk_start.py` -- `bin/deploy_release/cut.py`: `ready_release` (small) -- `bin/chunk_pr/main.py`: `levelled_and_finished`, `finished` (small) -- `bin/chunk_pr/test_chunk_pr.py` -- `README.md`: `### Set up a project` (small), `## Tools` (small) - ### 450. Add `do-epic --dry-run`, which prints every Jira write planning would make and each chunk that would start, and makes none of them. `do-epic ` writes to Jira before it starts any chunk: labels, sub-tasks, comments on a team's issues and a new backlog order. A person has no way to see those writes before they happen, so the first run on a team's epic is a gamble, and the writes can't be taken back in one step. On TW-13503 the first run would have filed duplicate sub-tasks and posted comments to the team. -- 2.52.0