import contextlib import io import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.test_main import Description, DESCRIPTION, DoEpicTest, MODELS, UNREAD from do_epic.config import DoEpicConfig, load from do_epic.epic_record import EpicRecord from failure import Failure from loop_claude.test_loop_claude import FakeEffects, judged, Worker from do_epic import findings, finish, main, scheduler from project_config.settings import Finish from do_epic.test_scheduler import issue from do_epic.backend.fake import MemoryEpic from loop_state.paths import paths_from from claude_code.session import session_named LAUNCHER = pathlib.Path("/b/do-epic") REVIEWED = [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "do-epic-claude", done=True), issue("ABC-30", "repo:api", "do-epic-release-review", done=True)] class WhenTheFinishingIsDue(DoEpicTest): def test_is_due_once_the_epic_holds_issues_and_none_is_open(self) -> None: self.assertIs(finish.due([]), False) self.assertIs(finish.due([issue("ABC-20", done=True), issue("ABC-21")]), False) self.assertIs(finish.due([issue("ABC-20", done=True), issue("ABC-21", done=True)]), True) def test_an_item_split_by_repo_is_done_once_its_sub_tasks_are(self) -> None: split = [issue("ABC-20", "split-by-repo"), issue("ABC-40", "repo:api", done=True, parent="ABC-20")] self.assertIs(finish.due(split), True) self.assertIs(finish.due([*split, issue("ABC-41", "repo:web", parent="ABC-20")]), False) def test_a_repo_lacks_its_review_while_a_done_issue_names_it_and_no_review_does(self) -> None: done = [issue("ABC-20", "repo:web", done=True), issue("ABC-21", "repo:api", done=True), issue("ABC-22", "do-epic-claude", done=True), issue("ABC-23", "repo:docs")] self.assertEqual(finish.unreviewed(done), ["api", "web"]) self.assertEqual(finish.unreviewed([*done, issue("ABC-30", "repo:api", "do-epic-release-review")]), ["web"]) self.assertEqual(finish.unreviewed([issue("ABC-30", "repo:api", "do-epic-release-review", done=True)]), [], "a review alone changes no repo") class TheFinishingChunksTask(DoEpicTest): def test_first_asks_for_one_review_issue_per_repo_that_lacks_one(self) -> None: task = finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "repo:web", done=True)], LAUNCHER, "Swedish") self.assertIn("Finish the epic ABC-12", task) self.assertIn("first, and api and web have none. ", task) self.assertIn("first, and api has none. ", finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True)], LAUNCHER, "Swedish")) self.assertIn('`/b/do-epic ABC-12 --file "" --label repo: --label do-epic-release-review`', task) self.assertIn("`Release review of ABC-12`", task) self.assertIn("in Swedish", task) self.assertNotIn("--close-epic", task) def test_then_has_the_human_confirm_each_goal_before_the_summary_and_the_closing(self) -> None: task = finish.task("ABC-12", REVIEWED, LAUNCHER, "Swedish") self.assertIn("Finish the epic ABC-12", task) self.assertIn("A goal is met only where the human confirms it", task) self.assertIn("ask the human to approve the set", task) self.assertIn("`/b/do-epic ABC-12 --close-epic`", task) self.assertIn("in Swedish", task) self.assertIn(findings.instructions("ABC-12", LAUNCHER, "Swedish"), task) self.assertIn("- ABC-20 (api): Do ABC-20\n- ABC-21: Do ABC-21\n- ABC-30 (api): Do ABC-30", task) self.assertNotIn("do-epic-release-review`", task) class ClosingTheEpic(DoEpicTest): def setUp(self) -> None: super().setUp() self.issues = list(REVIEWED) self.store = MemoryEpic("ABC-12", self.issues) def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]: self.assertIsInstance(config, DoEpicConfig) self.store.issues = list(self.issues) return self.store, EpicRecord(Description(self.description)) # type: ignore[arg-type] def close(self, summary: str = "## Shipped\n\napi: the import.\n") -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(["ABC-12", "--close-epic"], {}, paths_from(self.home), LAUNCHER, FakeEffects().effects(), self.backend, io.StringIO(summary)) return code, out.getvalue(), err.getvalue() def test_posts_the_summary_on_the_epic_and_closes_it(self) -> None: code, out, err = self.close() self.assertEqual(code, 0, err) self.assertIn("Posted the summary on the epic ABC-12 and closed it.\n", out) self.assertEqual(self.store.comments, {"ABC-12": ["## Shipped\n\napi: the import."]}) self.assertIs(self.store.done, True) def test_refuses_an_epic_that_is_closed_already(self) -> None: self.store.done = True code, _, err = self.close() self.assertEqual(code, 1) self.assertIn("cannot close the epic ABC-12: it is closed already\n", err) self.assertEqual(self.store.comments, {}) def test_says_why_it_cannot_tell_whether_the_epic_is_closed(self) -> None: class Unreadable(MemoryEpic): def closed(self) -> Failure: return Failure("Jira answered 503") self.assertEqual(finish.closed("ABC-12", Unreadable("ABC-12", list(REVIEWED)), io.StringIO("Shipped.")), Failure("cannot close the epic ABC-12: Jira answered 503")) def test_the_jira_backend_closes_an_epic_by_the_transition_the_settings_name(self) -> None: with open(self.home / ".claude-projects/do-epic/config.toml", "a", encoding="utf-8") as settings: settings.write('jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') config = load(self.home) assert isinstance(config, DoEpicConfig), config store, _ = main.jira_backend(config, "ABC-12") self.assertEqual(store.finish, Finish("Mark as done", "Done")) # type: ignore[attr-defined] def test_refuses_while_an_issue_is_open(self) -> None: self.issues.append(issue("ABC-31", "repo:api")) code, _, err = self.close() self.assertEqual(code, 1) self.assertIn("cannot close the epic ABC-12: ABC-31 is open\n", err) self.assertEqual((self.store.comments, self.store.done), ({}, False)) self.issues.append(issue("ABC-32", "repo:api")) self.assertIn("cannot close the epic ABC-12: ABC-31 and ABC-32 are open\n", self.close()[2]) def test_refuses_while_a_repo_the_epic_changed_lacks_its_release_review(self) -> None: self.issues.append(issue("ABC-31", "repo:web", done=True)) code, _, err = self.close() self.assertEqual(code, 1) self.assertIn("cannot close the epic ABC-12: no issue labelled do-epic-release-review reviews web\n", err) self.assertEqual((self.store.comments, self.store.done), ({}, False)) self.issues.append(issue("ABC-32", "repo:docs", done=True)) self.assertIn("reviews docs or web\n", self.close()[2]) def test_refuses_a_blank_summary_and_says_why_the_tracker_refused(self) -> None: code, _, err = self.close(" \n") self.assertEqual(code, 1) self.assertIn("cannot close the epic ABC-12: ", err) self.assertIs(self.store.done, False) self.store.fails = "Jira answered 401" code, _, err = self.close() self.assertEqual(code, 1) self.assertIn("cannot close the epic ABC-12: Jira answered 401\n", err) self.assertEqual((self.store.closed(), self.store.close("Shipped.")), (Failure("Jira answered 401"), Failure("Jira answered 401"))) def test_prints_the_help_for_a_closing_spelt_wrong(self) -> None: for argv in (["ABC-12", "--close-epic", "now"], ["--close-epic", "ABC-12"], ["--close-epic"]): code, out, err = self.run_main(argv, FakeEffects()) self.assertEqual((code, out), (1, ""), argv) self.assertIn("usage: do-epic [--status]\n", err) self.assertIn("do-epic --close-epic <<'EOF' summary EOF", err) class TheFinishingChunk(DoEpicTest): def setUp(self) -> None: super().setUp() self.store = MemoryEpic("ABC-12", []) def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]: self.store.issues = list(self.issues) return self.store, EpicRecord(Description(self.description)) # type: ignore[arg-type] def started(self, fake: FakeEffects) -> list[str]: """The name of each window do-epic started.""" return [args[args.index("-n") + 1] for args in fake.tmux_calls if args[0] in ("new-session", "new-window")] def test_starts_in_a_window_named_for_the_epic_once_no_issue_is_open(self) -> None: self.issues = [issue("ABC-20", "do-epic-claude", done=True)] fake = FakeEffects(on_terminal=False) code, out, err = self.run_main(["ABC-12"], fake) self.assertEqual(code, 0, err) self.assertIn("started ABC-12 in the tmux session epic-ABC-12\n", out) self.assertEqual(self.started(fake), ["ABC-12"]) self.assertIn(["/b/do-epic", "--chunk", "ABC-12", "ABC-12"], [args[-4:] for args in fake.tmux_calls]) def test_doesnt_start_while_an_issue_is_open_or_in_an_epic_without_issues(self) -> None: for issues in ([issue("ABC-20", "do-epic-claude", done=True), issue("ABC-21")], []): self.issues = issues fake = FakeEffects(on_terminal=False) code, out, _ = self.run_main(["ABC-12"], fake) self.assertEqual((code, self.started(fake)), (0, [])) self.assertIn("started no chunk\n", out) def test_doesnt_start_in_an_epic_that_is_closed(self) -> None: self.issues = [issue("ABC-20", "do-epic-claude", done=True)] self.store.done = True fake = FakeEffects(on_terminal=False) code, out, _ = self.run_main(["ABC-12"], fake) self.assertEqual((code, self.started(fake)), (0, [])) self.assertIn("started no chunk\n", out) self.assertIn("the epic ABC-12 is closed\n", out) def test_its_worker_is_handed_the_finishing_task_and_runs_until_the_judge_rules_it_finished(self) -> None: self.issues = list(REVIEWED) worker = Worker(paths_from(self.home).claude_code_transcripts.parent) fake = FakeEffects(streams=[worker], claude=[judged("finished")], git=UNREAD, windows="ABC-12\t0\t@9\n") code, out, err = self.run_main(["--chunk", "ABC-12", "ABC-12"], fake, MODELS) self.assertEqual(code, 0, err) self.assertIn("the chunk finished; started no other\n", out) streamed = " ".join([what for seam, what in fake.calls if seam == "stream_claude"][0]) self.assertIn("Finish the epic ABC-12", streamed) self.assertIn("`/b/do-epic ABC-12 --close-epic`", streamed) self.assertIn("From the epic ABC-12's description:\n## Goals\nShip the import.", streamed) self.assertIn("write a summary in English, the epic's language", streamed) self.assertTrue((self.home / ".local/state/do-epic/ABC-12").is_dir()) def test_a_worker_that_resumes_is_told_the_task_as_the_epic_now_stands(self) -> None: self.issues = list(REVIEWED) transcripts = paths_from(self.home).claude_code_transcripts worker = Worker(transcripts.parent) session = session_named("A ABC-12 do-epic ABC-12", transcripts) (transcripts / "-fake").mkdir(parents=True) (transcripts / "-fake" / f"{session.id}.jsonl").write_text("{}\n", encoding="utf-8") fake = FakeEffects(streams=[worker], claude=[judged("finished")], git=UNREAD, windows="ABC-12\t0\t@9\n") code, _, err = self.run_main(["--chunk", "ABC-12", "ABC-12"], fake, MODELS) self.assertEqual(code, 0, err) args = [what for seam, what in fake.calls if seam == "stream_claude"][0] self.assertIn("--resume", args) self.assertIn("so it may have changed since you began. It is now:\n\nFinish the epic ABC-12", " ".join(args)) self.assertIn("`/b/do-epic ABC-12 --close-epic`", " ".join(args)) def test_stops_where_the_epics_issues_cannot_be_read_or_its_lock_cannot_be_taken(self) -> None: self.issues = [issue("ABC-20", "do-epic-claude", done=True)] (self.home / ".local/state/do-epic/ABC-12" / scheduler.LOCK).mkdir(parents=True) code, _, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False)) self.assertEqual(code, 1) self.assertIn("cannot lock ", err) self.store.fails = "Jira answered 503" code, _, err = self.run_main(["--chunk", "ABC-12", "ABC-12"], FakeEffects(windows="ABC-12\t0\t@9\n"), MODELS) self.assertEqual(code, 1) self.assertIn("Jira answered 503\n", err) def test_ends_before_a_cycle_where_the_epic_holds_an_open_issue_again_and_starts_its_chunk(self) -> None: self.issues = [*REVIEWED, issue("ABC-31", "do-epic-claude")] self.description = DESCRIPTION.replace("chunks:** 2", "chunks:** 1") fake = FakeEffects(windows="ABC-12\t0\t@9\n") code, out, err = self.run_main(["--chunk", "ABC-12", "ABC-12"], fake, MODELS) self.assertEqual(code, 0, err) self.assertIn("the epic ABC-12 holds an open issue again, so its finishing chunk ends until none is open\n", out) self.assertIn("the chunk finished; started ABC-31\n", out) self.assertEqual([seam for seam, _ in fake.calls if seam == "stream_claude"], [])