Files
claude-config/bin/do_epic/test_scheduler.py
T

172 lines
9.9 KiB
Python

import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from agent_cycle import tmux
from do_epic.backend.protocol import EpicIssue
from do_epic.epic_record import parallel_chunks_in
from do_epic.scheduler import Chunk, chunks, CHUNK_FLAG, Epic, RepoRoom, refusal, start_chunks, Started, Waits
from failure import Failure
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_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"),
]))
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())
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), "")])
if __name__ == "__main__":
unittest.main()