Park on a new review once requested changes are answered, never park a Gitea draft, and count a slot only for a window that started
This commit is contained in:
+10
-7
@@ -49,8 +49,12 @@ class Listed:
|
||||
id: str
|
||||
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
|
||||
dead: bool
|
||||
# Whether its chunk is parked: its name held PARKED.
|
||||
parked: bool = False
|
||||
# What its name says its parked chunk awaits, as the words after PARKED; empty for a chunk that isn't parked.
|
||||
awaits: str = ""
|
||||
|
||||
@property
|
||||
def parked(self) -> bool:
|
||||
return bool(self.awaits)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -85,8 +89,8 @@ def listed(session: str, run: Tmux) -> list[Listed]:
|
||||
|
||||
def as_listed(shown: str, id: str, pane_dead: str) -> Listed:
|
||||
"""The window tmux shows under the name shown, with the ID id and `#{pane_dead}` as pane_dead."""
|
||||
name, parked, _ = shown.removesuffix(WAITS).partition(PARKED)
|
||||
return Listed(name, id, pane_dead == "1", bool(parked))
|
||||
name, _, awaits = shown.removesuffix(WAITS).partition(PARKED)
|
||||
return Listed(name, id, pane_dead == "1", awaits)
|
||||
|
||||
|
||||
def everywhere(run: Tmux) -> list[Placed]:
|
||||
@@ -142,13 +146,12 @@ def mark(window: Window, waits: bool, run: Tmux) -> None:
|
||||
|
||||
|
||||
def park(window: Window, on: str, run: Tmux) -> None:
|
||||
"""Shows window's chunk as parked while its pull request awaits on, such as `an approval`: the name says so, and the window names no folder its chunk works in, so no checkout counts it as a running chunk."""
|
||||
"""Shows window's chunk as parked while its pull request awaits on, such as `an approval`: the name says so, and no checkout counts a window so named as a running chunk."""
|
||||
run(["rename-window", "-t", window.pane, window.name + PARKED + on])
|
||||
run(["set-option", "-w", "-u", "-t", window.pane, ROOT])
|
||||
|
||||
|
||||
def unpark(window: Window, root: str, run: Tmux) -> None:
|
||||
"""Shows window's chunk as running again, in the folder root."""
|
||||
"""Shows window's chunk as running again, in the folder root. The window may name another folder: one started again for a parked chunk starts in the epic's folder."""
|
||||
run(["rename-window", "-t", window.pane, window.name])
|
||||
run(["set-option", "-w", "-t", window.pane, ROOT, root])
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time
|
||||
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
|
||||
|
||||
|
||||
def left_to_park(number: str, run: Run) -> Failure:
|
||||
"""Why a merge under PARKS ends at once where pull request number passed its checks and awaits an approval, in place of waiting as `approved` does: a reviewer's comment waits for an answer, which the worker gives first, or else do-epic parks the chunk, so the worker ends its run."""
|
||||
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 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)
|
||||
|
||||
@@ -86,7 +86,7 @@ import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from chunk_pr.approval import approval, approved, awaited, PARKS, unanswered
|
||||
from chunk_pr.approval import approval, approved, awaited, 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 +306,7 @@ def finishes_of(given: list[str]) -> list[list[str]] | None:
|
||||
|
||||
|
||||
def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, 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, telling the worker that do-epic parks the chunk."""
|
||||
"""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."""
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
@@ -337,8 +337,10 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = tim
|
||||
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
|
||||
if not isinstance(taken, AwaitsApproval):
|
||||
return taken if isinstance(taken, Failure) else taken + absent
|
||||
if parks:
|
||||
return left_to_park(number, run)
|
||||
# Out of the queue, so the project's other chunks merge while this one waits.
|
||||
waited = 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") if parks else approved(number, run, sleep)
|
||||
waited = approved(number, run, sleep)
|
||||
if isinstance(waited, Failure):
|
||||
return waited
|
||||
|
||||
|
||||
@@ -384,6 +384,15 @@ class Merge(unittest.TestCase):
|
||||
self.assertEqual(checkout.ran.count(GH_DECISION), 1)
|
||||
self.assertEqual(step(["merge"], self.requiring_approval(GITHUB, "REVIEW_REQUIRED"), checkout.config, parks=True), failed)
|
||||
|
||||
def test_a_merge_that_parks_reports_a_reviewers_unanswered_comment_before_the_approval_it_awaits(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
|
||||
checkout.threads = [MergeQueue.thread("bin/asked.py", "reviewer")]
|
||||
failed = merged(checkout, checkout.config, self.fail, parks=True)
|
||||
self.assertEqual(failed.reason, "a reviewer's comment on pull request 12 waits for an answer, in bin/asked.py; answer it in its thread, push any fix, and run chunk-pr merge again")
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
|
||||
checkout.answers[tuple(GH_THREADS)] = Failure("gh api graphql failed")
|
||||
self.assertEqual(merged(checkout, checkout.config, self.fail, parks=True), Failure("gh api graphql failed"))
|
||||
|
||||
def test_a_merge_that_parks_merges_an_approved_pull_request(self):
|
||||
checkout = self.requiring_approval()
|
||||
self.assertEqual(merged(checkout, checkout.config, self.fail, parks=True), "Merged pull request #12 (merge).")
|
||||
|
||||
+45
-12
@@ -1,18 +1,23 @@
|
||||
"""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, or an approval a reviewer has yet to give. While a chunk's pull request waits on one, its worker has nothing 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, or the new review of a reviewer whose requested changes the worker answered. While a chunk's pull request waits on one, its worker has nothing to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on."""
|
||||
import dataclasses
|
||||
import json
|
||||
import typing
|
||||
|
||||
from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks
|
||||
from failure import Failure
|
||||
from forge.commands import forge_of, Run
|
||||
from forge.commands import forge_of, gitea, Run
|
||||
from chunk_pr.approval import waiting_threads
|
||||
|
||||
# What a pull request waits on, as the words after "awaits".
|
||||
CHECKS = "its checks"
|
||||
APPROVAL = "an approval"
|
||||
NEW_REVIEW = "a new review"
|
||||
# What `review_decision` returns in place of GitHub's `CHANGES_REQUESTED` once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again.
|
||||
ANSWERED = "CHANGES_ANSWERED"
|
||||
# What the title of a draft opens with on Gitea, in any case: Gitea's default `WORK_IN_PROGRESS_PREFIXES`.
|
||||
GITEA_DRAFT = ("WIP:", "[WIP]")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -22,7 +27,7 @@ class Gate:
|
||||
worktree: str
|
||||
# The pull request's number.
|
||||
pull: str
|
||||
# CHECKS or APPROVAL.
|
||||
# CHECKS, APPROVAL or NEW_REVIEW.
|
||||
on: str
|
||||
|
||||
|
||||
@@ -36,7 +41,7 @@ class Open:
|
||||
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 says nothing 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`).
|
||||
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 (`answered`); from then on the pull request awaits a new review.
|
||||
"""
|
||||
worktree = worktree_of(branch, at(checkout))
|
||||
if not isinstance(worktree, str):
|
||||
@@ -50,8 +55,8 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate |
|
||||
forge = forge_of(origin)
|
||||
pull = open_pull(forge, branch, head, run)
|
||||
if not isinstance(pull, str):
|
||||
return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}")
|
||||
decision = review_decision(pull, run) if forge == "gh" else ""
|
||||
return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}; it may be merged or closed already")
|
||||
decision = review_decision(pull, head, run) if forge == "gh" else gitea_decision(pull, 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)
|
||||
@@ -69,8 +74,8 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate |
|
||||
return waiting
|
||||
if waiting:
|
||||
return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}")
|
||||
if decision == "REVIEW_REQUIRED":
|
||||
return Gate(worktree, pull, APPROVAL)
|
||||
if decision in (ANSWERED, "REVIEW_REQUIRED"):
|
||||
return Gate(worktree, pull, NEW_REVIEW if decision == ANSWERED else APPROVAL)
|
||||
return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == "APPROVED" else ""))
|
||||
|
||||
|
||||
@@ -86,13 +91,41 @@ def worktree_of(branch: str, run: Run) -> str | None | Failure:
|
||||
return None
|
||||
|
||||
|
||||
def review_decision(pull: str, run: Run) -> str | None | Failure:
|
||||
"""GitHub's review decision on the pull request, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. None where it is a draft."""
|
||||
viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision"])
|
||||
def review_decision(pull: str, head: str, run: Run) -> str | None | Failure:
|
||||
"""GitHub's review decision on the pull request, whose head commit is head, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. ANSWERED in place of `CHANGES_REQUESTED` once the worker answered those changes. None where it is a draft."""
|
||||
viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"])
|
||||
if isinstance(viewed, Failure):
|
||||
return viewed
|
||||
try:
|
||||
parsed = json.loads(viewed)
|
||||
return None if parsed["isDraft"] else str(parsed["reviewDecision"] or "")
|
||||
if parsed["isDraft"]:
|
||||
return None
|
||||
decision = str(parsed["reviewDecision"] or "")
|
||||
return ANSWERED if decision == "CHANGES_REQUESTED" and answered(parsed, head) else decision
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}")
|
||||
|
||||
|
||||
def answered(pull: dict[str, typing.Any], head: str) -> bool:
|
||||
"""Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape.
|
||||
|
||||
The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed.
|
||||
"""
|
||||
asked = max((review for review in pull["reviews"] if review["state"] == "CHANGES_REQUESTED"), key=lambda review: review["submittedAt"], default=None)
|
||||
if asked is None:
|
||||
return False
|
||||
author = pull["author"]["login"]
|
||||
# A review the author has yet to submit has no time, and answers nobody.
|
||||
said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author]
|
||||
return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said)
|
||||
|
||||
|
||||
def gitea_decision(pull: str, run: Run) -> str | None | Failure:
|
||||
"""What stands in for `review_decision` on Gitea, read once: empty, since no review is a gate there, and None where the pull request is a draft, which Gitea tells by its title (GITEA_DRAFT)."""
|
||||
viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}")
|
||||
if isinstance(viewed, Failure):
|
||||
return viewed
|
||||
try:
|
||||
return None if viewed["title"].upper().startswith(GITEA_DRAFT) else ""
|
||||
except (KeyError, TypeError, AttributeError):
|
||||
return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}")
|
||||
|
||||
+16
-19
@@ -207,17 +207,17 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
|
||||
place = chunk_root(issue, epic)
|
||||
if isinstance(place, Stop):
|
||||
return place
|
||||
root, in_repo = place
|
||||
root, repo = place
|
||||
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
|
||||
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)
|
||||
loop_run = LoopRun(0, root, "", "", chunk=key)
|
||||
# What a chunk that was parked is told as it resumes; empty for a chunk that wasn't.
|
||||
news = parked_through(issue, loop, epic, starts=True) if in_repo else ""
|
||||
news = parked_through(repo, loop, epic, starts=True) if repo is not None else ""
|
||||
while True:
|
||||
if isinstance(news, Stop):
|
||||
return news
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
cycle = next_cycle(loop_run, loop, in_repo, epic, news)
|
||||
cycle = next_cycle(loop_run, loop, repo is not None, epic, news)
|
||||
if isinstance(cycle, Stop):
|
||||
return cycle
|
||||
loop_run = dataclasses.replace(loop_run, task=cycle.task)
|
||||
@@ -228,18 +228,18 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
news = parked_through(issue, loop, epic, starts=False) if in_repo else ""
|
||||
news = parked_through(repo, loop, epic, starts=False) 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)
|
||||
|
||||
|
||||
def parked_through(issue: EpicIssue, loop: Loop, epic: EpicRun, starts: bool) -> str | Stop:
|
||||
"""Keeps the chunk of issue 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. starts says the window just started, where the chunk is parked only if its file says so: nothing is read from the forge for a chunk that starts afresh.
|
||||
def parked_through(repo: str, loop: Loop, epic: EpicRun, starts: bool) -> str | Stop:
|
||||
"""Keeps the chunk in loop's window, which changes repo, 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. starts says the window just started, where the chunk is parked only if its file says so: nothing is read from the forge for a chunk that starts afresh.
|
||||
|
||||
A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` takes it a slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again.
|
||||
"""
|
||||
key, folder = issue.key, epic.paths.home / scheduler.STATE / epic.key
|
||||
key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key
|
||||
recorded_as = parked.parked_chunks(folder)
|
||||
if isinstance(recorded_as, Failure):
|
||||
return Stop(1, recorded_as.reason)
|
||||
@@ -264,12 +264,12 @@ def parked_through(issue: EpicIssue, loop: Loop, epic: EpicRun, starts: bool) ->
|
||||
elif isinstance(now, Failure):
|
||||
stays = f"cannot read the gate: {now.reason}"
|
||||
elif isinstance(now, gates.Open):
|
||||
full = resumed(issue, loop, epic)
|
||||
full = resumed(repo, loop, epic)
|
||||
if full is None:
|
||||
failed = parked.unpark(folder, 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 = SLOT if isinstance(now, gates.Open) else now.on if isinstance(now, gates.Gate) else shown or on
|
||||
awaits = parked.SLOT if isinstance(now, gates.Open) else now.on if isinstance(now, gates.Gate) else shown or on
|
||||
if awaits != shown:
|
||||
tmux.park(loop.window, str(awaits), epic.effects.tmux)
|
||||
shown = awaits
|
||||
@@ -286,17 +286,14 @@ def parked_through(issue: EpicIssue, loop: Loop, epic: EpicRun, starts: bool) ->
|
||||
|
||||
# How the news for a chunk that was parked opens.
|
||||
DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while"
|
||||
# What a parked chunk awaits, in its window's name, once its worker has something to do but no running slot is free.
|
||||
SLOT = "a slot"
|
||||
|
||||
|
||||
def resumed(issue: EpicIssue, loop: Loop, epic: EpicRun) -> str | None:
|
||||
"""scheduler.resume for the parked chunk of issue, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
|
||||
pick = recorded(issue)
|
||||
def resumed(repo: str, loop: Loop, epic: EpicRun) -> str | None:
|
||||
"""scheduler.resume for the parked chunk in loop's window, which changes repo, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
|
||||
scheduled = scheduled_epic(epic)
|
||||
if isinstance(scheduled, Failure):
|
||||
return scheduled.reason
|
||||
return scheduler.resume(scheduled, pick.name, loop.window, epic.effects.tmux) if isinstance(pick, Repo) else f"no label of {issue.key} names its repo any longer"
|
||||
return scheduler.resume(scheduled, repo, loop.window, epic.effects.tmux)
|
||||
|
||||
|
||||
def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop:
|
||||
@@ -308,19 +305,19 @@ def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop:
|
||||
return found[0] if found else Stop(1, f"{key} is no issue of the epic {epic.key}")
|
||||
|
||||
|
||||
def chunk_root(issue: EpicIssue, epic: EpicRun) -> tuple[str, bool] | Stop:
|
||||
"""The folder the issue's chunk works in, and whether it is a repo's checkout: the epic's folder holds work without a repo. The chunk keeps both to its end, whatever the issue's labels become. The stop where the labels make the issue no chunk."""
|
||||
def chunk_root(issue: EpicIssue, epic: EpicRun) -> tuple[str, str | None] | Stop:
|
||||
"""The folder the issue's chunk works in, and the name of the repo whose checkout it is: None for the epic's folder, which holds work without a repo. The chunk keeps both to its end, whatever the issue's labels become. The stop where the labels make the issue no chunk."""
|
||||
pick = recorded(issue)
|
||||
if isinstance(pick, Failure):
|
||||
return Stop(1, pick.reason)
|
||||
if isinstance(pick, ClaudeWork):
|
||||
folder = epic.paths.home / scheduler.STATE / epic.key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
return str(folder), False
|
||||
return str(folder), None
|
||||
if not isinstance(pick, Repo):
|
||||
return Stop(1, f"{issue.key} is no chunk: {'it is a human\'s task' if isinstance(pick, HumanTask) else 'no label names its repo'}")
|
||||
found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git)
|
||||
return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), True)
|
||||
return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), pick.name)
|
||||
|
||||
|
||||
def handed_on(key: str, epic: EpicRun) -> Stop:
|
||||
|
||||
@@ -10,6 +10,8 @@ from failure import Failure
|
||||
|
||||
# Under the epic's folder, the folder that holds one file per parked chunk, named for its issue.
|
||||
FOLDER = "parked"
|
||||
# What a parked chunk awaits, in its window's name, once its worker has something to do but no running slot is free.
|
||||
SLOT = "a slot"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -22,13 +24,14 @@ 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`).
|
||||
# What its pull request waits on, as the words after "awaits" (`gates.CHECKS`, `gates.APPROVAL`, `gates.NEW_REVIEW`).
|
||||
on: str
|
||||
|
||||
@property
|
||||
def waits(self) -> str:
|
||||
"""Why the chunk doesn't run, for the human."""
|
||||
return f"it is parked: its pull request #{self.pull} awaits {self.on}"
|
||||
def waits(self, shown: str) -> str:
|
||||
"""Why the chunk doesn't run, for the human. shown is what the name of its live window says it awaits, which is newer than the file's `on`; empty where no window lives."""
|
||||
if shown == SLOT:
|
||||
return f"it is parked: its worker has work again on pull request #{self.pull} and awaits {SLOT}"
|
||||
return f"it is parked: its pull request #{self.pull} awaits {shown or self.on}"
|
||||
|
||||
|
||||
def file_of(folder: pathlib.Path, issue: str) -> pathlib.Path:
|
||||
|
||||
+10
-10
@@ -119,23 +119,22 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], own: str | None, run: tmux
|
||||
try:
|
||||
with starting(epic.folder):
|
||||
windows = tmux.listed(session, run)
|
||||
live = {window.name for window in windows if not window.dead} - {own}
|
||||
live = {window.name: window for window in windows if not window.dead and window.name != own}
|
||||
running = {window.name for window in windows if not window.dead and not window.parked} - {own}
|
||||
stopped = {window.name for window in windows if window.dead} - live
|
||||
stopped = {window.name for window in windows if window.dead} - set(live)
|
||||
# The windows this call started that take a running slot.
|
||||
taken = 0
|
||||
for chunk in found:
|
||||
if chunk.issue in running or chunk.issue == own:
|
||||
continue
|
||||
if chunk.issue in parked and chunk.issue in live:
|
||||
waits.append(Waits(chunk.issue, parked[chunk.issue].waits))
|
||||
waits.append(Waits(chunk.issue, parked[chunk.issue].waits(live[chunk.issue].awaits)))
|
||||
elif own and (chunk.issue in stopped or chunk.issue in parked):
|
||||
waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again"))
|
||||
elif chunk.issue not in parked and len(running) + taken >= epic.cap:
|
||||
waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"))
|
||||
else:
|
||||
now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run)
|
||||
taken += chunk.issue not in parked
|
||||
if isinstance(now, Failure):
|
||||
return now
|
||||
if isinstance(now, str):
|
||||
@@ -143,6 +142,7 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], own: str | None, run: tmux
|
||||
else:
|
||||
windows = now
|
||||
started.append(chunk.issue)
|
||||
taken += chunk.issue not in parked
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}")
|
||||
return Started(started, sorted(waits, key=lambda wait: [issue.key for issue in issues].index(wait.issue)))
|
||||
@@ -167,7 +167,7 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li
|
||||
|
||||
|
||||
def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pathlib.Path, run: tmux.Tmux) -> RepoRoom:
|
||||
"""The room in a repo's checkout under its limit. leaving is the session and name of a window whose chunk finished, which no longer counts."""
|
||||
"""The room in a repo's checkout under its limit. leaving is the session and name of the window that asks, which doesn't count: its chunk finished or is parked."""
|
||||
theirs = [placed for placed in epic_chunks(checkout, run) if (placed.session, placed.window.name) != leaving]
|
||||
loop_session = tmux.session_name(tmux.LOOP, project_key(checkout, home))
|
||||
loops = any(not window.dead for window in tmux.listed(loop_session, run)) and tmux.owner(loop_session, run) == checkout
|
||||
@@ -175,10 +175,10 @@ def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pa
|
||||
|
||||
|
||||
def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None:
|
||||
"""Takes a running slot for the parked chunk in window, which changes repo and whose worker has something to do again: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks."""
|
||||
"""Takes a running slot for the parked chunk in window, which changes repo and whose worker has something to do again: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks. The window itself never counts against them: one started again for a parked chunk, as after a reboot, isn't named as parked until its first read of the gate."""
|
||||
try:
|
||||
with starting(epic.folder):
|
||||
running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked]
|
||||
running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked and listed.name != window.name]
|
||||
if len(running) >= epic.cap:
|
||||
return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"
|
||||
located = epic.locate(repo)
|
||||
@@ -186,7 +186,7 @@ def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str |
|
||||
return located.reason
|
||||
checkout, limit = located
|
||||
with starting(project_lock(str(checkout), epic.home)):
|
||||
if reason := refusal(repo, room_in(str(checkout), limit, (window.session, None), epic.home, run)):
|
||||
if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)):
|
||||
return reason
|
||||
tmux.unpark(window, str(checkout), run)
|
||||
return None
|
||||
@@ -201,12 +201,12 @@ def status(key: str, home: pathlib.Path, issues: list[EpicIssue], run: tmux.Tmux
|
||||
if isinstance(parked, Failure):
|
||||
return parked
|
||||
windows = tmux.listed(tmux.session_name(tmux.EPIC, key), run)
|
||||
live = {window.name for window in windows if not window.dead}
|
||||
live = {window.name: window for window in windows if not window.dead}
|
||||
again = f"run `do-epic {key}` to start it again"
|
||||
reasons = {wait.issue: wait.reason for wait in waits}
|
||||
for chunk in found:
|
||||
if chunk.issue in parked:
|
||||
reasons[chunk.issue] = parked[chunk.issue].waits + ("" if chunk.issue in live else f", and its window stopped; {again}")
|
||||
reasons[chunk.issue] = parked[chunk.issue].waits(live[chunk.issue].awaits) if chunk.issue in live else f"{parked[chunk.issue].waits('')}, and its window stopped; {again}"
|
||||
elif chunk.issue not in live:
|
||||
reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it once the epic and its repo have room"
|
||||
return [f"{issue.key} waits: {reasons[issue.key]}" if issue.key in reasons else f"{issue.key} runs" for issue in issues if issue.key in reasons or issue.key in live]
|
||||
|
||||
@@ -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, Open
|
||||
from do_epic.gates import APPROVAL, CHECKS, gate, Gate, 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"
|
||||
@@ -16,10 +16,20 @@ def thread(resolved: bool, last: str, path: str = "a.py") -> dict:
|
||||
return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}}
|
||||
|
||||
|
||||
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."""
|
||||
def review(state: str, at: str, by: str = "reviewer", on: str = HEAD) -> dict:
|
||||
"""A review as `gh pr view --json reviews` prints it: made by `by` at `at`, on the commit `on`."""
|
||||
return {"author": {"login": by}, "state": state, "submittedAt": at, "commit": {"oid": on}}
|
||||
|
||||
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}', worktrees: str = WORKTREES, fails: str = "") -> None:
|
||||
|
||||
def comment(by: str, at: str) -> dict:
|
||||
return {"author": {"login": by}, "createdAt": at}
|
||||
|
||||
|
||||
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}', worktrees: str = WORKTREES, fails: str = "", reviews: tuple[dict, ...] = (), comments: tuple[dict, ...] = (), title: str = "Add x") -> None:
|
||||
self.cli = "gh" if "github.com" in origin else "tea"
|
||||
self.ran: list[str] = []
|
||||
self.commands: list[list[str]] = []
|
||||
self.fails = fails
|
||||
@@ -29,10 +39,11 @@ class Forge:
|
||||
"git rev-parse": HEAD + "\n",
|
||||
"git symbolic-ref": "origin/main\n",
|
||||
"gh pr list": pulls,
|
||||
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision}),
|
||||
"gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision, "author": {"login": "worker"}, "reviews": list(reviews), "comments": list(comments)}),
|
||||
"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}),
|
||||
"tea api repos/{owner}/{repo}/branches/main": '{"name": "main"}',
|
||||
"tea api repos/{owner}/{repo}/commits/" + HEAD + "/status": status,
|
||||
}
|
||||
@@ -41,6 +52,8 @@ class Forge:
|
||||
def run(command: list[str]) -> str | Failure:
|
||||
self.ran.append(folder)
|
||||
self.commands.append(command)
|
||||
if command[0] in ("gh", "tea") and command[0] != self.cli:
|
||||
return Failure(f"{command[0]} cannot read this origin")
|
||||
key = " ".join(command) if command[0] == "tea" else " ".join(command[:3] if command[0] == "gh" else command[:2])
|
||||
return Failure(f"{key} failed") if self.fails and key.startswith(self.fails) else self.answers[key]
|
||||
return run
|
||||
@@ -55,7 +68,7 @@ class GateOfAChunk(unittest.TestCase):
|
||||
self.assertEqual(forge.gate(), Gate("/code/billing-ABC-21", "7", APPROVAL))
|
||||
self.assertEqual((forge.ran[0], set(forge.ran[1:])), ("/code/billing", {"/code/billing-ABC-21"}))
|
||||
self.assertEqual(forge.commands[:4], [["git", "worktree", "list", "--porcelain"], ["git", "remote", "get-url", "origin"], ["git", "rev-parse", "HEAD"], ["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"]])
|
||||
self.assertIn(["gh", "pr", "view", "7", "--json", "isDraft,reviewDecision"], forge.commands)
|
||||
self.assertIn(["gh", "pr", "view", "7", "--json", "isDraft,reviewDecision,author,reviews,comments"], forge.commands)
|
||||
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)
|
||||
|
||||
@@ -74,6 +87,39 @@ class GateOfAChunk(unittest.TestCase):
|
||||
self.assertEqual(Forge(gitea, status='{"state": "pending", "total_count": 1}').gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
|
||||
self.assertEqual(Forge(gitea).gate(), Open("pull request #7 passed its checks"))
|
||||
|
||||
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"):
|
||||
with self.subTest(title=title):
|
||||
self.assertEqual(Forge(gitea, title=title, status='{"state": "pending", "total_count": 1}').gate(), Open("pull request #7 is a draft"))
|
||||
self.assertEqual(Forge(gitea, title="Add WIP: x", status='{"state": "pending", "total_count": 1}').gate(), Gate("/code/billing-ABC-21", "7", CHECKS))
|
||||
unread = Forge(gitea)
|
||||
unread.answers["tea api repos/{owner}/{repo}/pulls/7"] = "[1]"
|
||||
self.assertEqual(unread.gate(), Failure("tea api printed no title of pull request 7: [1]"))
|
||||
|
||||
def test_requested_changes_are_news_until_the_worker_pushed_or_replied_and_then_await_a_new_review(self):
|
||||
asked = review("CHANGES_REQUESTED", "2026-11-18T10:00:00Z")
|
||||
before, after, old = "2026-11-18T09:00:00Z", "2026-11-18T11:00:00Z", "fed" * 4
|
||||
news, waits = Open("a reviewer requested changes on pull request #7"), Gate("/code/billing-ABC-21", "7", NEW_REVIEW)
|
||||
cases = {
|
||||
"nobody answered": ((asked,), (), news),
|
||||
"the worker pushed": ((review("CHANGES_REQUESTED", "2026-11-18T10:00:00Z", on=old),), (), waits),
|
||||
"the worker replied in a thread": ((asked, review("COMMENTED", after, by="worker")), (), waits),
|
||||
"the worker commented": ((asked,), (comment("worker", after),), waits),
|
||||
"the worker spoke only before": ((review("COMMENTED", before, by="worker"), asked, review("PENDING", None, by="worker")), (comment("worker", before),), news), # type: ignore[arg-type]
|
||||
"only a reviewer spoke after": ((asked, review("COMMENTED", after)), (comment("reviewer", after),), news),
|
||||
"a reviewer asked again on the new head": ((asked, review("CHANGES_REQUESTED", before, on=old), review("COMMENTED", "2026-11-18T09:30:00Z", by="worker")), (), news),
|
||||
"GitHub lists no such review": ((review("APPROVED", before, on=old),), (comment("worker", after),), news),
|
||||
}
|
||||
for case, (reviews, comments, found) in cases.items():
|
||||
with self.subTest(case=case):
|
||||
self.assertEqual(Forge(decision="CHANGES_REQUESTED", reviews=reviews, comments=comments).gate(), found)
|
||||
self.assertEqual(NEW_REVIEW, "a new review")
|
||||
|
||||
def test_a_reviewers_unanswered_comment_is_news_though_the_worker_answered_the_requested_changes(self):
|
||||
forge = Forge(decision="CHANGES_REQUESTED", reviews=(review("CHANGES_REQUESTED", "2026-11-18T10:00:00Z", on="fed" * 4),), threads=(thread(False, "reviewer"),))
|
||||
self.assertEqual(forge.gate(), Open("a reviewer's comment on pull request #7 waits for an answer, in a.py"))
|
||||
|
||||
def test_the_worker_goes_on_where_nothing_but_the_worker_moves_the_pull_request(self):
|
||||
cases = {
|
||||
"pull request #7 passed its checks and is approved": Forge(decision="APPROVED"),
|
||||
@@ -82,7 +128,7 @@ class GateOfAChunk(unittest.TestCase):
|
||||
"a check on pull request 7 failed; fix it and push": Forge(buckets=("fail",)),
|
||||
"a reviewer requested changes on pull request #7": Forge(decision="CHANGES_REQUESTED"),
|
||||
"a reviewer's comment on pull request #7 waits for an answer, in a.py, b.py": Forge(threads=(thread(False, "reviewer", "b.py"), thread(False, "reviewer"), thread(True, "reviewer", "c.py"), thread(False, "worker", "d.py"))),
|
||||
"no pull request from origin's ABC-21 is open at abcabcabcabc": Forge(pulls=""),
|
||||
"no pull request from origin's ABC-21 is open at abcabcabcabc; it may be merged or closed already": Forge(pulls=""),
|
||||
"no worktree of /code/billing has the branch ABC-21 checked out": Forge(worktrees="worktree /code/billing\nHEAD aaa\nbranch refs/heads/main\n"),
|
||||
}
|
||||
for news, forge in cases.items():
|
||||
@@ -93,7 +139,9 @@ class GateOfAChunk(unittest.TestCase):
|
||||
for command in ("git worktree", "git remote", "gh pr list", "gh pr view", "gh pr checks", "gh api graphql"):
|
||||
with self.subTest(command=command):
|
||||
self.assertEqual(Forge(fails=command).gate(), Failure(f"{command} failed"))
|
||||
self.assertEqual(Forge("https://gitea.larvit.se/o/billing.git", fails="tea api repos/{owner}/{repo}/branches").gate(), Failure("tea api repos/{owner}/{repo}/branches/main failed"))
|
||||
for endpoint in ("pulls?state=open&limit=50", "pulls/7", "branches/main"):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertEqual(Forge("https://gitea.larvit.se/o/billing.git", fails=f"tea api repos/{{owner}}/{{repo}}/{endpoint}").gate(), Failure(f"tea api repos/{{owner}}/{{repo}}/{endpoint} failed"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -145,10 +145,10 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
epic = main.EpicRun("ABC-12", config, store, record, paths, env or {}, pathlib.Path("/b/do-epic"), fake.effects())
|
||||
place = main.chunk_root(self.issues[1], epic)
|
||||
assert isinstance(place, tuple)
|
||||
root, in_repo = place
|
||||
root, repo = place
|
||||
loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects())
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
found = main.next_cycle(LoopRun(1, root, "", "", chunk="ABC-21"), loop, in_repo, epic)
|
||||
found = main.next_cycle(LoopRun(1, root, "", "", chunk="ABC-21"), loop, repo is not None, epic)
|
||||
assert isinstance(found, main.Cycle), found
|
||||
return found
|
||||
|
||||
@@ -479,7 +479,7 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
|
||||
self.assertTrue(prompts[1].startswith(f"do-epic parked the chunk while its pull request awaited an approval. It resumes now: pull request #7 passed its checks and is approved. {chunk_prompt.FEEDBACK}\n\nWork the Jira issue ABC-20 "), prompts[1])
|
||||
self.assertIn("the chunk finished; ", out)
|
||||
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"], ["set-option", "-w", "-u", "-t", "%1", tmux.ROOT], ["rename-window", "-t", "%1", "ABC-20"], ["set-option", "-w", "-t", "%1", tmux.ROOT, checkout]])
|
||||
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_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"}}]}},))]
|
||||
@@ -521,6 +521,31 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
|
||||
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20 awaits a slot", "ABC-20"])
|
||||
self.assertEqual(len(prompts), 2)
|
||||
|
||||
def test_a_chunk_parks_and_resumes_though_the_next_chunk_cannot_start(self) -> None:
|
||||
self.forges = [awaiting(), awaiting(decision="APPROVED")]
|
||||
worker = self.worker()
|
||||
|
||||
def unreadable_after(*args: object) -> object:
|
||||
self.description = Failure("Jira answered 503")
|
||||
return worker(*args) # type: ignore[arg-type]
|
||||
fake = FakeEffects(streams=[unreadable_after, self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
|
||||
slept: list[bool] = []
|
||||
# The epic's description cannot be read from the first worker's run until the parked chunk first sleeps.
|
||||
description = Description("")
|
||||
object.__setattr__(description, "read", lambda: self.description)
|
||||
self.backend = lambda config, key: (MemoryEpic(key, list(self.issues)), EpicRecord(description)) # type: ignore[method-assign,arg-type]
|
||||
|
||||
def sleep(seconds: float) -> None:
|
||||
slept.append(self.file.exists())
|
||||
self.description = DESCRIPTION
|
||||
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
|
||||
code, out, err, prompts = self.parked_run(fake)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertIn("parked: pull request #7 awaits an approval\ncould not start the next chunk: Jira answered 503\n", out)
|
||||
self.assertEqual(slept, [True])
|
||||
self.assertFalse(self.file.exists())
|
||||
self.assertEqual(len(prompts), 2)
|
||||
|
||||
def test_a_forge_that_cannot_be_read_parks_no_chunk_and_unparks_none(self) -> None:
|
||||
self.forges = [awaiting(fails="gh pr checks")]
|
||||
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
|
||||
@@ -568,7 +593,9 @@ class TheStatus(DoEpicTest):
|
||||
folder = self.home / ".local/state/do-epic/ABC-12"
|
||||
parked.park(folder, parked.Parked("ABC-20", "/code/api-ABC-20", "7", "s", "an approval"))
|
||||
parked.park(folder, parked.Parked("ABC-26", "/code/api-ABC-26", "9", "s", "its checks"))
|
||||
fake = FakeEffects(windows="ABC-20 awaits an approval\t0\t@1\nABC-21 ?\t0\t@2\nABC-22\t1\t@3\n")
|
||||
parked.park(folder, parked.Parked("ABC-28", "/code/api-ABC-28", "11", "s", "an approval"))
|
||||
self.issues.insert(7, issue("ABC-28", "repo:api"))
|
||||
fake = FakeEffects(windows="ABC-20 awaits an approval\t0\t@1\nABC-21 ?\t0\t@2\nABC-22\t1\t@3\nABC-28 awaits a slot\t0\t@4\n")
|
||||
code, out, err = self.run_main(["ABC-12", "--status"], fake)
|
||||
self.assertEqual((code, err), (0, ""))
|
||||
self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [
|
||||
@@ -578,6 +605,7 @@ class TheStatus(DoEpicTest):
|
||||
"ABC-23 waits: ABC-20 blocks it",
|
||||
"ABC-24 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room",
|
||||
"ABC-26 waits: it is parked: its pull request #9 awaits its checks, and its window stopped; run `do-epic ABC-12` to start it again",
|
||||
"ABC-28 waits: it is parked: its worker has work again on pull request #11 and awaits a slot",
|
||||
"ABC-27 waits: no label names its repo",
|
||||
])
|
||||
self.assertEqual({args[0] for args in fake.tmux_calls}, {"-V", "list-windows"})
|
||||
|
||||
@@ -34,7 +34,9 @@ class ParkedChunks(unittest.TestCase):
|
||||
self.assertIsNone(unpark(self.folder, "ABC-21"))
|
||||
|
||||
def test_says_why_the_human_sees_no_chunk_run(self):
|
||||
self.assertEqual(CHUNK.waits, "it is parked: its pull request #7 awaits an approval")
|
||||
self.assertEqual(CHUNK.waits(""), "it is parked: its pull request #7 awaits an approval")
|
||||
self.assertEqual(CHUNK.waits("its checks"), "it is parked: its pull request #7 awaits its checks")
|
||||
self.assertEqual(CHUNK.waits("a slot"), "it is parked: its worker has work again on pull request #7 and awaits a slot")
|
||||
|
||||
def test_fails_naming_the_file_where_it_holds_no_parked_chunk_or_another_issues(self):
|
||||
park(self.folder, CHUNK)
|
||||
|
||||
@@ -153,6 +153,12 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api", blockers=("ABC-20",))], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "it is parked: its pull request #7 awaits an approval"), Waits("ABC-22", "ABC-20 blocks it")]))
|
||||
|
||||
def test_a_parked_chunk_whose_window_awaits_a_slot_says_so(self) -> None:
|
||||
self.parked("ABC-20")
|
||||
run = Tmux(("epic-ABC-12", "ABC-20 awaits a slot", False, ""), ("epic-ABC-12", "ABC-21", False, str(self.home / "code/api")))
|
||||
found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], run)
|
||||
self.assertEqual(found, Started([], [Waits("ABC-20", "it is parked: its worker has work again on pull request #7 and awaits a slot")]))
|
||||
|
||||
def test_a_parked_chunk_without_a_window_starts_again_whatever_the_limits_in_the_epics_folder(self) -> None:
|
||||
self.parked("ABC-20")
|
||||
for windows in ((), (("epic-ABC-12", "ABC-20 awaits an approval", True, ""),)):
|
||||
@@ -202,6 +208,13 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
self.assertIsNone(self.resumed(self.epic(1, api=1), run))
|
||||
self.assertEqual(run.windows[0], ("epic-ABC-12", "ABC-20", False, str(self.home / "code/api")))
|
||||
|
||||
def test_a_parked_chunk_whose_window_started_again_doesnt_count_itself_as_running(self) -> None:
|
||||
for root in (str(self.home / ".local/state/do-epic/ABC-12"), str(self.home / "code/api")):
|
||||
with self.subTest(root=root):
|
||||
run = Tmux(("epic-ABC-12", "ABC-20", False, root))
|
||||
self.assertIsNone(self.resumed(self.epic(1, api=1), run))
|
||||
self.assertEqual(run.windows[0], ("epic-ABC-12", "ABC-20", False, str(self.home / "code/api")))
|
||||
|
||||
def test_a_parked_chunk_stays_parked_while_the_epic_or_its_repo_is_full(self) -> None:
|
||||
parked = ("epic-ABC-12", "ABC-20 awaits an approval", False, "")
|
||||
cases = {
|
||||
@@ -225,6 +238,11 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
found = self.start(self.epic(3, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:web")], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "api runs as many chunks as its `parallel-chunks` allows: 1")]))
|
||||
|
||||
def test_a_chunk_its_repo_refuses_takes_no_slot_of_the_epics_cap(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
found = self.start(self.epic(1, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:web")], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "loop-claude runs chunks in api")]))
|
||||
|
||||
def test_never_starts_in_a_repo_loop_claude_runs_chunks_in(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
found = self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run)
|
||||
|
||||
Reference in New Issue
Block a user