Add the project setting merge = "human", under which chunk-pr merge leaves the pull request ready and a do-epic chunk parks on your merge

This commit is contained in:
Lilleman
2026-11-19 15:51:44 +01:00
parent 017cf33611
commit e2f5661760
15 changed files with 240 additions and 58 deletions
+10 -2
View File
@@ -12,8 +12,10 @@ WAIT_SECONDS = 90 * 60
PARKS = "CHUNK_PR_PARKS"
def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires."""
def awaited(forge: Forge, wait_for_approval: bool, by_human: bool = False) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`, and never where a person merges the pull request (by_human), who sees its approval themselves. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires."""
if by_human:
return False
if wait_for_approval and forge != "gh":
return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
return wait_for_approval
@@ -52,6 +54,12 @@ def left_to_park(number: str, run: Run) -> Failure:
return unanswered(number, run) or Failure(f"pull request {number} passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments")
def left_to_a_person(number: str, parks: bool) -> str:
"""What merge prints where the project's config leaves the merge of pull request number to a person (`merge = "human"`): what the worker does now, which under PARKS is to end its run, as in `left_to_park`."""
now = "end your run now, since do-epic parks the chunk and resumes this session once it is merged or a reviewer comments." if parks else "leave the merge to them, and report the chunk as ready to merge. Once it is merged, run chunk-pr clean in this worktree."
return f"Marked pull request #{number} ready. It passed its checks and awaits a person's merge, since the project's config sets `merge = \"human\"`: {now}"
def unanswered(number: str, run: Run) -> Failure | None:
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number, as `waiting_threads` finds them, or saying why they cannot be read. None where no thread waits."""
waiting = waiting_threads(number, run)
+24 -7
View File
@@ -47,6 +47,11 @@ merge merges the pull request in its turn: the chunks of one project on this
requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes
a new turn once approved. In a chunk do-epic runs, which sets CHUNK_PR_PARKS=1, it
fails at once instead of waiting: do-epic parks the chunk until the approval comes.
Where the project's config sets `merge = "human"` (`project-config --help`), it does
steps 1 to 4, marks the pull request ready in place of step 5, and prints that the pull
request awaits a person's merge, exit 0. The plan items step 2 finished are commits on
the branch, so they land with that merge. It reads no approval then, whatever
`wait-for-approval` says. Once a person merged it, run clean.
It stops, without merging, and says what to do before running it again:
- on a merge conflict in step 1, naming the conflicted files, with the merge in progress;
- where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a
@@ -86,7 +91,7 @@ import sys
import time
import typing
from chunk_pr.approval import approval, approved, awaited, left_to_park, PARKS, unanswered
from chunk_pr.approval import approval, approved, awaited, left_to_a_person, left_to_park, PARKS, unanswered
from forge.pulls import checks_passed, merged_pull, open_pull, required_checks
from failure import Failure
from forge.commands import Forge, forge_of, gitea, Run, runner
@@ -306,7 +311,7 @@ def finishes_of(given: list[str]) -> list[list[str]] | None:
def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], finishes: typing.Sequence[list[str]] = (), parks: bool = False) -> str | Failure:
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, as `left_to_park` says."""
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, as `left_to_park` says. Where the project's config leaves the merge to a person, the turn ends with the pull request ready, as `left_to_a_person` says."""
found = pull(run)
if isinstance(found, Failure):
return found
@@ -314,7 +319,8 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
loaded = config()
if isinstance(loaded, Failure):
return loaded
waits = awaited(forge, loaded.wait_for_approval)
by_human = loaded.merge == "human"
waits = awaited(forge, loaded.wait_for_approval, by_human)
if isinstance(waits, Failure):
return waits
method = merge_method(forge, run)
@@ -331,10 +337,12 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
if isinstance(absent, Failure):
return absent
file = pathlib.Path(queue[0]) / QUEUE
pull_request = Merging(forge, number, method, str(base), required, waits)
pull_request = Merging(forge, number, method, str(base), required, waits, by_human)
while True:
with turn(file, number, sleep) as untaken:
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
if isinstance(taken, AwaitsMerge):
return left_to_a_person(number, parks) + absent
if not isinstance(taken, AwaitsApproval):
return taken if isinstance(taken, Failure) else taken + absent
if parks:
@@ -347,13 +355,14 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], fini
@dataclasses.dataclass(frozen=True)
class Merging:
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, and whether it waits for an approval."""
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, whether it waits for an approval, and whether a person merges it."""
forge: Forge
number: str
method: str
base: str
required: set[str]
waits: bool
by_human: bool = False
@dataclasses.dataclass(frozen=True)
@@ -361,12 +370,20 @@ class AwaitsApproval:
"""The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one."""
def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | Failure:
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails."""
@dataclasses.dataclass(frozen=True)
class AwaitsMerge:
"""The pull request passed its checks and is marked ready, and the project's config leaves its merge to a person."""
def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | AwaitsMerge | Failure:
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails. A pull request a person merges is marked ready instead: its finished items are commits on its branch, so they reach the default branch with that person's merge."""
head = levelled_and_finished(run, pull_request.base, finishes, config)
checked = head if isinstance(head, Failure) else checks_passed(pull_request.forge, pull_request.number, head, pull_request.required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(checked, Failure):
return checked
if pull_request.by_human:
marked = marked_ready(run, None)
return marked if isinstance(marked, Failure) else AwaitsMerge()
ready = approval(pull_request.number, run) if pull_request.waits else True
if isinstance(ready, Failure):
return ready
+42 -1
View File
@@ -81,7 +81,7 @@ class Checkout:
return failed
texts = {name: str(answer).strip() for name, answer in named.items()}
paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")}
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", merge=texts.get("merge", "chunk"), commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
def __call__(self, command: list[str]) -> str | Failure:
self.ran.append(command)
@@ -360,6 +360,47 @@ class Merge(unittest.TestCase):
checkout.decisions = list(decisions) or ["APPROVED"]
return checkout
def merged_by_a_human(self, origin: str = GITHUB) -> Checkout:
"""A Checkout whose project config sets `merge = "human"`."""
checkout = Checkout(origin, open=True)
checkout.answers[(PROJECT_CONFIG, "merge")] = "human\n"
return checkout
def test_under_a_humans_merge_it_waits_for_the_checks_marks_the_pull_request_ready_and_leaves_it_unmerged(self):
for origin, ready in ((GITHUB, ["gh", "pr", "ready", "12"]), (GITEA, ["tea", "pulls", "edit", "12", "--ready"])):
with self.subTest(origin):
checkout = self.merged_by_a_human(origin)
done = step(["merge"], checkout, checkout.config)
self.assertEqual(done, "Marked pull request #12 ready. It passed its checks and awaits a person's merge, since the project's config sets `merge = \"human\"`: leave the merge to them, and report the chunk as ready to merge. Once it is merged, run chunk-pr clean in this worktree.")
self.assertEqual(checkout.acted()[-1], ready)
self.assertFalse(any("merge" in command[1:4] for command in checkout.acted() if command[0] != "git"), checkout.acted())
def test_under_a_humans_merge_a_chunk_that_parks_is_told_to_end_its_run(self):
checkout = self.merged_by_a_human()
done = merged(checkout, checkout.config, self.fail, parks=True)
self.assertEqual(done, "Marked pull request #12 ready. It passed its checks and awaits a person's merge, since the project's config sets `merge = \"human\"`: end your run now, since do-epic parks the chunk and resumes this session once it is merged or a reviewer comments.")
def test_under_a_humans_merge_a_failed_check_leaves_the_pull_request_as_it_was(self):
checkout = self.merged_by_a_human()
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(changes(checkout), [])
def test_under_a_humans_merge_it_never_reads_the_approval_also_on_gitea(self):
for origin in (GITHUB, GITEA):
with self.subTest(origin):
checkout = self.merged_by_a_human(origin)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertIn("awaits a person's merge", str(step(["merge"], checkout, checkout.config)))
self.assertNotIn(GH_DECISION, checkout.ran)
def test_under_a_humans_merge_the_plan_items_are_finished_on_the_branch_so_they_land_with_the_merge(self):
checkout = self.merged_by_a_human()
done = step(["merge", "--finish", "7", "--no-changelog"], checkout, checkout.config)
self.assertIn("awaits a person's merge", str(done))
self.assertIn([MergeQueue.TODO_ITEM, "finish", "7", "--no-changelog"], checkout.ran)
def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self):
checkout = Checkout(GITHUB, open=True)
checkout.decisions = ["REVIEW_REQUIRED"]
+4 -2
View File
@@ -18,8 +18,10 @@ DRIVER = DO_EPIC
def shipping(config: ProjectConfig) -> str:
"""How a chunk in the repo that config names ships its change. An epic's issue isn't an item of the repo's plan, so `chunk-pr merge --finish`, which adds a finished item's changelog bullet, doesn't apply: the worker writes the bullet itself, where the repo publishes something others consume (docs/decisions.md → `do-epic: drives one Jira epic …`, "Releases")."""
"""How a chunk in the repo that config names ships its change. An epic's issue isn't an item of the repo's plan, so `chunk-pr merge --finish`, which adds a finished item's changelog bullet, doesn't apply: the worker writes the bullet itself, where the repo publishes something others consume. Where the repo's config leaves the merge to a person, the worker is told that its run ends with the pull request ready (docs/decisions.md → `do-epic: drives one Jira epic …`, "Releases")."""
opening = "The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`."
if config.merge == "human":
opening += " The repo's team merges its pull requests itself, so `chunk-pr merge` leaves the pull request ready for a person to merge: end your run when it says so."
if config.epic:
return f"{opening} The repo's plan is a Jira epic, and the history of its issues serves as the changelog, so leave the changelog as it is."
changelog = config.paths["changelog"].relative_to(config.top) if "changelog" in config.paths and config.paths["changelog"].is_relative_to(config.top) else config.places["changelog"]
@@ -53,7 +55,7 @@ NAMES = prompts.RecordNames(
WORKER = prompts.worker_prompts(DRIVER, fresh, "", NAMES)
# What a worker does with a reviewer's feedback, as the decision asks (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
FEEDBACK = 'Where a reviewer left feedback, fix what is reasonable and push the fix, answer each other comment in its thread, and change the setup so our review would have caught the finding (~/.claude/CLAUDE.md → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first"). Then merge the pull request as before.'
FEEDBACK = 'Where a reviewer left feedback, fix what is reasonable and push the fix, answer each other comment in its thread, and change the setup so our review would have caught the finding (~/.claude/CLAUDE.md → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first"). Then merge the pull request as before. Where the pull request is merged, run `chunk-pr clean` in its worktree and finish the chunk.'
def unparked(news: str) -> WorkerPrompts:
+8 -5
View File
@@ -1,6 +1,6 @@
"""What the pull request of a do-epic chunk waits on, read once from its forge (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
A gate is something only time or a person passes: checks that still run, an approval a reviewer has yet to give, or the new review of a reviewer whose requested changes the worker answered. While a chunk's pull request waits on one, its worker doesn't have anything to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on."""
A gate is something only time or a person passes: checks that still run, an approval a reviewer has yet to give, the new review of a reviewer whose requested changes the worker answered, or the merge itself, where the project's config leaves it to a person. While a chunk's pull request waits on one, its worker doesn't have anything to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on."""
import dataclasses
import typing
@@ -13,6 +13,7 @@ from forge.commands import forge_of, Run
CHECKS = "its checks"
APPROVAL = "an approval"
NEW_REVIEW = "a new review"
MERGE = "your merge"
@dataclasses.dataclass(frozen=True)
@@ -22,7 +23,7 @@ class Gate:
worktree: str
# The pull request's number.
pull: str
# CHECKS, APPROVAL or NEW_REVIEW.
# CHECKS, APPROVAL, NEW_REVIEW or MERGE.
on: str
@@ -33,10 +34,10 @@ class Open:
news: str
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | Open | Failure:
"""What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder. A Failure where git or the forge cannot be read, which doesn't say anything about the gate.
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human: bool = False) -> Gate | Open | Failure:
"""What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder, and by_human says the project's config leaves the merge to a person (`merge = "human"`). A Failure where git or the forge cannot be read, which doesn't say anything about the gate.
A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`forge.reviews.answered`); from then on the pull request awaits a new review.
A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`forge.reviews.answered`); from then on the pull request awaits a new review. Where a person merges, a pull request with nothing else to wait on awaits that merge, and the chunk has news again once it is merged, when it is no longer open.
"""
worktree = worktree_of(branch, at(checkout))
if not isinstance(worktree, str):
@@ -71,6 +72,8 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate |
return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}")
if decision in (ANSWERED, REVIEW_REQUIRED):
return Gate(worktree, pull, NEW_REVIEW if decision == ANSWERED else APPROVAL)
if by_human:
return Gate(worktree, pull, MERGE)
return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == APPROVED else ""))
+63 -32
View File
@@ -56,7 +56,8 @@ A repo takes as many chunks as its `parallel-chunks`, and none while loop-claude
A chunk whose worker ends its run while its pull request waits on its checks, an approval or a new review
is parked: it frees its place for the next chunk, and its window's name says what it awaits. Its worker goes
on once the checks pass, the approval comes or a reviewer comments, and a place is free; until one is, the
name says `awaits a slot`. A parked chunk survives a reboot: run do-epic <EPIC-KEY> again to go on polling.
name says `awaits a slot`. In a repo whose config sets `merge = "human"`, a chunk never merges: its pull
request, ready and with nothing else to wait on, `awaits your merge`, and its worker goes on once you merged it. A parked chunk survives a reboot: run do-epic <EPIC-KEY> again to go on polling.
--status doesn't start any chunk. It prints a line per open issue: that its chunk runs or asks you a question, or why it waits, such as the gate a parked chunk awaits and since when.
{findings.HELP}
{finish.HELP}
@@ -290,46 +291,76 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, starts: bool) -> str |
recorded_as = parked.parked_chunks(folder)
if isinstance(recorded_as, Failure):
return Stop(1, recorded_as.reason)
if starts and key not in recorded_as:
config = config_located(loop.root, epic.paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
poll = Poll(key, repo, config.merge == "human", folder, loop, epic)
if key in recorded_as:
return resumed_news(poll, recorded_as[key].on, shown=None)
entered = None if starts else poll.gate()
if not isinstance(entered, gates.Gate):
if isinstance(entered, Failure):
say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {entered.reason}", epic.effects, stdout=True)
return ""
# What the chunk is parked on; None while it isn't parked.
on = recorded_as[key].on if key in recorded_as else None
# What the window's name says the chunk awaits, and the last reason said for staying parked.
shown = said = None
if failed := poll.record(entered):
return Stop(1, failed.reason)
tmux.park(loop.window, entered.on, epic.effects.tmux)
# Once the window shows as parked, so the chunks that start count it as running nowhere.
issues = epic.store.read()
started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key)
say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
epic.effects.sleep(POLL_SECONDS)
return resumed_news(poll, entered.on, shown=entered.on)
@dataclasses.dataclass(frozen=True)
class Poll:
"""What each read of a parked chunk's gate needs: the chunk's key, the repo its work is in, whether a person merges its pull request, the folder of the epic's parked chunks, and the chunk's loop and epic."""
key: str
repo: str
by_human: bool
folder: pathlib.Path
loop: Loop
epic: EpicRun
def gate(self) -> gates.Gate | gates.Open | Failure:
return gates.gate(self.key, self.loop.root, self.epic.forge_at, self.by_human)
def record(self, gate: gates.Gate) -> Failure | None:
"""Writes the chunk's file as parked on gate, and says so."""
failed = parked.park(self.folder, parked.Parked(self.key, gate.worktree, gate.pull, str(self.loop.session.id), gate.on))
if failed is None:
say(f"parked: pull request #{gate.pull} awaits {gate.on}", self.epic.effects, stdout=True)
return failed
def resumed_news(poll: Poll, on: str, shown: str | None) -> str | Stop:
"""Reads the gate of the parked chunk every POLL_SECONDS until its worker has something to do and a running slot is free, then removes its file: what to tell that worker. on is the gate the chunk's file says it is parked on, and shown what its window's name says it awaits, None where nothing yet. A gate that cannot be read leaves the chunk parked as it was."""
# The last reason said for staying parked.
said = None
while True:
now = gates.gate(key, loop.root, epic.forge_at)
if on is None and not isinstance(now, gates.Gate):
if isinstance(now, Failure):
say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {now.reason}", epic.effects, stdout=True)
return ""
stays = None
if isinstance(now, gates.Gate) and now.on != on:
failed = parked.park(folder, parked.Parked(key, now.worktree, now.pull, str(loop.session.id), now.on))
if failed is not None:
return Stop(1, failed.reason)
say(f"parked: pull request #{now.pull} awaits {now.on}", epic.effects, stdout=True)
now = poll.gate()
if isinstance(now, gates.Gate):
awaits, stays = now.on, None
if now.on != on:
if failed := poll.record(now):
return Stop(1, failed.reason)
on = now.on
elif isinstance(now, Failure):
stays = f"cannot read the gate: {now.reason}"
elif isinstance(now, gates.Open):
full = resumed(repo, loop, epic)
awaits, stays = shown or on, f"cannot read the gate: {now.reason}"
else:
full = resumed(poll.repo, poll.loop, poll.epic)
if full is None:
failed = parked.unpark(folder, key)
failed = parked.unpark(poll.folder, poll.key)
return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {on}. It resumes now: {now.news}."
stays = f"{now.news}, but the chunk stays parked: {full}"
awaits = parked.SLOT if isinstance(now, gates.Open) else now.on if isinstance(now, gates.Gate) else shown or on
awaits, stays = parked.SLOT, f"{now.news}, but the chunk stays parked: {full}"
if awaits != shown:
tmux.park(loop.window, str(awaits), epic.effects.tmux)
tmux.park(poll.loop.window, awaits, poll.epic.effects.tmux)
shown = awaits
if on is None:
# Once the window shows as parked, so the chunks that start count it as running nowhere.
issues = epic.store.read()
started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key)
say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
on = now.on if isinstance(now, gates.Gate) else on
if stays is not None and stays != said:
say(f"{stays}; trying again every {POLL_SECONDS} seconds", epic.effects, stdout=True)
say(f"{stays}; trying again every {POLL_SECONDS} seconds", poll.epic.effects, stdout=True)
said = stays
epic.effects.sleep(POLL_SECONDS)
poll.epic.effects.sleep(POLL_SECONDS)
# How the news for a chunk that was parked opens.
+1 -1
View File
@@ -24,7 +24,7 @@ class Parked:
pull: str
# The ID of its worker's claude session, which `claude --resume` takes.
session: str
# What its pull request waits on, as the words after "awaits" (`gates.CHECKS`, `gates.APPROVAL`, `gates.NEW_REVIEW`).
# What its pull request waits on, as the words after "awaits" (`gates.CHECKS`, `gates.APPROVAL`, `gates.NEW_REVIEW`, `gates.MERGE`).
on: str
def waits(self, shown: str) -> str:
+16 -3
View File
@@ -5,7 +5,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.gates import APPROVAL, CHECKS, gate, Gate, NEW_REVIEW, Open
from do_epic.gates import APPROVAL, CHECKS, gate, Gate, MERGE, NEW_REVIEW, Open
from failure import Failure
WORKTREES = "worktree /code/billing\nHEAD aaa\nbranch refs/heads/main\n\nworktree /code/billing-ABC-21\nHEAD abc\nbranch refs/heads/ABC-21\n"
@@ -58,8 +58,8 @@ class Forge:
return Failure(f"{key} failed") if self.fails and key.startswith(self.fails) else self.answers[key]
return run
def gate(self) -> Gate | Open | Failure:
return gate("ABC-21", "/code/billing", self.at)
def gate(self, by_human: bool = False) -> Gate | Open | Failure:
return gate("ABC-21", "/code/billing", self.at, by_human)
class GateOfAChunk(unittest.TestCase):
@@ -72,6 +72,19 @@ class GateOfAChunk(unittest.TestCase):
self.assertIn(["gh", "pr", "checks", "7", "--json", "bucket"], forge.commands)
self.assertTrue(any(command[:3] == ["gh", "api", "graphql"] and "number=7" in command for command in forge.commands), forge.commands)
def test_where_a_person_merges_a_pull_request_with_nothing_else_to_wait_on_awaits_that_merge(self):
gitea = "https://gitea.larvit.se/o/billing.git"
for forge in (Forge(decision="APPROVED"), Forge(decision=""), Forge(gitea)):
with self.subTest(forge.answers["git remote"]):
self.assertEqual(forge.gate(by_human=True), Gate("/code/billing-ABC-21", "7", MERGE))
self.assertEqual(MERGE, "your merge")
def test_where_a_person_merges_every_other_gate_and_all_news_stay_as_they_are(self):
same = (Forge(), Forge(buckets=("pending",)), Forge(draft=True), Forge(decision="CHANGES_REQUESTED"), Forge(threads=(thread(False, "reviewer"),)), Forge(buckets=("fail",)), Forge(pulls=""))
for forge in same:
with self.subTest(forge.answers):
self.assertEqual(forge.gate(by_human=True), forge.gate())
def test_a_review_decision_gh_prints_in_no_known_shape_is_a_failure(self):
forge = Forge()
forge.answers["gh pr view"] = "[1]"
+21 -1
View File
@@ -655,7 +655,7 @@ def awaiting(**answers: object) -> Forge:
class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
def setUp(self) -> None:
super().setUp()
self.repo_chunk()
self.repo_config = self.repo_chunk() / "config.toml"
self.issues.append(issue("ABC-22", "do-epic-claude"))
self.file = parked.file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20")
self.session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts)
@@ -684,6 +684,26 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
shown = [args for args in fake.tmux_calls if args[0] == "rename-window" or tmux.ROOT in args and "%1" in args]
self.assertEqual(shown, [["rename-window", "-t", "%1", "ABC-20 awaits an approval"], ["rename-window", "-t", "%1", "ABC-20"], ["set-option", "-w", "-t", "%1", tmux.ROOT, checkout]])
def test_where_a_person_merges_it_parks_on_that_merge_and_works_again_once_merged(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(), awaiting(decision="APPROVED"), awaiting(pulls="")]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("parked: pull request #7 awaits an approval\nstarted ABC-22\nparked: pull request #7 awaits your merge\n", out)
self.assertIn("leaves the pull request ready for a person to merge", prompts[0])
self.assertTrue(prompts[1].startswith(f"do-epic parked the chunk while its pull request awaited your merge. It resumes now: no pull request from origin's ABC-20 is open at abcabcabcabc; it may be merged or closed already. {chunk_prompt.FEEDBACK}\n\n"), prompts[1])
self.assertIn("Where the pull request is merged, run `chunk-pr clean`", chunk_prompt.FEEDBACK)
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20 awaits your merge", "ABC-20"])
self.assertFalse(self.file.exists())
def test_where_the_chunk_merges_an_approved_pull_request_parks_no_chunk(self) -> None:
self.forges = [awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertNotIn("parked: ", out)
def test_an_unfinished_chunk_parks_too_and_a_reviewers_comment_resumes_it(self) -> None:
self.forges = [awaiting(buckets=("pending",)), awaiting(), awaiting(threads=({"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": "reviewer"}}]}},))]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW + "ABC-22\t1\t@10\n")
+6 -1
View File
@@ -94,6 +94,11 @@ approval of the pull request, as its branch protection requires on GitHub, befor
false. `project-config wait-for-approval` prints true or false; the full listing shows the setting only where
it is true.
`merge` is an optional setting, "chunk" or "human": who merges a chunk's pull request. Left out, it is
"chunk": `chunk-pr merge` merges it. Under "human", for a team whose rules keep the merge with a person,
`chunk-pr merge` leaves the pull request ready and says it awaits a person's merge. `project-config merge`
prints chunk or human; the full listing shows the setting only where it is human.
`tooling-on-host` is an optional setting, true or false: whether the loop may run the project's language
runtime, package manager, tests and task runner directly on the host, for a project with no container
setup. Left out, it is false, and they run through the project's container setup.
@@ -142,7 +147,7 @@ and its commits and pull request are titled "ABC-123 - …".
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
setting, names an unknown one, misspells a path, a language or a template, sets `coding-conventions` to anything but a list of paths, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
`tooling-on-host` to anything but true or false, sets `merge` to anything but chunk or human, sets `notifier` to anything but mattermost or slack or
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
without a `plan` in Jira, names a Jira `plan` and leaves out `jira-score-formula` or `jira-score-bar`, sets
one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything
+10
View File
@@ -33,6 +33,10 @@ Notifier = typing.Literal["mattermost", "slack"]
NOTIFIERS: tuple[Notifier, ...] = typing.get_args(Notifier)
# An optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
WAIT_FOR_APPROVAL = "wait-for-approval"
# An optional setting: who merges a chunk's pull request, one of MERGERS. The chunk does where it is left out; under "human", `chunk-pr merge` leaves the pull request ready for a person to merge, for a team whose rules keep the merge with a person.
MERGE = "merge"
Merger = typing.Literal["chunk", "human"]
MERGERS: tuple[Merger, ...] = typing.get_args(Merger)
# An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out.
TOOLING_ON_HOST = "tooling-on-host"
# An optional number setting: the comprehension score under which code health is very important. A legacy project, whose code scores low, may lower it.
@@ -124,6 +128,7 @@ class ProjectConfig:
# The config's `env-file`, or None where it sets none.
env_file: pathlib.Path | None = None
wait_for_approval: bool = False
merge: Merger = "chunk"
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
parallel_chunks: int = 1
@@ -265,6 +270,10 @@ def parallel_read(value: object) -> int | Unfit:
return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`")
def merger_read(value: object) -> Merger | Unfit:
return next((name for name in MERGERS if name == value), None) or Unfit(f"not {' or '.join(f'"{name}"' for name in MERGERS)}")
def notifier_read(value: object) -> Notifier | Unfit:
return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}")
@@ -341,6 +350,7 @@ def language_fault(value: object) -> str | None:
# Each one-value setting, in the order `project-config` lists them.
SCALARS = (
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
Scalar(MERGE, "merge", merger_read),
Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"),
Scalar(READABILITY_FLOOR, "readability_floor", floor_read),
Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read),
+30 -1
View File
@@ -390,6 +390,27 @@ class LoadTest(ConfigCase):
(folder / "config.toml").write_text(CLIENT + f"coding-conventions = {value}\n", encoding="utf-8")
self.assertIn(f"`coding-conventions` is {shown}, not a list of paths, each \"checkout:<path>\"", self.failure())
def test_merge_is_chunk_where_left_out_and_takes_human(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertEqual(left_out.merge, "chunk")
for spelled in ("chunk", "human"):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f'merge = "{spelled}"\n')
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.merge, spelled)
def test_a_merge_that_is_neither_chunk_nor_human_fails_naming_it(self) -> None:
folder = self.write("acme", CLIENT)
for spelled in ('"person"', "true"):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"merge = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn(f'`merge` is {spelled.strip(chr(34)) if spelled == "true" else repr(spelled.strip(chr(34)))}, not "chunk" or "human"'.replace("true", "True"), found.reason)
def test_wait_for_approval_is_an_optional_boolean_that_is_false_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -506,7 +527,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, coding-conventions, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, coding-conventions, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, merge, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -685,6 +706,14 @@ class ToolTest(ConfigCase):
self.assertEqual((self.run_tool("jira-score-formula").stdout, self.run_tool("jira-score-bar").stdout), ("100 * V / (2**S + 8)\n", "0.5\n"))
self.assertIn("jira-score-formula: 100 * V / (2**S + 8)\njira-score-bar: 0.5\n", self.run_tool().stdout)
def test_prints_who_merges_and_lists_it_only_where_a_human_does(self) -> None:
folder = self.write("acme", CLIENT)
self.assertEqual(self.run_tool("merge").stdout, "chunk\n")
self.assertNotIn("merge", self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + 'merge = "human"\n')
self.assertEqual(self.run_tool("merge").stdout, "human\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "merge: human")
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
folder = self.write("acme", CLIENT)
left_out = self.run_tool("wait-for-approval")