import contextlib import dataclasses import io import json import pathlib import shutil import subprocess import sys import tempfile import typing import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic import chunk_prompt, main, planning from chunk_driver.chunk_run import ChunkRun from project_config.doubles import configured from do_epic.config import DoEpicConfig from project_config.settings import Epic, Finish from do_epic.epic_record import EpicRecord from agent_cycle import escalation_mark, judge, tmux from failure import Failure from loop_effects.doubles import FakeEffects, judged, Worker from do_epic.test_gates import Forge from do_epic.test_scheduler import issue from chunk_driver.this_loop import Loop from do_epic.backend.fake import MemoryEpic from do_epic import parked from loop_state.paths import paths_from from text_files.file_writes import replace_file from model_routing.route import Route from model_routing.ladder import Rung from do_epic.test_do_epic import SETTINGS from do_epic.backend.jira_start import Start DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n" def structured(output: object, key: str | None = "structured_output") -> subprocess.CompletedProcess[str]: """claude's reply that holds output as its structured answer. Where key is None, output is the whole result event.""" return subprocess.CompletedProcess([], 0, json.dumps({"type": "result", key: output} if key else output), "") @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", "do-epic-human"), dataclasses.replace(issue("ABC-21", "do-epic-claude"), detail="Tidy the docs.", scores={"L": 3, "E": 2, "I": 3})] self.description: str | Failure = DESCRIPTION # What the forge answers each read of a chunk's gate, in turn; the last answers every later read. No worktree has the chunk's branch, so no chunk parks. self.forges = [Forge(worktrees="worktree /code/api\nbranch refs/heads/main\n")] self.gate_reads = 0 def forge_at(self, folder: str): def run(command: list[str]) -> str | Failure: # A read of a gate opens with the checkout's worktrees. self.gate_reads += command[:2] == ["git", "worktree"] return self.forges[min(self.gate_reads, len(self.forges)) - 1].at(folder)(command) return run 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 worker(self) -> Worker: return Worker(paths_from(self.home).claude_code_transcripts.parent) def repo_chunk(self) -> pathlib.Path: """Makes ABC-20 the one issue, a chunk in the repo api whose checkout holds its premises; the folder of the repo's config.""" checkout = self.home / "code" / "api" folder = configured(self, checkout, home=self.home) (checkout / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8") self.issues = [issue("ABC-20", "repo:api")] return folder def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> main.EpicRun: config = main.load(self.home) assert not isinstance(config, Failure) store, record = self.backend(config, "ABC-12") return main.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects()) 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, forge_at=self.forge_at) return code, out.getvalue(), err.getvalue() class TheJiraBackend(unittest.TestCase): def test_reads_the_epic_with_the_credentials_and_the_finish_the_config_names(self) -> None: config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", Finish("Mark as done", "Done")) store, record = main.jira_backend(config, "ABC-12") self.assertEqual((store.epic, store.env_file, store.finish), (Epic("https://acme.atlassian.net", "ABC-12"), pathlib.Path("/h/jira.env"), Finish("Mark as done", "Done"))) # type: ignore[attr-defined] self.assertEqual((record.description.epic, record.description.env_file), (store.epic, store.env_file)) # type: ignore[attr-defined] def test_starts_an_issue_as_the_config_says(self) -> None: config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", start=Start("In Progress", 6)) store, _ = main.jira_backend(config, "ABC-12") self.assertEqual(store.start, Start("In Progress", 6)) # type: ignore[attr-defined] def test_files_the_issue_types_the_config_names(self) -> None: config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", finding_type="Feature", review_type="Chore") store, _ = main.jira_backend(config, "ABC-12") self.assertEqual((store.finding_type, store.review_type), ("Feature", "Chore")) # type: ignore[attr-defined] 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: it is a human's task\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", "-e", "CHUNK_PR_PARKS=1", "-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_plans_an_issue_no_label_places_before_it_starts_the_chunks(self) -> None: self.issues = [issue("ABC-20")] fake = FakeEffects(on_terminal=False, claude=[structured({"parts": []}), structured({"pick": "claude"})]) code, out, err = self.run_main(["ABC-12"], fake) self.assertEqual(code, 0, err) self.assertLess(out.index("ABC-20 is labelled do-epic-claude\n"), out.index("started ABC-20 in the tmux session epic-ABC-12\n")) def test_starts_no_chunk_where_a_usage_limit_ends_the_planning(self) -> None: self.issues.append(issue("ABC-22")) limit = {"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"} fake = FakeEffects(claude=[structured(limit, None)]) code, _, err = self.run_main(["ABC-12"], fake) self.assertEqual(code, 1) self.assertIn("the epic is not planned, so no chunk started: You've hit your limit\n", err) self.assertEqual([args for args in fake.tmux_calls if args[0] == "new-session"], []) def test_says_why_the_epic_is_not_planned_in_full_and_starts_the_chunks_that_may_start(self) -> None: self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}, by_loop=True) for key in ("ABC-20", "ABC-21")] code, out, err = self.run_main(["ABC-12"], FakeEffects()) self.assertEqual(code, 0, err) self.assertIn("the epic ABC-12 is not planned in full: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", err) self.assertTrue(err.endswith("(2**S + 32)`\n")) self.assertIn("started ABC-20, ABC-21 in the tmux session epic-ABC-12\n", out) 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 test_naming_the_chunks_folder_doesnt_make_it(self) -> None: folder = self.home / ".local/state/do-epic/ABC-12" self.assertEqual(main.chunk_root("ABC-21", self.issues[1], self.epic_run(FakeEffects())), (str(folder), None)) self.assertFalse(folder.exists()) self.assertIsNone(main.folder_made(str(folder))) self.assertTrue(folder.is_dir()) def test_a_chunk_whose_folder_cannot_be_made_stops_with_the_reason(self) -> None: (self.home / ".local/state").mkdir(parents=True, exist_ok=True) (self.home / ".local/state/do-epic").write_text("", encoding="utf-8") code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"}) self.assertEqual(code, 1) self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/do-epic/ABC-12: \\w") def cycle(self, env: dict[str, str] | None = None, run: ChunkRun = ChunkRun(1)) -> main.Cycle: fake = FakeEffects(git=[Failure("no git"), Failure("no git")]) paths = paths_from(self.home) epic = self.epic_run(fake, env) place = main.chunk_root("ABC-21", self.issues[1], epic) assert isinstance(place, tuple) root, repo = place self.assertIsNone(main.folder_made(root)) 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(run, loop, repo is not None, 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_keeps_the_route_and_the_evidence_its_run_holds(self) -> None: kept = Route(Rung("claude-opus-5-5", "xhigh"), 21, 3, 5) cycle = self.cycle(run=ChunkRun(2, unfinished_evidence="the evidence", route=kept)) self.assertEqual((cycle.route, cycle.unfinished_evidence), (kept, "the evidence")) def test_a_chunk_that_was_not_parked_starts_on_the_drivers_own_prompts_with_no_facts(self) -> None: cycle = self.cycle() self.assertIs(cycle.prompts, chunk_prompt.WORKER) self.assertEqual(cycle.facts, "") 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: task = self.cycle().task self.assertTrue(task.startswith("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"), task) self.assertIn('with `/b/do-epic ABC-12 --file "" --label