import contextlib import dataclasses import io import json import pathlib import shutil import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic import chunk_prompt, main from project_config.test_project_config import configured from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from agent_cycle import escalation_mark, judge, tmux from failure import Failure from loop_claude.test_loop_claude import FakeEffects, judged, Worker from do_epic.test_scheduler import issue from loop_claude.loop.this_loop import Loop from loop_claude.loop.reload import LoopRun from do_epic.backend.fake import MemoryEpic from loop_state.paths import paths_from from model_routing.route import Route from model_routing.ladder import Rung from do_epic.test_do_epic import SETTINGS 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 TheLauncher(unittest.TestCase): def test_the_repo_ships_a_do_epic_that_prints_its_help(self) -> None: launcher = pathlib.Path(__file__).resolve().parents[1] / "do-epic" ran = subprocess.run([str(launcher), "--help"], capture_output=True, text=True, timeout=60) self.assertEqual((ran.returncode, ran.stdout.split(" ", 2)[2]), (0, main.HELP + "\n")) tracked = subprocess.run(["git", "ls-files", "--error-unmatch", launcher.name], capture_output=True, cwd=launcher.parent) self.assertEqual(tracked.returncode, 0, "bin/do-epic is not in the repo; .gitignore lists what it keeps") 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), (["--chunk", "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()) place = main.chunk_root(self.issues[1], epic) assert isinstance(place, tuple) root, in_repo = place 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, in_repo, 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"))) self.assertEqual(self.cycle({"LOOP_CLAUDE_JUDGE_MODEL": "claude-fable-5-2"}).judge.model, "claude-fable-5-2") 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_records_are_the_epics_scoring_and_decisions_then_the_humans_rules(self) -> None: self.description = DESCRIPTION + "\n## Scoring\nE + I, bar 4.\n\n## Decisions\n### Merges squash\nAlways.\n" (self.home / ".claude").mkdir() (self.home / ".claude/CLAUDE.md").write_text("# Global\n", encoding="utf-8") self.assertEqual(self.cycle().records, "From the epic ABC-12's description, ## Scoring:\nE + I, bar 4.\n\nFrom the epic ABC-12's description, ## Decisions:\n### Merges squash\nAlways.\n\nFrom ~/.claude/CLAUDE.md:\n# Global") def test_stops_where_a_section_of_the_epics_records_cannot_be_read(self) -> None: self.description = DESCRIPTION + "\n## Scoring\nA.\n\n## Scoring\nB.\n" with self.assertRaises(AssertionError) as raised: self.cycle() self.assertIn("the epic ABC-12's description: the epic's description has ## Scoring more than once - the judge cannot read the records.", str(raised.exception)) 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. File a finding about one of the epic's goals in the epic, with `do-epic ABC-12 --file \"\" [--label