import dataclasses import pathlib import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.scheduler import Chunk, chunks, Epic, held_up, HUMAN_WAIT, refusal, RepoRoom, resume, start_chunks, Started, Waits from chunk_driver.claims import CHUNK_FLAG from do_epic import chunk_prompt from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, park, Parked from do_epic.epic_record import parallel_chunks_in from chunk_driver import prompts from model_routing.route import Route from model_routing.ladder import Rung from project_config import settings from agent_cycle import tmux def issue(key: str, *labels: str, done: bool = False, blockers: tuple[str, ...] = (), parent: str = "ABC-12", status: str | None = None) -> EpicIssue: return EpicIssue(key, f"Do {key}", "", tuple(sorted(labels)), None, status or ("Done" if done else "To Do"), done, parent, blockers=blockers) class TheCapLine(unittest.TestCase): def test_reads_the_epics_cap(self) -> None: self.assertEqual(parallel_chunks_in("**Language:** Swedish\n**Max parallel chunks:** 3\n\n## Goals\nShip.\n"), 3) def test_an_epic_without_the_line_runs_one_chunk_at_once(self) -> None: self.assertEqual(parallel_chunks_in("## Goals\nShip.\n"), 1) self.assertEqual(parallel_chunks_in("```\n**Max parallel chunks:** 3\n```\n"), 1) def test_refuses_a_line_that_nearly_spells_the_cap(self) -> None: for line in ("**Max parallel chunks**: 2", "Max parallel chunks: 2", "**max parallel chunks:** 2", "- **Max parallel chunks:** 2"): found = parallel_chunks_in(f"## Goals\nShip.\n{line}\n") assert isinstance(found, Failure), line self.assertEqual(found.reason, f"the epic's description holds the line `{line}`, which do-epic doesn't read as the epic's cap: write it as a line of its own, spelt `**Max parallel chunks:** 2`") self.assertEqual(parallel_chunks_in("We raise the max parallel chunks later.\n```\nMax parallel chunks: 2\n```\n"), 1) def test_refuses_a_cap_that_is_no_whole_number_of_1_or_more(self) -> None: for value in ("0", "many", "2.5", "-1", ""): found = parallel_chunks_in(f"**Max parallel chunks:** {value}\n") assert isinstance(found, Failure) self.assertEqual(found.reason, f"the epic's description caps its chunks with `**Max parallel chunks:** {value}`, which is not a whole number of 1 or more, such as `**Max parallel chunks:** 2`") class WhichIssuesAreChunks(unittest.TestCase): def test_an_open_issue_with_a_repo_or_claude_work_is_a_chunk_in_rank_order(self) -> None: found = chunks([issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "repo:web", done=True)], {}) self.assertEqual(found, ([Chunk("ABC-20", "api"), Chunk("ABC-21", None)], [])) def test_a_split_item_is_no_chunk_but_its_sub_tasks_are(self) -> None: found = chunks([issue("ABC-20", "split-by-repo"), issue("ABC-23", "repo:api", parent="ABC-20"), issue("ABC-24", "repo:web", parent="ABC-20")], {}) self.assertEqual(found, ([Chunk("ABC-23", "api"), Chunk("ABC-24", "web")], [])) def test_an_epic_shaped_as_a_teams_is_worked_through_its_own_sub_tasks_and_labels(self) -> None: team = {"twu-4": "tenant-web-ui-4", "core-4": "core-4"} issues = [ issue("ABC-19", "twu-4"), issue("ABC-20", blockers=("ABC-19",)), issue("ABC-23", "core-4", parent="ABC-20"), issue("ABC-24", "twu-4", parent="ABC-20", done=True), issue("ABC-21"), issue("ABC-25", "core-4", parent="ABC-21"), ] self.assertEqual(chunks(issues, team), ([Chunk("ABC-19", "tenant-web-ui-4"), Chunk("ABC-25", "core-4")], [Waits("ABC-23", "ABC-19 blocks it")])) self.assertEqual(chunks(issues[:1], {}), ([], [Waits("ABC-19", "no label names its repo")])) def test_an_item_whose_only_sub_task_do_epic_filed_is_not_split_until_marked(self) -> None: task = dataclasses.replace(issue("ABC-23", "repo:api", parent="ABC-20"), by_loop=True) self.assertEqual(chunks([issue("ABC-20"), task], {}), ([Chunk("ABC-23", "api")], [Waits("ABC-20", "no label names its repo")])) def test_an_item_a_person_split_waits_to_be_closed_once_its_sub_tasks_are_done_and_blocks_until_then(self) -> None: found = chunks([issue("ABC-20", "repo:api"), issue("ABC-23", parent="ABC-20", done=True), issue("ABC-21", "repo:api", blockers=("ABC-20",))], {}) self.assertEqual(found, ([], [Waits("ABC-20", "its sub-tasks are done; close it in Jira"), Waits("ABC-21", "ABC-20 blocks it")])) def test_an_item_marked_split_whose_sub_tasks_are_done_waits_for_nobody(self) -> None: self.assertEqual(chunks([issue("ABC-20", "split-by-repo"), issue("ABC-23", "repo:api", parent="ABC-20", done=True)], {}), ([], [])) def test_a_persons_sub_task_without_a_label_waits_for_one_and_says_do_epic_plans_none(self) -> None: found = chunks([issue("ABC-20", "repo:api"), issue("ABC-23", parent="ABC-20")], {}) self.assertEqual(found, ([], [Waits("ABC-23", "no label names its repo; label it in Jira, since do-epic plans no sub-task")])) def test_names_each_blocker_outside_the_epic(self) -> None: self.assertEqual(chunks([issue("ABC-20", "repo:api", blockers=("XYZ-1", "XYZ-2"))], {})[1], [ Waits("ABC-20", "XYZ-1 and XYZ-2 block it; do-epic cannot see XYZ-1 and XYZ-2, outside the epic, finish: remove such a link in Jira once its issue is done"), ]) def test_an_issue_waits_for_its_pick_its_human_and_its_blockers(self) -> None: found = chunks([ issue("ABC-20"), issue("ABC-21", "do-epic-human"), issue("ABC-22", "repo:api", "repo:web"), issue("ABC-23", "repo:api", blockers=("ABC-20", "ABC-30", "XYZ-1")), issue("ABC-30", "repo:api", done=True), ], {}) self.assertEqual(found, ([], [ Waits("ABC-20", "no label names its repo"), Waits("ABC-21", "it is a human's task"), Waits("ABC-22", "ABC-22 is labelled with 2 picks: repo:api, repo:web; remove the labels of all but the right one"), Waits("ABC-23", "ABC-20 and XYZ-1 block it; do-epic cannot see XYZ-1, outside the epic, finish: remove such a link in Jira once its issue is done"), ])) def test_a_human_task_that_blocks_an_open_issue_is_a_chunk_to_await_and_one_that_blocks_none_waits(self) -> None: found = chunks([issue("ABC-20", "do-epic-human"), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human")], {}) self.assertEqual(found, ([Chunk("ABC-20", None, human=True)], [Waits("ABC-21", "ABC-20 blocks it"), Waits("ABC-22", "it is a human's task")])) def test_a_human_task_is_awaited_while_it_blocks_a_sub_task_through_its_split_parent(self) -> None: found = chunks([issue("ABC-19", "do-epic-human"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")], {}) self.assertEqual(found, ([Chunk("ABC-19", None, human=True)], [Waits("ABC-23", "ABC-19 blocks it")])) def test_a_human_task_that_is_blocked_itself_or_blocks_only_done_issues_waits(self) -> None: found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "do-epic-human", blockers=("ABC-19",)), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human"), issue("ABC-23", "repo:api", done=True, blockers=("ABC-22",))], {}) self.assertEqual(found, ([Chunk("ABC-19", "api")], [Waits("ABC-20", "it is a human's task"), Waits("ABC-21", "ABC-20 blocks it"), Waits("ABC-22", "it is a human's task")])) def test_what_blocks_a_split_item_blocks_its_sub_tasks(self) -> None: found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")], {}) self.assertEqual(found, ([Chunk("ABC-19", "api")], [Waits("ABC-23", "ABC-19 blocks it")])) def test_an_issue_in_an_unblocking_status_unblocks_what_it_blocks_and_waits_to_be_done_itself(self) -> None: issues = [issue("ABC-19", "repo:api", status="Release Ready"), issue("ABC-20", "repo:api", blockers=("ABC-19",)), issue("ABC-21", "repo:api", status="Code Review"), issue("ABC-22", "repo:api", blockers=("ABC-21",)), issue("ABC-23", "repo:api", done=True), issue("ABC-24", "repo:api", blockers=("ABC-23", "ABC-21", "ABC-22"))] self.assertEqual(chunks(issues, {}, ("Release Ready", "Shipped")), ([Chunk("ABC-20", "api"), Chunk("ABC-21", "api")], [ Waits("ABC-19", "its work has landed: it is Release Ready, and the epic's finishing waits until Jira counts it done"), Waits("ABC-22", "ABC-21 blocks it, until it is Release Ready, Shipped or done"), Waits("ABC-24", "ABC-21 and ABC-22 block it, until each is Release Ready, Shipped or done"), ])) self.assertEqual(chunks(issues[:2], {}), ([Chunk("ABC-19", "api")], [Waits("ABC-20", "ABC-19 blocks it")])) self.assertEqual(held_up(issues, ("Release Ready", "Shipped")), {"ABC-21": ["ABC-22", "ABC-24"], "ABC-22": ["ABC-24"]}) def test_a_humans_task_gets_no_window_for_an_issue_it_blocks_that_is_in_an_unblocking_status(self) -> None: issues = [issue("ABC-19", "do-epic-human"), issue("ABC-20", "repo:api", blockers=("ABC-19",), status="Release Ready")] self.assertEqual(chunks(issues, {}, ("Release Ready",))[0], []) def test_an_unblocking_status_matches_whatever_its_case(self) -> None: issues = [issue("ABC-19", "repo:api", status="Release Ready"), issue("ABC-20", "repo:api", blockers=("ABC-19",))] self.assertEqual(chunks(issues, {}, ("release ready",)), ([Chunk("ABC-20", "api")], [Waits("ABC-19", "its work has landed: it is Release Ready, and the epic's finishing waits until Jira counts it done")])) def test_names_an_unblocking_status_only_for_a_blocker_inside_the_epic(self) -> None: unseen = "outside the epic, finish: remove such a link in Jira once its issue is done" issues = [issue("ABC-19", "repo:api"), issue("ABC-20", "repo:api", blockers=("XYZ-1",)), issue("ABC-21", "repo:api", blockers=("ABC-19", "XYZ-1")), issue("ABC-22", "repo:api", blockers=("ABC-19", "ABC-20", "XYZ-1"))] self.assertEqual(chunks(issues, {}, ("Release Ready",))[1], [ Waits("ABC-20", f"XYZ-1 blocks it; do-epic cannot see XYZ-1, {unseen}"), Waits("ABC-21", f"ABC-19 and XYZ-1 block it, until ABC-19 is Release Ready or done; do-epic cannot see XYZ-1, {unseen}"), Waits("ABC-22", f"ABC-19 and ABC-20 and XYZ-1 block it, until ABC-19 and ABC-20 are Release Ready or done; do-epic cannot see XYZ-1, {unseen}"), ]) def test_a_split_item_unblocks_what_it_blocks_once_each_sub_task_is_in_an_unblocking_status(self) -> None: issues = [issue("ABC-20", "split-by-repo"), issue("ABC-23", "repo:api", parent="ABC-20", status="Release Ready"), issue("ABC-24", "repo:web", parent="ABC-20", done=True), issue("ABC-21", "repo:api", blockers=("ABC-20",))] self.assertEqual(chunks(issues, {}, ("Release Ready",))[0], [Chunk("ABC-21", "api")]) self.assertEqual(chunks(issues, {})[0], [Chunk("ABC-23", "api")]) self.assertEqual(chunks([*issues[:2], issue("ABC-24", "repo:web", parent="ABC-20"), issues[3]], {}, ("Release Ready",))[0], [Chunk("ABC-24", "web")]) class RoomInARepo(unittest.TestCase): def test_a_repo_with_room_and_no_loop_claude_takes_a_chunk(self) -> None: self.assertIsNone(refusal("api", RepoRoom(limit=2, running=1, loop_claude=False))) def test_a_full_repo_takes_none(self) -> None: self.assertEqual(refusal("api", RepoRoom(limit=2, running=2, loop_claude=False)), "api runs as many chunks as its `parallel-chunks` allows: 2") def test_a_repo_loop_claude_runs_chunks_in_takes_none(self) -> None: self.assertEqual(refusal("api", RepoRoom(limit=2, running=0, loop_claude=True)), "loop-claude runs chunks in api") class Tmux: """Stands in for tmux: `windows` are the rows of `list-windows -a`, as session, name, dead and root; a started window joins them.""" def __init__(self, *windows: tuple[str, str, bool, str], owners: dict[str, str] | None = None) -> None: self.windows, self.owners, self.calls = list(windows), owners or {}, [] def __call__(self, args: list[str]) -> subprocess.CompletedProcess[str]: self.calls.append(args) out = "" if args[0] == "list-windows" and "-a" in args: out = "".join(f"{session}\t{name}\t{int(dead)}\t@{at}\t{root}\n" for at, (session, name, dead, root) in enumerate(self.windows)) elif args[0] == "list-windows": out = "".join(f"{name}\t{int(dead)}\t@{at}\n" for at, (session, name, dead, _) in enumerate(self.windows) if f"={session}" == args[2]) elif args[0] == "show-options": out = self.owners.get(args[3].removeprefix("=").removesuffix(":"), "") + "\n" elif args[0] in ("new-session", "new-window"): session = args[args.index("-s") + 1] if args[0] == "new-session" else args[args.index("-t") + 1].removeprefix("=").removesuffix(":") self.windows.append((session, args[args.index("-n") + 1], False, args[args.index("-c") + 1])) out = f"@{len(self.windows) - 1}\n" elif args[0] == "rename-window": at = int(args[2].removeprefix("%")) self.windows[at] = (self.windows[at][0], args[3], *self.windows[at][2:]) elif args[0] == "set-option" and tmux.ROOT in args: at = int(args[args.index("-t") + 1].removeprefix("%").removeprefix("@")) self.windows[at] = (*self.windows[at][:3], "" if "-u" in args else args[-1]) elif args[0] == "kill-window": self.windows[int(args[2].removeprefix("@"))] = ("", "", True, "") return subprocess.CompletedProcess(args, 0, out, "") def started(self) -> list[tuple[str, str, str]]: """Each window started, as its session, its name and its command's words after the launcher.""" return [(args[3].removeprefix("=").removesuffix(":"), args[args.index("-n") + 1], " ".join(args[args.index("--") + 2:])) for args in self.calls if args[0] in ("new-session", "new-window")] class StartingAnEpicsChunks(unittest.TestCase): def setUp(self) -> None: folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.home = pathlib.Path(folder.name) self.order: tuple[str, ...] = () def epic(self, cap: int, **limits: int) -> Epic: """An epic whose repos are checked out under the home folder, each with its `parallel-chunks`.""" def locate(name: str) -> tuple[pathlib.Path, int] | Failure: return (self.home / "code" / name, limits[name]) if name in limits else Failure(f"no project config names {name}") return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"LOOP_CLAUDE_X": "1", "OTHER": "2"}, {}, self.order) def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started: found = start_chunks(epic, issues, False, own, run) assert not isinstance(found, Failure), found return found def test_starts_a_window_per_chunk_up_to_the_epics_cap(self) -> None: run = Tmux() found = self.start(self.epic(2, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "repo:web")], run) self.assertEqual(found, Started(["ABC-20", "ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")])) self.assertEqual(run.started(), [("epic-ABC-12", "ABC-20", f"{CHUNK_FLAG} ABC-20 ABC-12"), ("epic-ABC-12", "ABC-21", f"{CHUNK_FLAG} ABC-21 ABC-12")]) self.assertEqual([args[args.index("-c") + 1] for args in run.calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / ".local/state/do-epic/ABC-12")]) self.assertIn("LOOP_CLAUDE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")]) self.assertNotIn("OTHER=2", run.calls[[args[0] for args in run.calls].index("new-session")]) def parked(self, issue_key: str, on: str = "an approval") -> None: self.assertIsNone(park(self.home / ".local/state/do-epic/ABC-12", Parked(issue_key, f"/code/api-{issue_key}", "7", "0c0f", on))) def test_starts_the_chunks_in_the_epics_start_order_and_those_it_leaves_out_last_in_backlog_order(self) -> None: self.order = ("ABC-23", "ABC-21") run = Tmux() issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "do-epic-claude"), issue("ABC-23", "do-epic-claude")] found = self.start(self.epic(3), issues, run) self.assertEqual(found, Started(["ABC-23", "ABC-21", "ABC-20"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 3")])) def test_the_epics_finishing_starts_whatever_the_start_order_names(self) -> None: self.order = ("ABC-20",) found = start_chunks(self.epic(1), [issue("ABC-20", "do-epic-claude", done=True)], True, None, Tmux()) self.assertEqual(found, Started(["ABC-12"], [])) def test_a_parked_chunk_waits_in_its_window_and_takes_no_slot_of_the_epic_or_its_repo(self) -> None: self.parked("ABC-20") run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")) 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, ""),)): with self.subTest(windows=windows): run = Tmux(*windows, ("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(["ABC-20"], [])) self.assertEqual(run.windows[-1], ("epic-ABC-12", "ABC-20", False, str(self.home / ".local/state/do-epic/ABC-12"))) self.assertEqual([name for _, name, dead, _ in run.windows if dead], [""] * len(windows)) def test_a_human_task_that_blocks_an_issue_gets_a_window_that_takes_no_slot_of_the_epics_cap(self) -> None: run = Tmux() found = self.start(self.epic(1, api=1), [issue("ABC-19", "do-epic-human"), issue("ABC-20", "do-epic-claude"), issue("ABC-21", "repo:api", blockers=("ABC-19",))], run) self.assertEqual(found, Started(["ABC-19", "ABC-20"], [Waits("ABC-21", "ABC-19 blocks it")])) def test_a_human_task_with_a_window_that_awaits_it_starts_no_second_window(self) -> None: run = Tmux(("epic-ABC-12", "ABC-19 awaits a human's task", False, "")) found = self.start(self.epic(1, api=1), [issue("ABC-19", "do-epic-human"), issue("ABC-21", "repo:api", blockers=("ABC-19",))], run) self.assertEqual(found, Started([], [Waits("ABC-19", HUMAN_WAIT), Waits("ABC-21", "ABC-19 blocks it")])) self.assertEqual(run.started(), []) def test_a_parked_chunk_that_starts_again_leaves_the_epics_cap_to_the_others(self) -> None: self.parked("ABC-20") found = self.start(self.epic(1, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], Tmux()) self.assertEqual(found, Started(["ABC-20", "ABC-21"], [])) def test_a_chunk_that_hands_on_starts_no_parked_chunk_whose_window_stopped(self) -> None: self.parked("ABC-20") found = self.start(self.epic(2, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], Tmux(), own="ABC-21") self.assertEqual(found, Started([], [Waits("ABC-20", "its window stopped; run `do-epic ABC-12` to start it again")])) def test_a_chunk_that_parks_frees_its_slot_for_the_next(self) -> None: self.parked("ABC-20") run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")) found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], run, own="ABC-20") self.assertEqual(found, Started(["ABC-21"], [])) def test_stops_on_a_parked_chunk_it_cannot_read_and_starts_none(self) -> None: self.parked("ABC-20") file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20").write_text("{") run = Tmux() found = start_chunks(self.epic(2, api=2), [issue("ABC-21", "repo:api")], False, None, run) assert isinstance(found, Failure) self.assertIn("cannot read the parked chunk in ", found.reason) self.assertEqual(run.started(), []) def test_hands_each_chunk_the_variable_that_makes_its_merge_park(self) -> None: run = Tmux() self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], run) self.assertIn("CHUNK_PR_PARKS=1", run.calls[[args[0] for args in run.calls].index("new-session")]) def resumed(self, epic: Epic, run: Tmux) -> str | None: """resume for the parked chunk in the first window, which changes the repo api.""" return resume(epic, "api", tmux.Window("epic-ABC-12", "ABC-20", "%0"), run) def test_a_parked_chunk_resumes_into_a_free_slot_and_counts_in_its_repo_again(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, ""), ("epic-ABC-12", "ABC-21 awaits its checks", False, "")) 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 = { "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1": (self.epic(1, api=2), Tmux(parked, ("epic-ABC-12", "ABC-21", False, str(self.home / "code/web")))), "api runs as many chunks as its `parallel-chunks` allows: 1": (self.epic(2, api=1), Tmux(parked, ("epic-XYZ-1", "XYZ-5", False, str(self.home / "code/api")))), "loop-claude runs chunks in api": (self.epic(2, api=1), Tmux(parked, ("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})), "no project config names api": (self.epic(2), Tmux(parked)), } for reason, (epic, run) in cases.items(): with self.subTest(reason=reason): self.assertEqual(self.resumed(epic, run), reason) self.assertEqual(run.windows[0], parked) def test_a_running_chunk_counts_and_is_not_started_twice(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20 ?", False, str(self.home / "code/api"))) found = self.start(self.epic(2, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run) self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")])) def test_a_repo_takes_its_parallel_chunks_across_epics(self) -> None: run = Tmux(("epic-XYZ-1", "XYZ-5", False, str(self.home / "code/api"))) 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) self.assertEqual(found, Started([], [Waits("ABC-20", "loop-claude runs chunks in api")])) def test_a_stopped_loop_claude_window_keeps_no_repo(self) -> None: run = Tmux(("loop-api", "item-3", True, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")}) self.assertEqual(self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run).started, ["ABC-20"]) def test_a_repo_that_cannot_be_located_waits_with_the_reason(self) -> None: found = self.start(self.epic(3), [issue("ABC-20", "repo:api")], Tmux()) self.assertEqual(found, Started([], [Waits("ABC-20", "no project config names api")])) def test_the_human_restarts_a_stopped_chunk_in_place_of_its_window(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20", True, str(self.home / "code/api"))) self.assertEqual(self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], run).started, ["ABC-20"]) self.assertIn(["kill-window", "-t", "@0"], run.calls) def test_a_finished_chunk_leaves_its_room_and_restarts_no_stopped_chunk(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20", False, str(self.home / "code/api")), ("epic-ABC-12", "ABC-21", True, str(self.home / "code/api"))) found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run, own="ABC-20") self.assertEqual(found, Started(["ABC-22"], [Waits("ABC-21", "its window stopped; run `do-epic ABC-12` to start it again")])) def test_holds_each_repos_starting_lock_that_loop_claude_holds(self) -> None: self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], Tmux()) self.assertTrue((self.home / ".local/state/loop-claude/api/starting").is_file()) self.assertTrue((self.home / ".local/state/do-epic/ABC-12/starting").is_file()) def test_a_parked_chunk_resumes_under_the_starting_lock_of_its_repos_checkout(self) -> None: self.assertIsNone(self.resumed(self.epic(1, api=1), Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")))) self.assertEqual([lock.parent.name for lock in (self.home / ".local/state/loop-claude").glob("*/starting")], ["api"]) def test_the_waits_keep_the_trackers_rank_order(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20", True, str(self.home / "code/api")), ("epic-ABC-12", "ABC-22", False, str(self.home / "code/api"))) found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21"), issue("ABC-22", "repo:api")], run, own="ABC-22") self.assertEqual([wait.issue for wait in found.waits], ["ABC-20", "ABC-21"]) def test_a_chunks_window_never_marks_the_session_as_a_checkouts(self) -> None: run = Tmux() self.start(self.epic(2, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude")], run) options = [args[-2] for args in run.calls if args[0] == "set-option"] self.assertIn(tmux.ROOT, options) self.assertNotIn(tmux.OWNER, options) def test_says_which_lock_it_could_not_take(self) -> None: (self.home / ".local/state/do-epic").mkdir(parents=True) (self.home / ".local/state/do-epic/ABC-12").write_text("", encoding="utf-8") found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux()) assert isinstance(found, Failure) self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/do-epic/ABC-12: \\w") def test_says_which_repos_lock_it_could_not_take(self) -> None: (self.home / ".local/state").mkdir(parents=True) (self.home / ".local/state/loop-claude").write_text("", encoding="utf-8") found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux()) assert isinstance(found, Failure) self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") self.assertRegex(self.resumed(self.epic(1, api=1), Tmux()) or "", f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self) -> None: def failing(args: list[str]) -> subprocess.CompletedProcess[str]: raise OSError("tmux is gone") with self.assertRaisesRegex(OSError, "tmux is gone"): start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, failing) with self.assertRaisesRegex(OSError, "tmux is gone"): resume(self.epic(1, api=1), "api", tmux.Window("epic-ABC-12", "ABC-20", "%0"), failing) CONFIG = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {"changelog": pathlib.Path("/code/api/CHANGELOG.md")}, epic=settings.Epic("https://acme.atlassian.net", "API-1")) class TheFirstPrompt(unittest.TestCase): def test_the_task_names_the_checkout_and_branch_and_quotes_a_description_only_where_there_is_one(self) -> None: labels = "`repo:` for the repo that works it, `do-epic-claude` for work of Claude's that changes no repo, or `do-epic-human` for a task of the human's" told = ( f"File a finding about one of the epic's goals in the epic, with `/b/do-epic ABC-12 --file \"\" --label