import json import pathlib import subprocess import sys import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.repo_pick import CLAUDE_LABEL, ClaudeWork, HUMAN_LABEL, HumanTask, label_of, PICK_SCHEMA, picked, recorded, Repo, REPO_PREFIX, Unclear from do_epic.backend.protocol import EpicIssue from failure import Failure from claude_code.reply import Limited from do_epic.backend.fake import MemoryEpic from model_routing.ladder import Rung RULE = "A label equal to a repo's name names that repo. Cleaning up docs has no repo." RUNG = Rung("claude-sonnet-5-5", "medium") class Claude: """Stands in for claude: answers each call with stdout, and keeps the calls' arguments and prompts.""" def __init__(self, stdout: str, returncode: int = 0) -> None: self.stdout, self.returncode, self.calls = stdout, returncode, [] def __call__(self, args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[str]: self.calls.append((args, cwd, prompt)) return subprocess.CompletedProcess(args, self.returncode, self.stdout, "") def says(output: object) -> Claude: return Claude(json.dumps({"type": "result", "structured_output": output})) class RepoPick(unittest.TestCase): def setUp(self) -> None: self.store = MemoryEpic("ABC-12") self.key = self.store.file("ABC-12", "Count the runs.", "Why it counts.", ("api",)) assert isinstance(self.key, str) def issue(self): # type: ignore[no-untyped-def] read = self.store.read() assert isinstance(read, list) return read[0] def pick(self, claude: Claude): # type: ignore[no-untyped-def] return picked(self.store, self.issue(), RULE, RUNG, claude, "/rules") def test_records_the_claude_pick_as_a_label_on_the_issue(self) -> None: self.assertEqual(self.pick(says({"pick": "repo", "repo": "payments-api"})), Repo("payments-api")) self.assertEqual(self.issue().labels, ("api", "repo:payments-api")) def test_asks_claude_for_a_json_reply_on_the_given_rung_and_without_tools(self) -> None: claude = says({"pick": "claude"}) self.pick(claude) args, cwd, _ = claude.calls[0] self.assertEqual(cwd, "/rules") self.assertEqual(args[:9], ["-p", "--json-schema", json.dumps(PICK_SCHEMA), "--model", "claude-sonnet-5-5", "--effort", "medium", "--tools", ""]) def test_puts_the_rule_and_the_item_in_the_prompt(self) -> None: claude = says({"pick": "claude"}) self.pick(claude) prompt = claude.calls[0][2] self.assertIn(RULE, prompt) self.assertIn(f"## Item {self.key}: Count the runs.\n\nLabels: api\n\nWhy it counts.", prompt) def test_tells_claude_all_of_an_items_labels(self) -> None: self.store.add_label(self.key, "web") claude = says({"pick": "claude"}) self.pick(claude) self.assertIn("Labels: api, web\n", claude.calls[0][2]) def test_tells_claude_an_item_has_no_labels_and_no_description(self) -> None: store = MemoryEpic("ABC-12") store.file("ABC-12", "Clean up the docs.", "", ()) claude = says({"pick": "claude"}) picked(store, store.read()[0], RULE, RUNG, claude, "/rules") # type: ignore[index] self.assertIn("Labels: none\n\n(no description)\n", claude.calls[0][2]) def test_records_a_pick_without_a_repo_as_claudes_work_or_a_human_task(self) -> None: for output, pick, label in (({"pick": "claude"}, ClaudeWork(), CLAUDE_LABEL), ({"pick": "human"}, HumanTask(), HUMAN_LABEL)): with self.subTest(label=label): store = MemoryEpic("ABC-12") key = store.file("ABC-12", "Clean up the docs.", "", ()) issue = store.read()[0] # type: ignore[index] self.assertEqual(picked(store, issue, RULE, RUNG, says(output), "/rules"), pick) self.assertEqual(store.read()[0].labels, (label,)) # type: ignore[index] self.assertEqual(recorded(store.read()[0]), pick) # type: ignore[index] def test_reads_a_recorded_pick_back_without_asking_claude(self) -> None: self.store.add_label(self.key, "repo:log") claude = says({"pick": "claude"}) self.assertEqual(self.pick(claude), Repo("log")) self.assertEqual(claude.calls, []) def test_two_recorded_picks_fail_and_name_both(self) -> None: self.store.add_label(self.key, "repo:log") self.store.add_label(self.key, HUMAN_LABEL) claude = says({"pick": "claude"}) self.assertEqual(self.pick(claude), Failure(f"{self.key} is labelled with 2 picks: do-epic-human, repo:log; remove all but the right one")) self.assertEqual(claude.calls, []) def test_an_unclear_pick_returns_the_question_and_records_nothing_until_the_human_answers(self) -> None: self.assertEqual(self.pick(says({"pick": "unclear", "question": " Is this the api or the worker? "})), Unclear("Is this the api or the worker?")) self.assertEqual(self.issue().labels, ("api",)) def test_a_reply_that_is_no_pick_fails_and_records_nothing(self) -> None: for output in (None, "repo", {"pick": "repo"}, {"pick": "repo", "repo": "two words"}, {"pick": "unclear"}, {"pick": "unclear", "question": " "}, {"pick": "elsewhere"}): with self.subTest(output=output): self.assertIsInstance(self.pick(says(output)), Failure) self.assertEqual(self.issue().labels, ("api",)) def test_a_repo_name_that_could_leave_its_folder_or_name_a_host_is_no_pick(self) -> None: for name in ("../../.ssh", "a/b", ".hidden", "-flag", "https://host/x.git", "host:repo"): with self.subTest(name=name): self.assertIsInstance(self.pick(says({"pick": "repo", "repo": name})), Failure) self.assertIsNone(recorded(EpicIssue(self.key, "s", "", (REPO_PREFIX + name,), None, "To Do", False, "ABC-12"))) def test_a_reply_that_is_no_pick_says_what_it_got_in_its_first_200_characters(self) -> None: output = {"pick": "repo", "repo": "two words" * 40} self.assertEqual(self.pick(says(output)), Failure("the repo pick answered " + json.dumps(output)[:200] + '; expected pick "repo" with a repo name of letters, digits, dots, hyphens and underscores, "claude", "human", or "unclear" with a question')) def test_a_failed_run_comes_back_as_it_is(self) -> None: self.assertEqual(self.pick(Claude("", 1)), Failure("the repo pick exited 1")) def test_a_usage_limit_comes_back_as_it_is(self) -> None: limit = json.dumps({"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"}) self.assertIsInstance(self.pick(Claude(limit)), Limited) def test_a_label_the_tracker_refuses_comes_back_as_it_is(self) -> None: issue = self.issue() self.store.fails = "Jira answered 503" self.assertEqual(picked(self.store, issue, RULE, RUNG, says({"pick": "claude"}), "/rules"), Failure("Jira answered 503")) def test_the_label_of_a_pick_reads_back_as_that_pick(self) -> None: for pick in (Repo("payments-api"), ClaudeWork(), HumanTask()): with self.subTest(pick=pick): self.assertEqual(recorded(EpicIssue(self.key, "s", "", (label_of(pick),), None, "To Do", False, "ABC-12")), pick) def test_a_label_with_the_prefix_alone_is_no_pick(self) -> None: self.store.add_label(self.key, "repo:") self.assertIsNone(recorded(self.issue())) if __name__ == "__main__": unittest.main()