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

401 lines
27 KiB
Python

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, 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") -> 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_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")]))
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)
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, 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_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_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:<name>` 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 \"<summary>\" --label <label>` and its detail on stdin. The label is {labels}; leave it out where you cannot tell, and the next `do-epic` the human runs picks it. "
"Where filing fails and says the issue may exist, ask the human to look before you file it again. File a finding about a repo's goals by that repo's rules. Where unsure which, ask the human. "
"Record a decision that governs the epic, such as an answer the human typed, with `/b/do-epic ABC-12 --record-decision \"<title>\"` and its text on stdin. Write the issue and the decision in Swedish, the epic's language."
)
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", "/code/api", pathlib.Path("/b/do-epic"), "Swedish", CONFIG)
self.assertTrue(task.startswith(f"Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout /code/api, on the branch ABC-20. {told} "))
self.assertTrue(task.endswith(" Its summary: Do ABC-20"))
def test_a_chunk_without_a_repo_is_told_nothing_of_shipping(self) -> None:
task = chunk_prompt.task(issue("ABC-20"), "ABC-12", None, pathlib.Path("/b/do-epic"), "Swedish", None)
self.assertTrue(task.endswith("Swedish, the epic's language. Its summary: Do ABC-20"))
self.assertNotIn("--finish", task)
def test_a_repo_with_a_plan_file_is_told_to_add_a_bullet_to_its_changelog_where_it_publishes(self) -> None:
config = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {"changelog": pathlib.Path("/code/api/CHANGELOG.md")})
told = chunk_prompt.shipping(config)
self.assertTrue(told.startswith("The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`."))
self.assertIn("Where the repo publishes something others consume, add one bullet to `## Unreleased` in `CHANGELOG.md`", told)
def test_a_changelog_outside_the_checkout_or_on_a_page_is_named_as_the_config_spells_it(self) -> None:
config = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {"changelog": pathlib.Path("/c/api/CHANGELOG.md")})
self.assertIn("in `/c/api/CHANGELOG.md`", chunk_prompt.shipping(config))
paged = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {}, pages={"changelog": settings.Page("https://acme.atlassian.net", "7", "confluence:https://acme.atlassian.net/wiki/pages/7")})
self.assertIn("in `confluence:https://acme.atlassian.net/wiki/pages/7`", chunk_prompt.shipping(paged))
def test_a_repo_with_its_plan_in_jira_is_told_to_leave_the_changelog_as_it_is(self) -> None:
told = chunk_prompt.shipping(CONFIG)
self.assertTrue(told.startswith("The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`."))
self.assertIn("leave the changelog as it is", told)
self.assertNotIn("## Unreleased", told)
def test_an_answer_the_judge_quoted_names_the_epics_description_first(self) -> None:
self.assertTrue(chunk_prompt.WORKER.answered("Q", "A", Route(Rung("off-the-ladder")), None, False).startswith("Your question: Q\n\nthe epic's description, "))
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, asks=True), "/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()