import contextlib import dataclasses import io import pathlib import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from agent_cycle import escalation_mark, judge, tmux from do_epic import chunk_prompt, main from do_epic.backend.fake import MemoryEpic from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from do_epic.test_do_epic import SETTINGS from do_epic.test_scheduler import issue from failure import Failure from loop_claude.loop.reload import LoopRun from loop_claude.loop.this_loop import Loop from loop_claude.test_loop_claude import FakeEffects from loop_state.paths import paths_from from model_routing.ladder import Rung from model_routing.route import Route DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n" @dataclasses.dataclass(frozen=True) class Description: """Stands in for an epic's description in Jira.""" text: str | Failure def read(self) -> str | Failure: return self.text class DoEpicTest(unittest.TestCase): def setUp(self) -> None: made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name).resolve() folder = self.home / ".claude-projects" / "do-epic" folder.mkdir(parents=True) (folder / "config.toml").write_text(SETTINGS, encoding="utf-8") (folder / "repo-rule.md").write_text("A label that equals a repo's name names that repo.\n", encoding="utf-8") self.issues = [issue("ABC-20"), dataclasses.replace(issue("ABC-21", "do-epic-claude"), detail="Tidy the docs.", scores={"L": 3, "E": 2, "I": 3})] self.description: str | Failure = DESCRIPTION def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]: return MemoryEpic(key, list(self.issues)), EpicRecord(Description(self.description)) # type: ignore[arg-type] def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, env or {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend) return code, out.getvalue(), err.getvalue() class TheCommand(DoEpicTest): def test_prints_the_help_for_anything_but_one_epic_key(self) -> None: for argv, code in ((["--help"], 0), (["-h"], 0), ([], 1), (["abc"], 1), (["ABC-12", "ABC-13"], 1), (["--chunk", "x", "ABC-12"], 1)): with self.subTest(argv=argv): ran_code, out, err = self.run_main(argv, FakeEffects()) self.assertEqual((ran_code, (err if code else out).split(" ", 1)[1]), (code, main.HELP + "\n")) def test_refuses_a_tmux_too_old_naming_do_epic(self) -> None: code, _, err = self.run_main(["ABC-12"], FakeEffects(tmux_version="tmux 3.1")) self.assertEqual(code, 1) self.assertIn("do-epic runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1", err) def test_starts_the_chunks_and_says_why_each_other_issue_waits(self) -> None: fake = FakeEffects(on_terminal=False) code, out, _ = self.run_main(["ABC-12"], fake, {"LOOP_CLAUDE_WORKER_MODEL": "m"}) self.assertEqual(code, 0) self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out) self.assertIn("ABC-20 waits: no label names its repo\n", out) started = [args for args in fake.tmux_calls if args[0] == "new-session"] self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) # The session is no checkout's, so nothing marks it as one's. self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"]) def test_stops_on_an_epic_it_cannot_read(self) -> None: self.description = Failure("Jira answered 401") code, _, err = self.run_main(["ABC-12"], FakeEffects()) self.assertEqual(code, 1) self.assertIn("Jira answered 401\n", err) def test_a_chunk_outside_a_tmux_window_says_how_to_run_do_epic(self) -> None: fake = FakeEffects() code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake) self.assertEqual(code, 1) self.assertIn("--chunk is how do-epic starts itself in a tmux window; run do-epic \n", err) self.assertEqual(fake.dms, ["do-epic --chunk ABC-21 ABC-12 stopped: --chunk is how do-epic starts itself in a tmux window; run do-epic "]) def test_a_chunk_of_an_issue_the_epic_lacks_stops(self) -> None: code, _, err = self.run_main(["--chunk", "ABC-99", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"}) self.assertEqual(code, 1) self.assertIn("ABC-99 is no issue of the epic ABC-12\n", err) class ACycleOfAChunkWithoutARepo(DoEpicTest): def cycle(self, env: dict[str, str] | None = None) -> main.Cycle: fake = FakeEffects(git=[Failure("no git"), Failure("no git")]) paths = paths_from(self.home) config = main.load(self.home) assert not isinstance(config, Failure) store, record = self.backend(config, "ABC-12") epic = main.EpicRun("ABC-12", config, store, record, paths, env or {}, pathlib.Path("/b/do-epic"), fake.effects()) root = main.chunk_root(self.issues[1], epic) assert isinstance(root, str) 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, epic) assert isinstance(found, main.Cycle), found return found def test_routes_on_the_repoless_model_by_the_issues_scores(self) -> None: cycle = self.cycle() assert cycle.project is not None self.assertEqual(cycle.project.rung.model, "claude-opus-5-5") self.assertEqual(cycle.route, Route(cycle.project.worker_rung(3), 21, 3, 5)) self.assertEqual(cycle.judge.model, "claude-opus-5-5") self.assertEqual(self.cycle({"LOOP_CLAUDE_WORKER_MODEL": "off-the-ladder"}).route, Route(Rung("off-the-ladder"))) def test_works_in_the_epics_folder_and_archives_apart_from_loop_claude(self) -> None: cycle = self.cycle() self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/do-epic/ABC-12"), self.home / ".claude/do-epic-transcripts/ABC-12", "")) def test_the_premises_are_the_epics_goals_and_audience(self) -> None: self.assertEqual(self.cycle().premises, "the epic ABC-12's description:\n## Goals\nShip the import.\n\n## Audience\nThe client's team.") def test_the_task_is_the_issue(self) -> None: self.assertEqual(self.cycle().task, "Work the Jira issue ABC-21 of the epic ABC-12 as one chunk, which changes no repo: work in the folder you start in. Its summary: Do ABC-21\n\nIts description:\n\nTidy the docs.") def test_an_issue_without_scores_runs_on_the_projects_rung(self) -> None: self.issues[1] = dataclasses.replace(self.issues[1], scores={}) cycle = self.cycle() assert cycle.project is not None self.assertEqual(cycle.route, Route(cycle.project.rung)) class WhatAWorkerJudgeAndHumanRead(DoEpicTest): def test_every_prompt_names_do_epic_and_never_loop_claude(self) -> None: cycle = ACycleOfAChunkWithoutARepo.cycle(self) # type: ignore[arg-type] prompts = cycle.prompts texts = [ prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, ""), prompts.resumed("the work remaining", cycle.route, cycle.project), prompts.typed("Which one?", "The first.", cycle.route, cycle.project, True), judge.judge_rules(prompts.answer_destinations, prompts.driver), str(judge.judge_schema(prompts.driver)), ] for text in texts: self.assertNotIn("loop-claude", text) self.assertIn(f"do-epic runs you on {cycle.route.rung}, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue.", texts[0]) self.assertNotIn("Chunk items:", texts[1]) # The worker's prompt and the judge's rules word the request for a higher rung alike, from one place. for text in (texts[0], texts[3]): self.assertIn(escalation_mark.asks_higher_rung(chunk_prompt.DRIVER), text) self.assertEqual(escalation_mark.asks_higher_rung(chunk_prompt.DRIVER), "asking do-epic for a higher rung") if __name__ == "__main__": unittest.main()