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, CHUNK_FLAG, chunks, Epic, refusal, RepoRoom, start_chunks, Started, Waits from do_epic import chunk_prompt from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.epic_record import parallel_chunks_in from loop_claude.cycle import prompts from model_routing.route import Route from model_routing.ladder import Rung from agent_cycle import tmux def issue(key: str, *labels: str, done: bool = False, blockers: tuple[str, ...] = (), parent: str = "ABC-12") -> EpicIssue: return EpicIssue(key, f"Do {key}", "", tuple(sorted(labels)), None, "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_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 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_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")])) 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] == "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) 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"}) def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started: found = start_chunks(epic, issues, 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 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_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_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")], None, Tmux()) assert isinstance(found, Failure) self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/do-epic/ABC-12: \\w") class TheFirstPrompt(unittest.TestCase): def test_the_task_names_the_checkout_and_branch_and_quotes_a_description_only_where_there_is_one(self) -> None: self.assertEqual(chunk_prompt.task(issue("ABC-20"), "ABC-12", "/code/api"), "Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout /code/api, on the branch ABC-20. Its summary: Do ABC-20") def test_opens_with_the_task_then_the_rung_then_the_premises(self) -> None: rest = f"The issue sets the chunk's scope. The goals below choose between ways to deliver that scope, and never widen it. The epic's goals rank first, then code health ({chunk_prompt.CODE_HEALTH}), then the repo's.\n\nFrom P" start = f"T\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE}\n\n" self.assertEqual(chunk_prompt.fresh("T", "P", Route(Rung("off-the-ladder")), None, ""), start + rest) routed = chunk_prompt.fresh("T", "P", Route(Rung("off-the-ladder"), 21, 3, 5), None, "") self.assertTrue(routed.startswith(start + "do-epic runs you on off-the-ladder, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue."), routed) self.assertTrue(routed.endswith("\n\n" + rest), routed) class WindowsAcrossSessions(unittest.TestCase): def test_lists_each_window_with_its_session_and_root(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20 ?", False, "/code/api"), ("loop-api", "item-3", True, "")) self.assertEqual(tmux.everywhere(run), [tmux.Placed("epic-ABC-12", tmux.Listed("ABC-20", "@0", False), "/code/api"), tmux.Placed("loop-api", tmux.Listed("item-3", "@1", True), "")]) self.assertEqual(run.calls, [["list-windows", "-a", "-F", f"#{{session_name}}\t#{{window_name}}\t#{{pane_dead}}\t#{{window_id}}\t#{{{tmux.ROOT}}}"]]) def test_without_a_tmux_server_there_are_none(self) -> None: self.assertEqual(tmux.everywhere(lambda args: subprocess.CompletedProcess(args, 1, "epic-ABC-12\tABC-20\t0\t@0\t/code/api\n", "")), []) def test_a_started_chunk_joins_the_sessions_windows_as_running(self) -> None: found = tmux.start_chunk(tmux.Window("epic-ABC-12", "ABC-20", ""), "/code/api", {}, ["do-epic"], [tmux.Listed("ABC-20", "@0", True), tmux.Listed("ABC-21", "@1", False)], False, Tmux(("epic-ABC-12", "ABC-20", True, "/code/api"), ("epic-ABC-12", "ABC-21", False, "/code/api"))) self.assertEqual(found, [tmux.Listed("ABC-21", "@1", False), tmux.Listed("ABC-20", "", False)]) if __name__ == "__main__": unittest.main()