Files
claude-config/bin/do_epic/test_ranking.py
T
Lilleman c5b5ec78ef
CI / tests (pull_request) Has been cancelled
Test the names of three items that block each other in a loop
2026-11-20 17:04:43 +01:00

292 lines
18 KiB
Python

import dataclasses
import decimal
import itertools
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic.ranking import chain, EpicItem, goals_named, rank_moves, ranked, RepoRanking, reranked
from failure import Failure
from plan.todo_table import Item, parse_moves
from do_epic.backend.fake import MemoryEpic
EPIC_GOALS = "1. **Achieve:** Ship invoices.\n2. **Achieve:** Cut support mail.\n3. **Maintain:** Leak no customer data.\n"
VOIDED = RepoRanking("## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** Fast builds.\n", "", "", decimal.Decimal("7.0"))
HEALTHY = RepoRanking("## Goals\n\n1. **Achieve:** Fast builds.\n2. **Maintain:** Stay on the LTS.\n", "", "", decimal.Decimal("7.0"))
# A scoring run of a repo whose overall mean is {overall}.
SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n"
# What the epic's two achieve goals weigh together before they are scaled to sum to 1, the second 0.97 of the first.
TOTAL = 1 + 0.97
def item(id_: int, moves: str, repo: str | None = "billing-api", exempt: str = "", blocked_by: tuple[int, ...] = ()) -> EpicItem:
parsed = parse_moves(f"item {id_}", moves)
assert not isinstance(parsed, Failure), parsed
return EpicItem(Item(id_, (0, 0, 0), exempt, f"**Item {id_}.**", {"L": 1, "E": 1, "I": 1, "S": 1}, parsed, blocked_by), repo, f"item {id_}") # type: ignore[arg-type]
def order(items: list[EpicItem], repos: dict[str, RepoRanking], formula: str = "V") -> list[int] | Failure:
found = ranked(items, formula, EPIC_GOALS, repos)
return found if isinstance(found, Failure) else [scored.id for scored, _ in found]
class MovesSpellingTest(unittest.TestCase):
def test_a_moves_cell_names_an_epics_goal_and_a_repos_goal_by_their_scope(self) -> None:
self.assertEqual(parse_moves("item 1", "epic 1.1 by 8, code health by 5, repo 2 by 4"), (("epic 1.1", 8), ("code health", 5), ("repo 2", 4)))
def test_a_moves_cell_refuses_an_epic_goal_beside_its_own_sub_goal(self) -> None:
self.assertIsInstance(parse_moves("item 1", "epic 1 by 8, epic 1.1 by 5"), Failure)
self.assertEqual(parse_moves("item 1", "epic 1 by 8, repo 1.1 by 5"), (("epic 1", 8), ("repo 1.1", 5)))
class ChainTest(unittest.TestCase):
def test_the_chain_is_the_epics_goals_then_code_health_then_the_repos_goals(self) -> None:
self.assertEqual(chain(EPIC_GOALS, "web", HEALTHY), [("epic 1", "Achieve"), ("epic 2", "Achieve"), ("epic 3", "Maintain"), ("code health", "Achieve"), ("repo 1", "Achieve"), ("repo 2", "Maintain")])
def test_a_repo_that_voids_code_health_leaves_it_out_of_its_chain(self) -> None:
self.assertEqual(chain(EPIC_GOALS, "billing-api", VOIDED), [("epic 1", "Achieve"), ("epic 2", "Achieve"), ("epic 3", "Maintain"), ("repo 1", "Achieve")])
def test_an_item_without_a_repo_weighs_only_the_epics_goals(self) -> None:
self.assertEqual(chain(EPIC_GOALS, None, None), [("epic 1", "Achieve"), ("epic 2", "Achieve"), ("epic 3", "Maintain")])
def test_an_epic_without_a_numbered_goal_fails(self) -> None:
self.assertEqual(chain("Ship it.\n", None, None), Failure("the epic's ## Goals has no numbered goal"))
class GoalsNamedTest(unittest.TestCase):
EPIC = "1. **Maintain:** Break no import.\n2. **Achieve:** Ship the import.\n"
def test_names_only_the_epics_achieve_goals_for_an_item_without_a_repo(self) -> None:
self.assertEqual(goals_named(self.EPIC, None, None), "The epic's goals, each named `epic <its number>`:\n\n1. **Maintain:** Break no import.\n2. **Achieve:** Ship the import.\n\nAn item moves only these: `epic 2`.")
self.assertTrue(str(goals_named("1. **Maintain:** Break no import.\n", None, None)).endswith("An item moves only these: none, so leave the moves empty."))
def test_names_code_health_and_the_repos_goals_for_an_item_in_a_repo(self) -> None:
own = RepoRanking("## Goals\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n", "", "", decimal.Decimal(7))
found = goals_named(self.EPIC, "api", own)
assert isinstance(found, str), found
self.assertIn("\n\n`code health` is the goal that the code of api stays easy to read, change safely and debug.\n\nThe goals of the repo api, each named `repo <its number>`:\n\n1. **Achieve:** Serve the API.\n\nAn item moves only these: `epic 2`, `code health`, `repo 1`.", found)
def test_fails_on_goals_that_cannot_be_read(self) -> None:
self.assertIsInstance(goals_named(self.EPIC, "api", RepoRanking("No goals here.\n", "", "", decimal.Decimal(7))), Failure)
class RankedTest(unittest.TestCase):
def test_each_goal_weighs_0_97_of_the_one_above_it_in_the_chain(self) -> None:
found = ranked([item(1, "repo 1 by 10"), item(2, "epic 2 by 10"), item(3, "epic 1 by 10")], "V", EPIC_GOALS, {"billing-api": VOIDED})
assert not isinstance(found, Failure), found
self.assertEqual([scored.id for scored, _ in found], [3, 2, 1])
for (_, value), expected in zip(found, (10 / TOTAL, 9.7 / TOTAL, 10 * 0.97**2 / TOTAL)):
self.assertAlmostEqual(value, expected)
def test_where_the_epic_and_a_repo_disagree_the_epic_wins(self) -> None:
self.assertEqual(order([item(1, "repo 1 by 5"), item(2, "epic 2 by 5")], {"billing-api": VOIDED}), [2, 1])
def test_items_of_two_repos_rank_in_one_order_each_by_its_own_repos_chain(self) -> None:
repos = {"billing-api": VOIDED, "web": HEALTHY}
self.assertEqual(order([item(1, "repo 1 by 5"), item(2, "repo 1 by 6", repo="web"), item(3, "epic 1 by 9", repo="web")], repos, "V * 0 + S + I"), [1, 2, 3])
self.assertEqual(order([item(1, "repo 1 by 5"), item(2, "repo 2 by 9", repo="web")], repos), [2, 1])
def test_an_item_without_a_repo_scores_by_the_epics_goals_alone(self) -> None:
found = ranked([item(1, "epic 1 by 10", repo=None)], "V", EPIC_GOALS, {})
assert not isinstance(found, Failure), found
self.assertAlmostEqual(found[0][1], 10 / TOTAL)
def test_an_item_without_a_repo_may_not_name_a_repos_goal_or_code_health(self) -> None:
self.assertEqual(order([item(4, "repo 1 by 5", repo=None)], {}), Failure("item 4 names repo 1, but isn't worked in a repo; name only the epic's goals, as in `epic 1 by 5`"))
self.assertEqual(order([item(4, "code health by 5", repo=None)], {}), Failure("item 4 names code health, but isn't worked in a repo; name only the epic's goals, as in `epic 1 by 5`"))
self.assertEqual(order([item(4, "2 by 5", repo=None)], {}), Failure("item 4 names 2, but isn't worked in a repo; write `epic 2` for the epic's goal"))
def test_a_goal_without_its_scope_is_refused(self) -> None:
self.assertEqual(order([item(4, "1 by 5")], {"billing-api": VOIDED}), Failure("item 4 names goal 1 without saying whose it is; write `epic 1` for the epic's goal or `repo 1` for its repo's"))
def test_an_epics_goal_outweighs_a_repos_goal_across_repos_with_chains_of_different_lengths(self) -> None:
long = RepoRanking("## Goals\n\n" + "".join(f"{place}. **Achieve:** Goal {place}.\n" for place in range(1, 10)), "", "", decimal.Decimal("7.0"))
found = ranked([item(1, "repo 1 by 10"), item(2, "epic 2 by 10", repo="web"), item(3, "epic 2 by 10", repo=None)], "V", EPIC_GOALS, {"billing-api": VOIDED, "web": long})
assert not isinstance(found, Failure), found
self.assertEqual([scored.id for scored, _ in found], [2, 3, 1])
for (_, value), expected in zip(found, (9.7 / TOTAL, 9.7 / TOTAL, 10 * 0.97**2 / TOTAL)):
self.assertAlmostEqual(value, expected)
def test_an_epic_without_an_achieve_goal_weighs_each_repos_first_achieve_goal_1(self) -> None:
two = dataclasses.replace(VOIDED, goals_text=VOIDED.goals_text + "2. **Achieve:** Small images.\n")
found = ranked([item(1, "repo 1 by 10"), item(2, "repo 1 by 10", repo="web"), item(3, "repo 2 by 10", repo="web")], "V", "1. **Maintain:** Leak no customer data.\n", {"billing-api": VOIDED, "web": two})
assert not isinstance(found, Failure), found
for (_, value), expected in zip(found, (10, 10, 9.7)):
self.assertAlmostEqual(value, expected)
def test_an_item_without_a_score_fails_naming_it(self) -> None:
unscored = EpicItem(dataclasses.replace(item(4, "").item, scores={}), None, "item 4")
self.assertEqual(ranked([unscored], "V", EPIC_GOALS, {}), Failure("item 4 has no L: score it on L, E, I and S before it is ranked"))
def test_an_epic_that_numbers_a_goal_twice_fails(self) -> None:
self.assertEqual(chain("1. **Achieve:** A.\n1. **Achieve:** B.\n", None, None), Failure("the epic's ## Goals numbers 1, 1; number each goal by its position"))
def test_a_goal_the_chain_does_not_hold_is_refused(self) -> None:
self.assertEqual(order([item(4, "epic 9 by 5")], {"billing-api": VOIDED}), Failure("item 4 names epic 9, which the epic's ## Goals does not number"))
self.assertEqual(order([item(4, "repo 9 by 5")], {"billing-api": VOIDED}), Failure("item 4 names repo 9, which the ## Goals of billing-api's goals file does not number"))
self.assertEqual(order([item(4, "code health by 5")], {"billing-api": VOIDED}), Failure("item 4 names code health, which billing-api's goals file voids"))
def test_an_item_in_a_repo_without_premises_fails(self) -> None:
self.assertEqual(order([item(4, "epic 1 by 5", repo="ghost")], {}), Failure("item 4 is in the repo ghost, whose goals were not read"))
def test_a_goal_marked_neither_way_fails_naming_whose_it_is(self) -> None:
unmarked = RepoRanking("## Goals\n\n1. Fast builds.\n", "", "", decimal.Decimal("7.0"))
self.assertEqual(order([item(4, "epic 1 by 5")], {"billing-api": unmarked}), Failure("billing-api's goal 1 is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so the epic's items can be scored"))
found = ranked([item(4, "epic 1 by 5", repo=None)], "V", "1. Ship invoices.\n", {})
self.assertEqual(found, Failure("the epic's goal 1 is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so the epic's items can be scored"))
def test_a_repos_goals_file_that_cannot_be_read_fails_naming_the_repo(self) -> None:
self.assertEqual(order([item(4, "epic 1 by 5")], {"billing-api": RepoRanking("# Billing\n", "", "", decimal.Decimal("7.0"))}), Failure("billing-api: the goals file has no ## Goals heading"))
def test_code_health_weighs_four_times_its_place_while_the_repo_is_unmeasured_or_under_its_floor(self) -> None:
for history, times in (("", 4), (SCORED.format(overall="6.9"), 4), (SCORED.format(overall="7.0"), 1)):
with self.subTest(history=history):
found = ranked([item(1, "code health by 10", repo="web"), item(2, "repo 1 by 10", repo="web")], "V", EPIC_GOALS, {"web": dataclasses.replace(HEALTHY, history=history)})
assert not isinstance(found, Failure), found
self.assertAlmostEqual(found[0][1], times * 10 * 0.97**2 / TOTAL)
self.assertAlmostEqual(found[1][1], 10 * 0.97**3 / TOTAL)
def test_code_health_weighs_four_times_its_place_under_a_floor_the_repo_sets_higher(self) -> None:
found = ranked([item(1, "code health by 10", repo="web")], "V", EPIC_GOALS, {"web": dataclasses.replace(HEALTHY, history=SCORED.format(overall="7.5"), floor=decimal.Decimal("8.0"))})
assert not isinstance(found, Failure), found
self.assertAlmostEqual(found[0][1], 4 * 10 * 0.97**2 / TOTAL)
def test_a_history_that_cannot_be_read_fails_naming_the_repo(self) -> None:
found = order([item(1, "code health by 10", repo="web")], {"web": dataclasses.replace(HEALTHY, history=SCORED.format(overall="high"))})
assert isinstance(found, Failure), found
self.assertTrue(found.reason.startswith("web: ") and len(found.reason) > len("web: None"), found.reason)
def test_a_formula_that_gives_an_item_no_finite_score_fails_naming_the_item(self) -> None:
self.assertEqual(order([item(4, "epic 1 by 5")], {"billing-api": VOIDED}, "10 ** 400 * V * 10 ** 400"), Failure("the formula gives item 4 no finite score"))
def test_each_goal_an_item_names_is_checked(self) -> None:
self.assertEqual(order([item(4, "epic 1 by 5, repo 9 by 5")], {"billing-api": VOIDED}), Failure("item 4 names repo 9, which the ## Goals of billing-api's goals file does not number"))
def test_a_question_then_a_security_finding_rank_before_any_score(self) -> None:
self.assertEqual(order([item(1, "epic 1 by 10"), item(2, "epic 2 by 1", exempt="security"), item(3, "", exempt="question")], {"billing-api": VOIDED}), [3, 2, 1])
def test_a_blocker_ranks_above_the_item_it_blocks_and_a_tie_goes_to_the_older_item(self) -> None:
self.assertEqual(order([item(1, "epic 1 by 9", blocked_by=(3,)), item(2, "epic 1 by 2"), item(3, "epic 1 by 1"), item(5, "epic 1 by 2")], {"billing-api": VOIDED}), [3, 1, 2, 5])
def test_names_by_their_names_the_items_that_block_each_other_in_a_loop(self) -> None:
looped = [dataclasses.replace(item(1, "epic 1 by 9", blocked_by=(2,)), name="ABC-1"), dataclasses.replace(item(2, "epic 1 by 2", blocked_by=(1,)), name="XYZ-1"), item(3, "epic 1 by 1")]
self.assertEqual(ranked(looped, "V", EPIC_GOALS, {"billing-api": VOIDED}), Failure("ABC-1 and XYZ-1 block each other in a loop; drop one of the blockers"))
three = [item(1, "epic 1 by 9", blocked_by=(3,)), item(2, "epic 1 by 2", blocked_by=(1,)), item(3, "epic 1 by 1", blocked_by=(2,))]
self.assertEqual(ranked(three, "V", EPIC_GOALS, {"billing-api": VOIDED}), Failure("item 1, item 2 and item 3 block each other in a loop; drop one of the blockers"))
def test_a_formula_that_cannot_be_read_fails(self) -> None:
self.assertIsInstance(order([item(1, "epic 1 by 9")], {"billing-api": VOIDED}, "V +"), Failure)
class Recording(MemoryEpic):
"""A MemoryEpic that keeps each rank asked of it, and refuses every rank of the issue named in refused."""
refused: str | None = None
asked: list[tuple[str, str]]
def rank(self, key: str, before: str) -> None | Failure:
self.asked.append((key, before))
return Failure("Jira answered 403") if key == self.refused else super().rank(key, before)
def epic(*people: int, issues: int = 4) -> Recording:
"""An epic whose child issues are ABC-100 onwards. The loop filed each of them, except those whose positions, counted from 0, are in people."""
store = Recording("ABC-12")
store.asked = []
for position in range(issues):
store.file("ABC-12", f"Item {position}.", "", ())
if position in people:
store.change(f"ABC-{100 + position}", by_loop=False)
return store
def keys(store: MemoryEpic) -> list[str]:
read = store.read()
assert isinstance(read, list), read
return [issue.key for issue in read]
class RerankedTest(unittest.TestCase):
def test_the_loops_issues_take_their_slots_in_the_order_given_and_a_persons_keep_theirs(self) -> None:
store = epic(1)
self.assertEqual(reranked(store, ["ABC-103", "ABC-100", "ABC-102"]), None)
self.assertEqual(keys(store), ["ABC-103", "ABC-101", "ABC-100", "ABC-102"])
def test_the_last_slot_takes_its_issue_where_a_persons_issue_comes_before_it(self) -> None:
store = epic(0, issues=3)
self.assertEqual(reranked(store, ["ABC-102", "ABC-101"]), None)
self.assertEqual(keys(store), ["ABC-100", "ABC-102", "ABC-101"])
def test_an_order_the_backlog_already_reads_in_ranks_nothing(self) -> None:
store = epic(1)
self.assertEqual(reranked(store, ["ABC-100", "ABC-102", "ABC-103"]), None)
self.assertEqual(store.asked, [])
def test_ranks_only_the_issues_out_of_place(self) -> None:
store = epic(issues=5)
self.assertEqual(reranked(store, ["ABC-100", "ABC-102", "ABC-101", "ABC-103", "ABC-104"]), None)
self.assertEqual(store.asked, [("ABC-101", "ABC-103")])
def test_an_issue_the_order_doesnt_name_keeps_its_slot(self) -> None:
store = epic()
store.change("ABC-101", status="Done", done=True)
self.assertEqual(reranked(store, ["ABC-103", "ABC-102", "ABC-100"]), None)
self.assertEqual(keys(store), ["ABC-103", "ABC-101", "ABC-102", "ABC-100"])
def test_sub_tasks_hold_no_slot_and_follow_their_parent(self) -> None:
store = epic(issues=2)
task = store.file("ABC-100", "A task.", "", ())
self.assertEqual(reranked(store, ["ABC-101", "ABC-100"]), None)
self.assertEqual(keys(store), ["ABC-101", "ABC-100", task])
def test_refuses_an_order_naming_a_persons_issue_a_sub_task_an_issue_outside_the_epic_or_one_twice(self) -> None:
store = epic(1)
task = store.file("ABC-100", "A task.", "", ())
for order, reason in (
(["ABC-101", "ABC-100"], "ABC-101 is not one of the child issues of the epic ABC-12 that the loop filed, so the backlog was not re-ranked"),
([task, "ABC-100"], f"{task} is not one of the child issues of the epic ABC-12 that the loop filed, so the backlog was not re-ranked"),
(["ZZZ-1"], "ZZZ-1 is not one of the child issues of the epic ABC-12 that the loop filed, so the backlog was not re-ranked"),
(["ABC-100", "ABC-102", "ABC-100"], "the order names ABC-100 twice, so the backlog was not re-ranked"),
):
with self.subTest(order=order):
self.assertEqual(reranked(store, order), Failure(reason))
self.assertEqual(store.asked, [])
def test_a_rank_the_tracker_refuses_stops_the_walk_and_names_the_order_to_finish_by_hand(self) -> None:
store = epic()
store.refused = "ABC-101"
self.assertEqual(reranked(store, ["ABC-103", "ABC-102", "ABC-101", "ABC-100"]), Failure("cannot rank ABC-101 just before ABC-100: Jira answered 403; the re-rank stopped there, so rank the loop's issues in ABC-12's backlog by hand to come in this sequence: ABC-103, ABC-102, ABC-101, ABC-100"))
self.assertEqual(store.asked, [("ABC-100", "ABC-103"), ("ABC-101", "ABC-100")])
def test_a_refused_rank_of_the_issue_due_last_names_it(self) -> None:
store = epic()
store.refused = "ABC-100"
self.assertEqual(reranked(store, ["ABC-103", "ABC-102", "ABC-101", "ABC-100"]), Failure("cannot rank ABC-100 just before ABC-103: Jira answered 403; the re-rank stopped there, so rank the loop's issues in ABC-12's backlog by hand to come in this sequence: ABC-103, ABC-102, ABC-101, ABC-100"))
def test_a_read_that_fails_ranks_nothing(self) -> None:
store = epic()
store.fails = "Jira is down"
self.assertEqual(reranked(store, ["ABC-101"]), Failure("Jira is down"))
self.assertEqual(store.asked, [])
class RankMovesTest(unittest.TestCase):
def test_every_backlog_of_up_to_six_issues_reaches_its_target_moving_only_the_listed_keys(self) -> None:
for size in range(7):
backlog = [f"K-{n}" for n in range(size)]
for listed in itertools.chain.from_iterable(itertools.combinations(backlog, count) for count in range(size + 1)):
for order in itertools.permutations(listed):
sequence = iter(order)
target = [next(sequence) if key in listed else key for key in backlog]
now = list(backlog)
for rank in rank_moves(backlog, list(order)):
self.assertIn(rank.key, listed)
now.remove(rank.key)
now.insert(now.index(rank.before), rank.key)
self.assertEqual(now, target, (backlog, order))
if __name__ == "__main__":
unittest.main()