Answer stability round 1: 1 🔴, 5 🟡 (0 misread); hold a pull request's base on the forge to the recorded one, ask origin for the epic branch, and name where a chunk's work landed
CI / tests (pull_request) Successful in 3m46s

This commit is contained in:
Lilleman
2026-11-20 21:42:32 +01:00
parent 525f3f8836
commit d464f271bf
13 changed files with 352 additions and 74 deletions
+6 -5
View File
@@ -5,7 +5,7 @@ import dataclasses
import typing
from forge.reviews import ANSWERED, APPROVED, CHANGES_REQUESTED, review_decision, REVIEW_REQUIRED, waiting_threads
from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks, unmergeable
from forge.pulls import CheckFailed, checks_now, open_pull, other_base, Pending, required_checks, unmergeable
from git_cli.git_repo import CHUNK_BASE
from failure import Failure
from forge.commands import forge_of, Run
@@ -46,7 +46,7 @@ class Unmergeable(Open):
def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human: bool) -> 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.
"""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 Failure too where the forge merges the pull request into another branch than the checkout takes as its base (`forge.pulls.other_base`): the caller chose by_human from that base.
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. The chunk has news again once the pull request is no longer open. It has news too once the pull request no longer merges into its base as it stands (`forge.pulls.unmergeable`): the worker then levels the branch for that person.
"""
@@ -58,10 +58,10 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
failed = next((answer for answer in read if isinstance(answer, Failure)), None)
if failed is not None:
return failed
origin, head, base = (str(answer).strip() for answer in read)
origin, head, default = (str(answer).strip() for answer in read)
# A chunk of an epic that keeps a working branch merges into that branch, so its protection names the checks.
epic_base = run(["git", "config", "--get", f"branch.{branch}.{CHUNK_BASE}"])
base = base if isinstance(epic_base, Failure) or not epic_base.strip() else epic_base.strip()
base = default.removeprefix("origin/") if isinstance(epic_base, Failure) or not epic_base.strip() else epic_base.strip()
forge = forge_of(origin)
pull = open_pull(forge, branch, head, run)
if not isinstance(pull, str):
@@ -69,7 +69,8 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run], by_human:
decision = review_decision(forge, pull, head, run)
if not isinstance(decision, str):
return decision or Open(f"pull request #{pull} is a draft")
required = required_checks(forge, base.removeprefix("origin/"), run)
# do-epic takes the base as saying who merges, so the forge must merge the pull request into it too.
required = other_base(forge, pull, base, run) or required_checks(forge, base, run)
checks = required if isinstance(required, Failure) else checks_now(forge, pull, head, required, run)
if isinstance(checks, CheckFailed):
return Open(f"{checks.reason}; fix it and push")
+29 -16
View File
@@ -4,6 +4,7 @@
After each cycle of a chunk in a repo, the window reads what the chunk's pull request waits on (`gates`). While that is a gate only time or a person passes, the chunk is parked (`parked`): the window frees its running slot and polls the forge, and the chunk's next cycle starts once the worker has something to do and a slot is free. `do-epic <EPIC-KEY> --status` prints what each open issue does."""
import dataclasses
import enum
import pathlib
import sys
import typing
@@ -79,6 +80,8 @@ STATUS_FLAG = "--status"
DRY_RUN_FLAG = "--dry-run"
# How often a parked chunk reads its pull request's gate, and a human task's window reads the epic: a person answers in hours, and each read is a few calls.
POLL_SECONDS = 60
# A call to origin that levels an epic's working branch is stopped after this long, chunk-preflight's limit for the same calls: one that hangs would hold the chunk's running slot before any cycle, with nothing said.
LEVEL_SECONDS = 60
# The store of an epic's issues and its record, for the epic with this key.
Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]]
@@ -304,7 +307,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
return issue
if issue and isinstance(recorded(issue, epic.config.label_repos), HumanTask):
human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, epic.config.unblocking, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects)
return handed_on(key, epic, humans=True)
return handed_on(key, epic, Landed.WITH_A_HUMAN)
place = chunk_root(key, issue, epic)
if isinstance(place, Stop):
return place
@@ -321,7 +324,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects)
run = ChunkRun()
# What a chunk that was parked is told as it resumes; empty for a chunk that wasn't.
news = parked_through(repo, loop, epic, told=None, finished=False) if repo is not None else ""
news = parked_through(repo, loop, epic, told=None, finished=False, based=based) if repo is not None else ""
while True:
if isinstance(news, Stop):
return news
@@ -339,10 +342,10 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
if isinstance(closed, Stop):
return closed
run = closed
news = parked_through(repo, loop, epic, told=news, finished=isinstance(concluded.verdict, Finished)) if repo is not None else ""
news = parked_through(repo, loop, epic, told=news, finished=isinstance(concluded.verdict, Finished), based=based) if repo is not None else ""
# A chunk that was parked has work again, whatever the judge ruled before its pull request passed the gate.
if isinstance(concluded.verdict, Finished) and news == "":
return handed_on(key, epic, repo is not None, to_epic_branch=based is not None)
return handed_on(key, epic, Landed.ON_EPIC_BRANCH if based is not None else Landed.ON_DEFAULT_BRANCH if repo is not None else Landed.NOWHERE)
def epic_based(key: str, root: str, epic: EpicRun) -> str | None | Stop:
@@ -354,7 +357,7 @@ def epic_based(key: str, root: str, epic: EpicRun) -> str | None | Stop:
return None
branch = templates.epic_branch(config.epic_branch, epic.key)
default = epic.effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=root)
level = default if isinstance(default, Failure) else epic_branch.levelled(branch, default.strip(), cwd=root, run=epic.effects.git)
level = default if isinstance(default, Failure) else epic_branch.levelled(branch, default.strip(), cwd=root, timeout=LEVEL_SECONDS, run=epic.effects.git)
readied = level if isinstance(level, Failure) else record_chunk_base(key, branch, cwd=root, run=epic.effects.git)
if isinstance(readied, Failure):
return Stop(1, f"cannot ready the epic's working branch {branch} in {root} for {key}: {readied.reason}; once that is settled, run `do-epic {epic.key}` to start the chunk again")
@@ -371,8 +374,8 @@ def issue_started(key: str, epic: EpicRun) -> None:
say(f"{key} stays assigned to {other}", epic.effects, stdout=True)
def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool) -> str | Stop:
"""Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh.
def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finished: bool, based: str | None) -> str | Stop:
"""Keeps the chunk in loop's window parked. Its work is in the repo called repo. It stays parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. told is the news its last cycle's worker got, None where the window just started, and finished says the judge ruled the chunk finished. based is the epic's working branch that `epic_based` recorded as the chunk's base when the window started, None where it recorded none. A window that just started parks the chunk only if its file says so: the forge isn't read for a chunk that starts afresh.
Where a person merges, a worker ends its run with the pull request open, so the judge may rule the chunk finished before it is. For such a finished chunk, a gate that cannot be read is read again until it can, and a pull request no longer open, in a worktree that still stands, is news the worker hasn't been told: the worker removes the worktree. A pull request that doesn't merge into its base is news after every cycle that leaves it so: the worker levels the branch.
@@ -385,8 +388,8 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis
config = config_located(loop.root, epic.paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
# A pull request into an epic's working branch merges without a person, whatever `merge` says.
poll = Poll(key, repo, config.merge == "human" and config.epic_branch is None, folder, loop, epic)
# A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere.
poll = Poll(key, repo, config.merge == "human" and based is None, folder, loop, epic)
if key in recorded_as:
return resumed_news(poll, recorded_as[key].on, shown=None)
entered = None if told is None else poll.first_gate(again=finished)
@@ -401,7 +404,7 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis
return "" if uncleaned in (told or "") else uncleaned
if failed := poll.record(entered):
return Stop(1, failed.reason)
if config.epic_branch is not None and (status := epic.config.pull_open_status):
if based is not None and (status := epic.config.pull_open_status):
# The team's automation moves an issue only from a pull request into the default branch.
if isinstance(moved := epic.store.move_issue(key, status), Failure):
say(f"{key} did not move to {status!r} though its pull request is open: {moved.reason}", epic.effects, stdout=True)
@@ -520,13 +523,23 @@ def folder_made(root: str) -> Failure | None:
return None
def handed_on(key: str, epic: EpicRun, in_repo: bool = False, humans: bool = False, to_epic_branch: bool = False) -> Stop:
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk in a repo, which in_repo marks, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task, which humans marks: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch, which to_epic_branch marks: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits."""
class Landed(enum.Enum):
"""Where a finished chunk's work went, which decides who moves its issue."""
# No repo took it, as for the epic's finishing and a chunk that changes none.
NOWHERE = enum.auto()
# A human did the task.
WITH_A_HUMAN = enum.auto()
ON_DEFAULT_BRANCH = enum.auto()
ON_EPIC_BRANCH = enum.auto()
def handed_on(key: str, epic: EpicRun, landed: Landed = Landed.NOWHERE) -> Stop:
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Where the team's automation moves issues, others move two kinds of issue. The automation moves the issue of a chunk whose work landed on the default branch, from its pull request: the stop waits for that move (`moved_by_automation`). The human moves their own task: the stop doesn't move or await anything. A chunk without a repo has no pull request, so its issue moves to done as ever, and so does a split item, once Jira counts each of its sub-tasks done. The automation doesn't see a pull request that merged into an epic's working branch: the stop moves that chunk's issue to the status `jira-pull-request-merged-status` names. Where none is named, it moves the issue to done, or stops where the automation moves issues, since then nobody would move it. do-epic's window closes as it exits."""
automated = epic.config.automation_moves
# The epic's finishing has no issue to move: the epic is closed by `--close-epic`. Nor has a human's task where the human moves it: its window waited until it holds up no issue.
if key == epic.key or (humans and automated):
if key == epic.key or (landed is Landed.WITH_A_HUMAN and automated):
issues: list[EpicIssue] | Failure = epic.store.read()
elif to_epic_branch and (status := epic.config.pull_merged_status):
elif landed is Landed.ON_EPIC_BRANCH and (status := epic.config.pull_merged_status):
moved = epic.store.move_issue(key, status)
# A chunk that never parked left its issue before the open status, from which a workflow may offer no way to the merged one.
if isinstance(moved, Failure) and (opened := epic.config.pull_open_status) and not isinstance(epic.store.move_issue(key, opened), Failure):
@@ -536,9 +549,9 @@ def handed_on(key: str, epic: EpicRun, in_repo: bool = False, humans: bool = Fal
issues = epic.store.read()
# A search may not show the move yet, so the issue counts as moved here whatever the read says.
issues = issues if isinstance(issues, Failure) else [dataclasses.replace(each, status=status) if each.key == key else each for each in issues]
elif to_epic_branch and automated:
elif landed is Landed.ON_EPIC_BRANCH and automated:
return Stop(1, f"the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `{PULL_MERGED_STATUS}` to move it to. Move {key} in Jira, then run `do-epic {epic.key}` to start the chunks it blocks")
elif in_repo and automated:
elif landed is Landed.ON_DEFAULT_BRANCH and automated:
issues = moved_by_automation(key, epic)
else:
moved = epic.store.finish_issue(key)
+14 -4
View File
@@ -28,7 +28,7 @@ def comment(by: str, at: str) -> dict:
class Forge:
"""Stands in for git and the forge's CLI in the checkout and the chunk's worktree; `ran` holds each folder a command ran in. Only the CLI of origin's forge answers: `gh` fails on a Gitea origin, and `tea` on a GitHub one."""
def __init__(self, origin: str = "git@github.com:o/billing.git", pulls: str = f"7\t{HEAD}\tfalse\n", draft: bool = False, decision: str = "REVIEW_REQUIRED", buckets: tuple[str, ...] = ("pass",), threads: tuple[dict, ...] = (), status: str = '{"state": "success", "total_count": 1}', mergeable: str = "MERGEABLE", merge_state: str = "CLEAN", worktrees: str = WORKTREES, fails: str = "", reviews: tuple[dict, ...] = (), comments: tuple[dict, ...] = (), title: str = "Add x") -> None:
def __init__(self, origin: str = "git@github.com:o/billing.git", pulls: str = f"7\t{HEAD}\tfalse\n", draft: bool = False, decision: str = "REVIEW_REQUIRED", buckets: tuple[str, ...] = ("pass",), threads: tuple[dict, ...] = (), status: str = '{"state": "success", "total_count": 1}', mergeable: str = "MERGEABLE", merge_state: str = "CLEAN", worktrees: str = WORKTREES, fails: str = "", reviews: tuple[dict, ...] = (), comments: tuple[dict, ...] = (), title: str = "Add x", base: str = "main") -> None:
self.cli = "gh" if "github.com" in origin else "tea"
self.ran: list[str] = []
self.commands: list[list[str]] = []
@@ -40,11 +40,11 @@ class Forge:
"git symbolic-ref": "origin/main\n",
"git config": Failure("git config: unset"),
"gh pr list": pulls,
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments), "mergeable": mergeable, "mergeStateStatus": merge_state}),
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments), "mergeable": mergeable, "mergeStateStatus": merge_state, "baseRefName": base}),
"gh pr checks": json.dumps([{"bucket": bucket} for bucket in buckets]),
"gh api graphql": json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": list(threads)}}}}}),
"tea api repos/{owner}/{repo}/pulls?state=open&limit=50": json.dumps([{"number": 7, "merged": False, "head": {"label": "ABC-21", "sha": HEAD, "repo": {"full_name": "o/billing"}}, "base": {"repo": {"full_name": "o/billing"}}}]),
"tea api repos/{owner}/{repo}/pulls/7": json.dumps({"number": 7, "title": title, "mergeable": mergeable == "MERGEABLE"}),
"tea api repos/{owner}/{repo}/pulls/7": json.dumps({"number": 7, "title": title, "mergeable": mergeable == "MERGEABLE", "base": {"ref": base}}),
"tea api repos/{owner}/{repo}/branches/main": '{"name": "main"}',
"tea api repos/{owner}/{repo}/commits/" + HEAD + "/status": status,
}
@@ -122,13 +122,23 @@ class GateOfAChunk(unittest.TestCase):
self.assertEqual(Forge(gitea).gate(), Open("pull request #7 passed its checks"))
def test_a_chunk_that_merges_into_an_epics_working_branch_reads_the_checks_that_branch_requires(self):
forge = Forge("https://gitea.larvit.se/o/billing.git")
forge = Forge("https://gitea.larvit.se/o/billing.git", base="ABC-12")
forge.answers["git config"] = "ABC-12\n"
forge.answers["tea api repos/{owner}/{repo}/branches/ABC-12"] = '{"enable_status_check": true, "status_check_contexts": ["epic-gate"]}'
self.assertEqual(forge.gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
self.assertIn(["git", "config", "--get", "branch.ABC-21.chunk-base"], forge.commands)
self.assertNotIn(["tea", "api", "repos/{owner}/{repo}/branches/main"], forge.commands)
def test_a_pull_request_the_forge_merges_into_another_branch_than_the_checkout_records_is_a_failure_naming_both(self):
differs = "pull request #7 merges into {} on the forge, but this checkout takes {} as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config"
for origin in ("git@github.com:o/billing.git", "https://gitea.larvit.se/o/billing.git"):
with self.subTest(origin):
recorded = Forge(origin, decision="APPROVED")
recorded.answers["git config"] = "ABC-12\n"
self.assertEqual(recorded.gate(by_human=False), Failure(differs.format("main", "ABC-12")), "no pull request into the default branch reads as one that merges without a person")
self.assertNotIn(["tea", "api", "repos/{owner}/{repo}/branches/ABC-12"], recorded.commands)
self.assertEqual(Forge(origin, decision="APPROVED", base="ABC-12").gate(by_human=True), Failure(differs.format("ABC-12", "main")))
def test_a_gitea_draft_awaits_nothing_though_its_checks_run(self):
gitea = "https://gitea.larvit.se/o/billing.git"
for title in ("WIP: Add x", "[wip] Add x"):
+56 -12
View File
@@ -1024,28 +1024,40 @@ class AnEpicsWorkingBranch(DoEpicTest):
self.store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
self.backend = lambda config, key: (self.store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.git_calls: list[tuple[tuple[str, ...], str | None]] = []
self.git_timeouts: list[tuple[str, object]] = []
def settings(self, more: str) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8")
def with_git(self, fake: FakeEffects, **answers: str | Failure) -> FakeEffects:
"""fake, whose git answers each command by its first word: as answers has it, else as a checkout whose origin has the branch ABC-12, which holds origin/main."""
answered = {"symbolic-ref": "origin/main\n", "fetch": "", "rev-parse": "aaa\n", "rev-list": "0\n", "config": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
answered = {"symbolic-ref": "origin/main\n", "fetch": "", "ls-remote": "aaa\trefs/heads/ABC-12\n", "rev-parse": "aaa\n", "rev-list": "0\n", "config": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def git(*args: str, cwd: str | None = None, **more: object) -> str | Failure:
self.git_calls.append((args, cwd))
self.git_timeouts.append((args[0], more.get("timeout")))
return answered.get(args[0], Failure("no git"))
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, git=git) # type: ignore[method-assign]
return fake
def recorded(self, **answers: object) -> Forge:
"""A forge like `awaiting`'s, in a checkout that records ABC-12 as the base of ABC-20's branch."""
forge = awaiting(**answers)
forge.answers["git config"] = "ABC-12\n"
return forge
def test_a_chunk_that_starts_levels_the_branch_and_records_it_as_the_chunks_base(self) -> None:
fake = self.with_git(FakeEffects())
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.epic_based("ABC-20", self.checkout, self.epic_run(fake)), "ABC-12")
self.assertEqual(self.git_calls, [(args, self.checkout) for args in (("symbolic-ref", "--short", "refs/remotes/origin/HEAD"), ("fetch", "--quiet", "origin"), ("rev-parse", "--quiet", "--verify", "refs/remotes/origin/ABC-12"), ("rev-list", "--count", "origin/ABC-12..origin/main"), ("config", "branch.ABC-20.chunk-base", "ABC-12"))])
self.assertEqual(self.git_calls, [(args, self.checkout) for args in (("symbolic-ref", "--short", "refs/remotes/origin/HEAD"), ("fetch", "--quiet", "origin"), ("ls-remote", "--heads", "origin", "refs/heads/ABC-12"), ("rev-list", "--count", "origin/ABC-12..origin/main"), ("config", "branch.ABC-20.chunk-base", "ABC-12"))])
self.assertIn("origin/ABC-12 already holds origin/main; ABC-20's pull request goes into ABC-12\n", out.getvalue())
def test_a_call_to_origin_that_levels_the_branch_is_stopped_after_a_minute_so_no_window_hangs_before_its_first_cycle(self) -> None:
main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), ls_remote="", push="")))
self.assertEqual([timed for timed in self.git_timeouts if timed[0] in ("fetch", "ls-remote", "push")], [("fetch", 60), ("ls-remote", 60), ("push", 60), ("fetch", 60)])
def test_says_the_default_branchs_whole_name_however_it_ends(self) -> None:
out = io.StringIO()
with contextlib.redirect_stdout(out):
@@ -1083,7 +1095,7 @@ class AnEpicsWorkingBranch(DoEpicTest):
def test_its_issue_moves_as_the_pull_request_opens_and_merges_and_no_person_merges_it(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.forges = [awaiting(), awaiting(), awaiting(decision="APPROVED")]
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
@@ -1097,10 +1109,42 @@ class AnEpicsWorkingBranch(DoEpicTest):
self.assertIn("The chunk's pull request goes into the epic's working branch `ABC-12`", prompts[0])
self.assertIn(("config", "branch.ABC-20.chunk-base", "ABC-12"), [args for args, _ in self.git_calls])
def test_a_chunk_parked_on_a_persons_merge_into_the_default_branch_stays_parked_until_its_pull_request_goes_into_the_branch(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts)
parked.park(self.home / ".local/state/do-epic/ABC-12", parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(session.id), "your merge"))
self.worker()(["--session-id", str(session.id)])
# The pull request was opened into main before the setting was on; a person then changes its base to ABC-12.
self.forges = [self.recorded(decision="APPROVED"), self.recorded(decision="APPROVED"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker()], claude=[judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
self.assertEqual(code, 0, err)
self.assertEqual(out.count("cannot read the gate: pull request #7 merges into main on the forge, but this checkout takes ABC-12 as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config; trying again every 60 seconds\n"), 1)
self.assertEqual(len(prompts), 1)
self.assertTrue(prompts[0].startswith("do-epic parked the chunk while its pull request awaited a person's merge. It resumes now: pull request #7 passed its checks and is approved. "), prompts[0])
def test_a_chunk_that_started_before_the_setting_was_on_keeps_its_merge_for_a_person(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
set_on = self.repo_config.read_text(encoding="utf-8")
self.repo_config.write_text(set_on.replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
worker = self.worker()
def turns_the_setting_on(args: list[str]) -> object:
self.repo_config.write_text(set_on, encoding="utf-8")
return worker(args)
self.forges = [awaiting(decision="APPROVED"), awaiting(decision="APPROVED"), awaiting(pulls=""), CLEANED]
fake = self.with_git(FakeEffects(streams=[turns_the_setting_on, self.worker()], claude=[judged("unfinished"), judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertNotIn("config", [args[0] for args, _ in self.git_calls], "no base recorded, so the pull request goes into the default branch")
self.assertIn("parked: pull request #7 awaits your merge\n", out)
self.assertNotIn("move ABC-20 to Code Review", self.store.writes)
def test_an_issue_that_cannot_move_to_the_open_status_says_so_and_its_chunk_goes_on(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.backend = lambda config, key: (StepwiseStore(self.store, {"Code Review": "QA"}), EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.forges = [awaiting(), awaiting(), awaiting(decision="APPROVED")]
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
@@ -1109,7 +1153,7 @@ class AnEpicsWorkingBranch(DoEpicTest):
def test_a_finished_chunk_whose_issue_has_no_pull_request_into_the_epic_branch_moves_it_to_done(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), humans=True).code, 0)
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.WITH_A_HUMAN).code, 0)
self.assertEqual((self.store.issues[0].status, self.store.issues[0].done), ("Done", True))
# A chunk not marked as in a repo moves its issue to done itself, even where the automation moves issues.
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
@@ -1124,11 +1168,11 @@ class AnEpicsWorkingBranch(DoEpicTest):
lagging = LaggingStore(self.store, before)
out = io.StringIO()
with contextlib.redirect_stdout(out):
stop = main.handed_on("ABC-20", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=lagging), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-20", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=lagging), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertIn("the chunk finished; started ABC-22\n", out.getvalue())
unread = LaggingStore(self.store, Failure("Jira answered 503"))
stop = main.handed_on("ABC-22", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=unread), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-22", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=unread), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but the next could not start: Jira answered 503"))
def test_the_epics_finishing_is_due_once_every_issue_has_the_merged_status(self) -> None:
@@ -1139,13 +1183,13 @@ class AnEpicsWorkingBranch(DoEpicTest):
def test_without_a_merged_status_a_finished_chunk_stops_where_automation_moves_issues_and_is_done_where_it_doesnt(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `jira-pull-request-merged-status` to move it to. Move ABC-20 in Jira, then run `do-epic ABC-12` to start the chunks it blocks"))
self.assertEqual(self.store.writes, [])
self.settings("")
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), in_repo=True, to_epic_branch=True).code, 0)
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.ON_EPIC_BRANCH).code, 0)
self.assertTrue(self.store.issues[0].done)
def test_an_issue_whose_workflow_reaches_the_merged_status_only_through_the_open_status_moves_through_it(self) -> None:
@@ -1153,18 +1197,18 @@ class AnEpicsWorkingBranch(DoEpicTest):
epic = self.epic_run(FakeEffects(windows=""))
stepwise = StepwiseStore(self.store, {"Release Ready": "Code Review"})
with contextlib.redirect_stdout(io.StringIO()):
stop = main.handed_on("ABC-20", dataclasses.replace(epic, store=stepwise), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-20", dataclasses.replace(epic, store=stepwise), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertEqual(self.store.writes, ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
# An issue the open status doesn't lead on from stops on the move it asked for.
stuck = StepwiseStore(self.store, {"Release Ready": "QA", "Code Review": "QA"})
stop = main.handed_on("ABC-22", dataclasses.replace(epic, store=stuck), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-22", dataclasses.replace(epic, store=stuck), main.Landed.ON_EPIC_BRANCH)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': ABC-22 has no transition to 'Release Ready'"), stop.reason)
def test_an_issue_that_cannot_move_to_the_merged_status_stops_and_says_what_to_do(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
self.store.fails = "Jira answered 503"
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), in_repo=True, to_epic_branch=True)
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': "), stop.reason)
self.assertTrue(stop.reason.endswith("once it has that status in Jira, run `do-epic ABC-12` to start the chunks it blocks"), stop.reason)