Merge remote-tracking branch 'origin/main' into item-401
CI / tests (pull_request) Has been cancelled
CI / tests (pull_request) Has been cancelled
# Conflicts: # todo.md
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""The order do-epic works an epic's items in: by score, then each blocker above what it blocks (docs/decisions.md → `do-epic: drives one Jira epic …`).
|
||||
|
||||
An item scores by the epic's formula over one chain of goals: the epic's goals, then code health, then the goals of the item's repo. An item without a repo has only the epic's goals. Each achieve goal weighs 0.97 of the one above it in the chain, and the epic's achieve goals weigh the same in every repo, so an achieve goal of the epic outweighs every achieve goal of a repo, whichever repos the two items are in. chain_scoring says what code health and a maintain goal weigh.
|
||||
|
||||
An item's Moves names a goal by its scope, as plan/todo_table.py's EPIC_GOAL says."""
|
||||
import ast
|
||||
import dataclasses
|
||||
import decimal
|
||||
|
||||
from plan.blockers import blockers_first
|
||||
from plan.todo_table import CODE_HEALTH, EPIC_GOAL, Item, REPO_GOAL, SHAPE
|
||||
from failure import Failure
|
||||
from plan.goals_file import GOAL_STEP, goal_weights, Mark, numbered, ranked_goals
|
||||
from review_rules.comprehension_history import latest_overall
|
||||
from plan.formula import parse_formula
|
||||
from plan import ranking
|
||||
from plan_store.jira_epic import SET_SCORES
|
||||
|
||||
MARK_IT = "is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so the epic's items can be scored"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RepoRanking:
|
||||
"""What a repo's own plan is ranked by: its goals file, its decision log and its comprehension history, each as text, and its readability floor."""
|
||||
goals_text: str
|
||||
decisions: str
|
||||
history: str
|
||||
floor: decimal.Decimal
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class EpicItem:
|
||||
"""One of an epic's open items. An Item names a release and an epic item has none: give every item of one epic the same release, so that no blocker sits in a later release than what it blocks. repo is the name of the repo the item is worked in; None where it has none."""
|
||||
item: Item
|
||||
repo: str | None
|
||||
|
||||
|
||||
def ranked(items: list[EpicItem], formula: str, epic_goals: str, repos: dict[str, RepoRanking]) -> list[tuple[Item, float]] | Failure:
|
||||
"""Each item with its score: a question first, then a security finding, then by score from highest, then by ID, and then each blocker above every item it blocks. formula is the epic's, epic_goals the text under its ## Goals, and repos holds, by name, each repo an item is in. An item without a score fails, so leave out an issue a person filed and nobody scored."""
|
||||
parsed = parse_formula(formula, ranking.variables(SHAPE))
|
||||
if isinstance(parsed, Failure):
|
||||
return parsed
|
||||
scorings: dict[str | None, ranking.Scoring] = {}
|
||||
scored = []
|
||||
for each in items:
|
||||
name = f"item {each.item.id}"
|
||||
if each.repo not in scorings:
|
||||
if each.repo is not None and each.repo not in repos:
|
||||
return Failure(f"{name} is in the repo {each.repo}, whose goals were not read")
|
||||
scoring = chain_scoring(parsed, epic_goals, each.repo, repos[each.repo] if each.repo else None)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
scorings[each.repo] = scoring
|
||||
value = unscored(each.item, name) or misnamed_goal(each, scorings[each.repo], name) or ranking.item_score(each.item, scorings[each.repo], name)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
scored.append((each.item, value))
|
||||
scored.sort(key=lambda pair: (ranking.FIRST.get(pair[0].exempt, len(ranking.FIRST)), -pair[1], pair[0].id))
|
||||
return blockers_first(scored)
|
||||
|
||||
|
||||
def chain_scoring(formula: ast.Expression, epic_goals: str, repo: str | None, own: RepoRanking | None) -> ranking.Scoring | Failure:
|
||||
"""How an item in repo scores: the chain's goals, and what each achieve goal weighs. The bar is 0, since a bar decides what is filed, and the order holds every item that was.
|
||||
|
||||
goal_weights scales a chain's weights to sum to 1. Here they are scaled so that the epic's achieve goals sum to 1 instead, in every chain, or the chain's first achieve goal weighs 1 where the epic has none, which makes the scores of items in different repos comparable.
|
||||
|
||||
Code health and a maintain goal weigh by the rules every project's plan follows, which an epic doesn't change: code health weighs four times its place while its repo is unmeasured or under its readability floor, and plan/ranking.py's weight_of weighs a maintain goal. Either may then outweigh an achieve goal of the epic. "The epic wins" in the decision settles the epic's goals against a repo's, and code health is neither's: it is every project's, and a repo that is hard to read costs each epic item worked in it."""
|
||||
goals = chain(epic_goals, repo, own)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
if unmarked := next((goal for goal, mark in goals if mark is None), None):
|
||||
whose, _, number = unmarked.partition(" ")
|
||||
return Failure(f"{'the epic' if whose == 'epic' else repo}'s goal {number} {MARK_IT}")
|
||||
overall = latest_overall(own.history) if own and CODE_HEALTH in dict(goals) else None
|
||||
if isinstance(overall, Failure):
|
||||
return Failure(f"{repo}: {overall.reason}")
|
||||
# goal_weights fails only on a goal without a mark, and the check above has named that goal as the epic's or the repo's.
|
||||
weights = goal_weights(goals, overall, own.floor if own else decimal.Decimal(0))
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
achieve = [goal for goal, mark in goals if mark == "Achieve"]
|
||||
of_epic = len([goal for goal in achieve if goal.startswith(EPIC_GOAL)])
|
||||
# Under an epic without an achieve goal, the first achieve goal of each chain weighs 1.
|
||||
scale = total(len(achieve)) / (total(of_epic) or 1)
|
||||
return ranking.Scoring(SHAPE, formula, 0, 0, dict(goals), {goal: weight * scale for goal, weight in weights.items()})
|
||||
|
||||
|
||||
def total(goals: int) -> float:
|
||||
"""What this many achieve goals weigh together before goal_weights scales them, the first 1 and each 0.97 of the one above it."""
|
||||
return sum(GOAL_STEP**place for place in range(goals))
|
||||
|
||||
|
||||
def chain(epic_goals: str, repo: str | None, own: RepoRanking | None) -> list[tuple[str, Mark]] | Failure:
|
||||
"""Every goal an item in repo may name, in rank order, each with its mark. The epic's goals come first, as `epic <number>`. For an item with a repo, whose ranking is own, code health follows unless the repo's goals file voids it, then the repo's goals as `repo <number>`."""
|
||||
epic = numbered(epic_goals)
|
||||
if isinstance(epic, Failure):
|
||||
return Failure(epic.reason.replace("the goals file's", "the epic's"))
|
||||
scoped = [(f"{EPIC_GOAL}{number}", mark) for number, mark in epic]
|
||||
if own is None:
|
||||
return scoped
|
||||
goals = ranked_goals(own.goals_text, own.decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return Failure(f"{repo}: {goals.reason}")
|
||||
return [*scoped, *((goal if goal == CODE_HEALTH else f"{REPO_GOAL}{goal}", mark) for goal, mark in goals)]
|
||||
|
||||
|
||||
def unscored(item: Item, name: str) -> Failure | None:
|
||||
"""Why the item cannot be scored, such as an issue a person filed and nobody scored; None where it holds each score."""
|
||||
missing = next((score for score in SET_SCORES if score not in item.scores), None)
|
||||
return Failure(f"{name} has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]} before it is ranked") if missing else None
|
||||
|
||||
|
||||
def misnamed_goal(each: EpicItem, scoring: ranking.Scoring, name: str) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, in the epic's terms; None where its chain holds each."""
|
||||
for goal, _ in each.item.moves:
|
||||
if goal in scoring.goals:
|
||||
continue
|
||||
if goal.startswith(EPIC_GOAL):
|
||||
return Failure(f"{name} names {goal}, which the epic's ## Goals does not number")
|
||||
if each.repo is None:
|
||||
scoped = f"; write `{EPIC_GOAL}{goal}` for the epic's goal" if goal[0].isdigit() else f"; name only the epic's goals, as in `{EPIC_GOAL}1 by 5`"
|
||||
return Failure(f"{name} names {goal}, but isn't worked in a repo{scoped}")
|
||||
if goal == CODE_HEALTH:
|
||||
return Failure(f"{name} names {CODE_HEALTH}, which {each.repo}'s goals file voids")
|
||||
if not goal.startswith(REPO_GOAL):
|
||||
return Failure(f"{name} names goal {goal} without saying whose it is; write `{EPIC_GOAL}{goal}` for the epic's goal or `{REPO_GOAL}{goal}` for its repo's")
|
||||
return Failure(f"{name} names {goal}, which the ## Goals of {each.repo}'s goals file does not number")
|
||||
return None
|
||||
@@ -0,0 +1,159 @@
|
||||
import dataclasses
|
||||
import decimal
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from do_epic.ranking import chain, EpicItem, ranked, RepoRanking
|
||||
from failure import Failure
|
||||
from plan.todo_table import Item, parse_moves
|
||||
|
||||
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) # 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 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)
|
||||
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_a_formula_that_cannot_be_read_fails(self) -> None:
|
||||
self.assertIsInstance(order([item(1, "epic 1 by 9")], {"billing-api": VOIDED}, "V +"), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,7 +14,7 @@ from failure import Failure
|
||||
from project_config.main import located
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from release_plan.next_chunk import NextChunk, NoItem, planned
|
||||
from touch_predictions.prediction import overlaps, predicted, Touches
|
||||
from plan.touches import overlaps, predicted, Touches
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from release_plan.release_standing import project_plan
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from adf_codec import convert
|
||||
from failure import Failure
|
||||
from plan.touches import overlaps, Part, predicted, rendered, together
|
||||
|
||||
DETAIL = """A planning call.
|
||||
|
||||
Touches:
|
||||
|
||||
- `bin/a.py`: `main`, `Plan.branch` (small)
|
||||
- `README.md`: `## Goals, and (more): things`
|
||||
- `bin/run.sh`: lines 10-20
|
||||
- `docs/new.md`
|
||||
|
||||
More prose, with `bin/b.py` named.
|
||||
"""
|
||||
|
||||
needs_docker = unittest.skipIf(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode != 0, "adf_codec runs in a container, which needs a docker daemon")
|
||||
|
||||
|
||||
def text(words: str, code: bool = False) -> dict:
|
||||
return {"type": "text", "text": words, **({"marks": [{"type": "code"}]} if code else {})}
|
||||
|
||||
|
||||
def bullet_of(*spans: dict) -> dict:
|
||||
return {"type": "listItem", "attrs": {"localId": "i"}, "content": [{"type": "paragraph", "attrs": {"localId": "p"}, "content": list(spans)}]}
|
||||
|
||||
|
||||
# A Touches list as someone types it in Jira's editor: a paragraph, then a bulleted list whose paths and names carry the code mark.
|
||||
JIRA_TOUCHES = {"type": "doc", "version": 1, "content": [
|
||||
{"type": "paragraph", "attrs": {"localId": "a"}, "content": [text("A planning call.")]},
|
||||
{"type": "paragraph", "attrs": {"localId": "b"}, "content": [text("Touches:")]},
|
||||
{"type": "bulletList", "attrs": {"localId": "c"}, "content": [
|
||||
bullet_of(text("bin/a.py", True), text(": "), text("main", True), text(", "), text("Plan.branch", True), text(" (small)")),
|
||||
bullet_of(text("a`b.md", True), text(": "), text("## The `foo` tool", True), text(" (small)"), text(", "), text("`x`", True)),
|
||||
bullet_of(text("bin/run.sh", True), text(": lines 10-20")),
|
||||
bullet_of(text("docs/new.md", True)),
|
||||
]},
|
||||
{"type": "paragraph", "attrs": {"localId": "d"}, "content": [text("More prose.")]},
|
||||
]}
|
||||
|
||||
|
||||
class PredictedTest(unittest.TestCase):
|
||||
def test_reads_each_bullet_of_the_touches_list(self) -> None:
|
||||
self.assertEqual(predicted(DETAIL), {
|
||||
"bin/a.py": (Part("main"), Part("Plan.branch", small=True)),
|
||||
"README.md": (Part("## Goals, and (more): things"),),
|
||||
"bin/run.sh": (Part("lines 10-20"),),
|
||||
"docs/new.md": (),
|
||||
})
|
||||
|
||||
def test_a_detail_without_the_list_predicts_nothing(self) -> None:
|
||||
self.assertIsNone(predicted("Only prose, with `bin/a.py` named."))
|
||||
|
||||
def test_a_bullet_it_cannot_read_is_a_failure_that_quotes_it(self) -> None:
|
||||
for bullet in ("- bin/a.py: main", "- `bin/a.py`: main", "- `bin/a.py`: lines 20-10", "- `bin/a.py`: `main` `other`"):
|
||||
with self.subTest(bullet):
|
||||
found = predicted(f"Touches:\n\n{bullet}\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertIn(bullet, found.reason)
|
||||
|
||||
def test_an_empty_list_is_a_failure(self) -> None:
|
||||
self.assertIsInstance(predicted("Touches:\n\nProse.\n"), Failure)
|
||||
found = predicted("Touches:\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, "no bullet follows `Touches:`")
|
||||
|
||||
def test_reads_a_list_right_under_its_label_a_one_line_range_and_a_name_of_any_letters(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.py`: `Xray`, lines 5-5\n"), {"a.py": (Part("Xray"), Part("lines 5-5"))})
|
||||
|
||||
def test_rendered_reads_back(self) -> None:
|
||||
touches = predicted(DETAIL)
|
||||
assert isinstance(touches, dict)
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_name_that_holds_backticks_takes_a_longer_run_with_a_space_inside_each_end(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```, `` `x` ``\n"), {"a.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
|
||||
self.assertEqual(rendered({"a.md": (Part("## The `foo` tool", small=True), Part("``"))}), "- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```")
|
||||
|
||||
def test_a_longer_run_without_padding_spaces_is_the_text_between_its_runs(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- ``a`b.md``: ``## The `foo` tool`` (small), ``` `` ```, `` `x` ``\n"), {"a`b.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
|
||||
|
||||
def test_a_longer_run_with_a_space_at_one_end_only_keeps_it(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` x``, ``y ``, `` a ``\n"), {"a.md": (Part(" x"), Part("y "), Part("a"))})
|
||||
|
||||
@needs_docker
|
||||
def test_a_list_written_in_markdown_and_read_back_from_a_jira_description_reads_as_written(self) -> None:
|
||||
description = convert.markdown_to_adf(DETAIL)
|
||||
assert isinstance(description, dict)
|
||||
self.assertEqual(predicted(convert.adf_to_markdown(description)), predicted(DETAIL))
|
||||
|
||||
@needs_docker
|
||||
def test_a_list_typed_in_jiras_editor_reads_as_its_files_and_parts(self) -> None:
|
||||
read = convert.adf_to_markdown(JIRA_TOUCHES)
|
||||
self.assertEqual(predicted(read), {
|
||||
"bin/a.py": (Part("main"), Part("Plan.branch", small=True)),
|
||||
"a`b.md": (Part("## The `foo` tool", small=True), Part("`x`")),
|
||||
"bin/run.sh": (Part("lines 10-20"),),
|
||||
"docs/new.md": (),
|
||||
})
|
||||
|
||||
def test_a_name_ends_only_at_a_run_as_long_as_the_one_that_opens_it(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` a ``` b ``, `c``d`\n"), {"a.md": (Part("a ``` b"), Part("c``d"))})
|
||||
|
||||
def test_a_path_holds_any_character_and_a_single_backtick_keeps_a_names_spaces(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `my file.md`: ` x `\n- `` a`b.md ``\n"), {"my file.md": (Part(" x "),), "a`b.md": ()})
|
||||
|
||||
def test_rendered_reads_back_whatever_a_path_or_a_name_holds(self) -> None:
|
||||
touches = {"my file.md": (Part("## todo.md: under `Touches:` in its detail"), Part("## ``a`` and `b`", small=True), Part("`"), Part("## ends in `x`"), Part(" x "), Part("lines 2-3")), "a`b.md": (), "c, d: e.md": (Part("# T"),)}
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_bullet_with_an_unclosed_run_a_blank_name_or_a_stray_separator_is_a_failure(self) -> None:
|
||||
for bullet in ("- `a.md`: `` ## A", "- `a.md`: `` ## A `", "- `a.md`: `` ``", "- `a.md`: ", "- `a.md`:", "- `a.md`: `f`, ", "- `a.md`: `f`,`g`", "- ``", "- `a.md` (small)", "- `a.md`: `f` (small) (small)"):
|
||||
with self.subTest(bullet):
|
||||
self.assertIsInstance(predicted(f"Touches:\n\n{bullet}\n"), Failure)
|
||||
|
||||
def test_a_range_that_runs_backwards_is_a_failure_that_says_so(self) -> None:
|
||||
found = predicted("Touches:\n\n- `bin/a.py`: `f`, lines 20-10\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, "the bullet '- `bin/a.py`: `f`, lines 20-10' under `Touches:` holds a line range whose first line comes after its last")
|
||||
|
||||
def test_together_joins_items_and_keeps_small_only_where_each_says_so(self) -> None:
|
||||
joined = together([{"a.py": (Part("f", small=True), Part("g", small=True))}, {"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),)}])
|
||||
self.assertEqual(joined, {"a.py": (Part("f"), Part("g", small=True)), "b.md": ()})
|
||||
|
||||
def test_together_keeps_a_part_not_small_once_one_says_so_and_reads_on_past_a_whole_file(self) -> None:
|
||||
joined = together([{"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),), "a.py": (Part("f", small=True),), "c.py": (Part("h"),)}])
|
||||
self.assertEqual(joined, {"a.py": (Part("f"),), "b.md": (), "c.py": (Part("h"),)})
|
||||
|
||||
|
||||
class OverlapsTest(unittest.TestCase):
|
||||
def test_other_files_and_other_parts_do_not_overlap(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("g"),), "b.py": ()}), [])
|
||||
|
||||
def test_the_same_part_overlaps(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"), Part("g"))}, {"a.py": (Part("g"),)}), ["`a.py` `g`"])
|
||||
|
||||
def test_a_class_overlaps_its_method_but_not_a_name_it_only_starts(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("Plan"),)}, {"a.py": (Part("Plan.branch"), Part("Planned"))}), ["`a.py` `Plan`"])
|
||||
|
||||
def test_a_whole_file_overlaps_any_part_of_it(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": ()}, {"a.py": (Part("g", small=True),)}), ["`a.py`"])
|
||||
|
||||
def test_reads_on_past_a_file_only_one_touches_and_past_a_whole_file(self) -> None:
|
||||
theirs = {"a.py": (), "b.py": (Part("g"),)}
|
||||
self.assertEqual(overlaps({"z.py": (Part("f"),), "a.py": (), "b.py": (Part("g"),)}, theirs), ["`a.py`", "`b.py` `g`"])
|
||||
|
||||
def test_line_ranges_overlap_where_they_share_a_line(self) -> None:
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 1-10"),)}, {"x.sh": (Part("lines 10-12"),)}), ["`x.sh` lines 1-10"])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 1-9"),)}, {"x.sh": (Part("lines 10-12"),)}), [])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 10-12"),)}, {"x.sh": (Part("lines 1-10"),)}), ["`x.sh` lines 10-12"])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 11-12"),)}, {"x.sh": (Part("lines 1-10"),)}), [])
|
||||
|
||||
def test_a_line_range_overlaps_a_named_part_since_nothing_tells_them_apart(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("lines 1-9"),)}, {"a.py": (Part("f"),)}), ["`a.py` lines 1-9"])
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("lines 1-9"),)}), ["`a.py` `f`"])
|
||||
|
||||
def test_a_small_change_on_either_side_is_taken(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"),)}), [])
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("f", small=True),)}), [])
|
||||
@@ -22,6 +22,9 @@ BLOCKED_BY = "Blocked by"
|
||||
MOVES = "Moves"
|
||||
# The achieve goal every project shares, which ~/.claude/CLAUDE.md → "Shared goal" states, and a Moves cell names by these words, since it has no number in any goals file.
|
||||
CODE_HEALTH = "code health"
|
||||
# The scope that opens a goal's name in the Moves of an epic's item, since the epic and the item's repo both number their goals from 1: `epic 1.1 by 8, code health by 5, repo 2 by 4`. Three readers, seated as the human who writes these cells, picked a scope word on both goals, 3-0, over one on either alone and over the repo's name. A todo.md's item may name neither.
|
||||
EPIC_GOAL = "epic "
|
||||
REPO_GOAL = "repo "
|
||||
# How the items table's header opens, which tells it from any other table in todo.md.
|
||||
HEADER_START = "| ID | Release |"
|
||||
# todo.md's ## Details section, its body the first group.
|
||||
@@ -61,7 +64,7 @@ class Shape:
|
||||
|
||||
def parse_moves(label: str, cell: str) -> Moves | Failure:
|
||||
"""A Moves cell: empty, or each goal the item moves, named once, and how far. ranking.py's cited_goals_failure holds the rules that need the goals file."""
|
||||
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
matches = [re.fullmatch(rf"((?:{EPIC_GOAL}|{REPO_GOAL})?[0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
|
||||
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
|
||||
return Failure(f"{label}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""An item's prediction of the files and parts it will touch, as its detail spells it, and where two predictions overlap.
|
||||
|
||||
It sits in plan so that plan_store's `FilePlan.check` and todo-item can call `predicted`: touch_predictions imports plan_store, and importing touch_predictions from plan_store would make the two packages import each other.
|
||||
|
||||
The spelling, which the decision `todo.md: an item of the next release predicts the files and parts it will touch …` gives the reasons for:
|
||||
|
||||
Touches:
|
||||
@@ -46,7 +48,7 @@ def predicted(detail: str) -> Touches | None | Failure:
|
||||
break
|
||||
read = bullet(line)
|
||||
if read is None:
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>`, and optionally `{SMALL}`")
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>` that `{SMALL.strip()}` may follow; `{SMALL.strip()}` follows a part, never a bare path")
|
||||
if any(span and span[0] > span[1] for span in map(line_range, read[1])):
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` holds a line range whose first line comes after its last")
|
||||
touches = together([touches, {read[0]: read[1]}])
|
||||
@@ -7,6 +7,7 @@ from plan_store.plans import cells, Plan, Written
|
||||
from failure import Failure
|
||||
from plan.todo_table import item_details, items, NoItemsTable, renames
|
||||
from plan_store import markdown_edits
|
||||
from plan.touches import predicted
|
||||
from plan import ranking
|
||||
from record_store.stores import RecordStore
|
||||
from text_files.file_writes import replace_file
|
||||
@@ -84,7 +85,7 @@ class FilePlan:
|
||||
return ranked
|
||||
|
||||
def check(self) -> list[str]:
|
||||
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, or an item scores under the bar."""
|
||||
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, an item scores under the bar, or touch-predictions cannot read an item's `Touches:` list."""
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return [texts.reason]
|
||||
@@ -92,7 +93,7 @@ class FilePlan:
|
||||
if isinstance(ranked, Failure):
|
||||
return [ranked.reason]
|
||||
unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"]
|
||||
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar]
|
||||
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar + unreadable_touches(texts[0])]
|
||||
|
||||
def reported(self, ranked: ranking.Ranked) -> list[str]:
|
||||
"""Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr."""
|
||||
@@ -115,6 +116,14 @@ class FilePlan:
|
||||
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
|
||||
|
||||
|
||||
def unreadable_touches(todo: str) -> list[str]:
|
||||
"""One line per item whose `Touches:` list touch-predictions cannot read, saying why. Every item is read, not only the next release's: a later item moves into the next release with its detail, and the list is fixed most cheaply where it was written."""
|
||||
details = item_details(todo)
|
||||
if isinstance(details, Failure):
|
||||
return [details.reason]
|
||||
return [f"item {id_}: {read.reason}" for id_, detail in details.items() if isinstance(read := predicted(detail), Failure)]
|
||||
|
||||
|
||||
def plan_of(todo: str) -> Plan | Failure:
|
||||
"""The plan a todo.md's text holds."""
|
||||
found = items(todo)
|
||||
|
||||
+3
-2
@@ -11,7 +11,8 @@ question rows come first, then security rows, then the rest, each group by score
|
||||
then by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below
|
||||
an item it blocks to just above the first such item. Orders the details to match. Writes each
|
||||
item's R, and adds the Blocked by and R columns to a table without them. --check doesn't write
|
||||
anything and fails when the file is not ranked as it would be.
|
||||
anything and fails when the file is not ranked as it would be, or when an item's detail holds a
|
||||
`Touches:` list not spelt as `touch-predictions --help` shows.
|
||||
|
||||
A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
@@ -87,7 +88,7 @@ Exit 1, saying why, on bad arguments, a checkout no config names or a config tha
|
||||
file given that is not the config's plan, a file that cannot be read or written, a todo.md, goals file or docs/decisions.md that breaks the
|
||||
rules above, a scoring run on docs/comprehension-history.md's newest scored commit with no Mean row
|
||||
ending in its overall, an item that is not exempt scoring under the bar, or --check finding the file
|
||||
unranked.
|
||||
unranked, or an item's `Touches:` list unreadable.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
@@ -12,6 +12,7 @@ from plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO
|
||||
from project_config.settings import DEFAULT_FLOOR
|
||||
from plan import goals_file, ranking
|
||||
import rank_todo
|
||||
from todo_item.test_todo_item import READABLE_TOUCHES, UNREADABLE_BULLETS
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
@@ -102,6 +103,25 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: {under}\n"))
|
||||
self.assertEqual(self.run_main("--check", str(todo)), (1, f"{todo}: {under}\n"))
|
||||
|
||||
def test_check_fails_on_each_item_whose_touches_list_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
configured(self, pathlib.Path(temp))
|
||||
self.enterContext(contextlib.chdir(temp))
|
||||
pathlib.Path(temp, "README.md").write_text(README)
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS)
|
||||
for bullet in UNREADABLE_BULLETS:
|
||||
with self.subTest(bullet):
|
||||
# Item 1 sits in a later release than item 3: the check reads every item's list, not only the next release's.
|
||||
todo.write_text(TODO.replace("Fast detail.", READABLE_TOUCHES).replace("Later detail.", f"Touches:\n\n{bullet}"))
|
||||
self.assertEqual(self.run_main(str(todo))[0], 0)
|
||||
code, said = self.run_main("--check", str(todo))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertTrue(said.startswith(f"{todo}: item 1: "), said)
|
||||
self.assertIn(repr(bullet), said)
|
||||
self.assertEqual(said.count("\n"), 1)
|
||||
|
||||
def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
|
||||
+14
-4
@@ -27,7 +27,8 @@ list and show read only the plan, and print no Score: an item's place in list's
|
||||
|
||||
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
|
||||
stdin, if any. The detail may hold no ## or ### heading.
|
||||
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
|
||||
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar,
|
||||
or where the detail holds a `Touches:` list not spelt as `touch-predictions --help` shows.
|
||||
In a Jira epic, add files a Task under the epic, and <ID> is the new issue's number. The release
|
||||
must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there, and --exempt
|
||||
security also labels the issue `security`. The item scores by the config's `jira-score-formula`, and
|
||||
@@ -41,7 +42,8 @@ edit sets the cells whose flag is given and leaves the rest; an empty value, as
|
||||
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
|
||||
Text on stdin without --detail, and --detail without text on stdin, are refused, so no detail is
|
||||
dropped or wiped by mistake. It prints `Edited item <ID> in <plan>.` It doesn't write anything where
|
||||
ranking fails or scores the item under the bar.
|
||||
ranking fails or scores the item under the bar, or where a new detail holds a `Touches:` list not
|
||||
spelt as `touch-predictions --help` shows.
|
||||
In a Jira epic, edit changes an issue the loop filed: its summary, description and scores, the label
|
||||
`security` with --exempt, and its "is blocked by" links with --blocked-by: it makes a link for each
|
||||
blocker added and deletes the link of each blocker dropped. Each blocker must be an open child of the
|
||||
@@ -89,6 +91,7 @@ from project_config.main import located
|
||||
from plan_store.plans import no_item, PlanStore, TAGLINE, Written
|
||||
from plan.release import parsed, Release, version as release_version
|
||||
from plan_store.stores import store as plan_store
|
||||
from plan.touches import predicted
|
||||
from record_store.stores import RecordStore, store
|
||||
from todo_item.table import shown, table
|
||||
from todo_item.edits import with_bullet
|
||||
@@ -115,7 +118,8 @@ def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.T
|
||||
case "show":
|
||||
done = show(args, plan)
|
||||
case "add":
|
||||
done = reported(plan.add(fields(args), piped(stdin)), "not filed", lambda written: f"Filed item {written.id} in {plan.label}.")
|
||||
detail = piped(stdin)
|
||||
done = unreadable(detail, "not filed") or reported(plan.add(fields(args), detail), "not filed", lambda written: f"Filed item {written.id} in {plan.label}.")
|
||||
case "edit":
|
||||
done = edit(args, plan, piped(stdin))
|
||||
case "move":
|
||||
@@ -194,6 +198,12 @@ def reported(written: Written | Failure, refusal: str, done: typing.Callable[[Wr
|
||||
return done(written)
|
||||
|
||||
|
||||
def unreadable(detail: str | None, refusal: str) -> Failure | None:
|
||||
"""A Failure opened with refusal where detail holds a `Touches:` list touch-predictions cannot read; checked here, before the plan's backend gets the detail, so a plan in Jira is held to it too."""
|
||||
read = None if detail is None else predicted(detail)
|
||||
return Failure(f"{refusal}: {read.reason}") if isinstance(read, Failure) else None
|
||||
|
||||
|
||||
def list_(args: argparse.Namespace, plan: PlanStore) -> str | Failure:
|
||||
read = plan.read()
|
||||
if isinstance(read, Failure):
|
||||
@@ -220,7 +230,7 @@ def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure:
|
||||
detail = text if args.detail else "" if args.clear_detail else None
|
||||
if not fields(args) and detail is None:
|
||||
return Failure("not edited: no flag names a change; todo-item --help lists them")
|
||||
return reported(plan.edit(args.id, fields(args), detail, args.comment), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
return unreadable(detail, f"not edited: item {args.id}'s detail") or reported(plan.edit(args.id, fields(args), detail, args.comment), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
|
||||
|
||||
def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore | None) -> str | Failure:
|
||||
|
||||
@@ -25,6 +25,16 @@ CHANGELOG = "# Changelog\n\n## Unreleased\n\n- Older news.\n\n## 0.1.0\n\n- Firs
|
||||
# ## Details of the ranked fixture, without the trailing ## Notes.
|
||||
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
DETAILS = "## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n"
|
||||
# The bullets six items held on 2026-11-18, which touch-predictions cannot read: `(small)` after a bare path, and a part not in backticks.
|
||||
UNREADABLE_BULLETS = (
|
||||
"- `bin/judge_replay/main.py` (small)",
|
||||
"- `bin/do_epic/main.py` (small)",
|
||||
"- `principles/technical-principles.md`: the tests bullet group, `A valuable test checks behaviour` (small)",
|
||||
"- `README.md`: loop-claude's section (small)",
|
||||
"- `bin/rule_hook/rules.py`: the rule table (small)",
|
||||
"- `settings.json`: the PreToolUse matcher (small)",
|
||||
)
|
||||
READABLE_TOUCHES = "Why.\n\nTouches:\n\n- `bin/a.py`: `main`, `Plan.branch` (small)\n- `bin/run.sh`: lines 10-20\n- `docs/new.md`\n"
|
||||
|
||||
|
||||
class Terminal(io.StringIO):
|
||||
@@ -488,6 +498,37 @@ class Edit(TodoItem):
|
||||
self.assertEqual(self.todo.read_text(), before)
|
||||
|
||||
|
||||
class UnreadableTouches(TodoItem):
|
||||
"""A `Touches:` list touch-predictions cannot read is refused when written, since loop-claude doesn't start any chunk beside an item whose list it cannot read."""
|
||||
|
||||
def test_add_and_edit_refuse_each_bullet_that_stalled_the_loop(self):
|
||||
for bullet in UNREADABLE_BULLETS:
|
||||
for argv, refusal in ((ADD, "not filed: "), (["edit", "3", "--detail"], "not edited: item 3's detail: ")):
|
||||
with self.subTest(bullet=bullet, command=argv[0]):
|
||||
before = self.todo.read_text()
|
||||
code, out, err = self.run_main(*argv, stdin=f"Why.\n\nTouches:\n\n- `bin/a.py`: `main`\n{bullet}\n")
|
||||
self.assertEqual((code, out), (1, ""))
|
||||
self.assertTrue(err.startswith(refusal), err)
|
||||
self.assertIn(repr(bullet), err)
|
||||
self.assertEqual(self.todo.read_text(), before)
|
||||
|
||||
def test_add_and_edit_take_a_readable_list_and_a_detail_without_one(self):
|
||||
for detail in (READABLE_TOUCHES, "Why, without a list.\n"):
|
||||
with self.subTest(detail):
|
||||
self.assertEqual(self.run_main(*ADD, stdin=detail)[0], 0)
|
||||
self.assertEqual(self.run_main("edit", "3", "--detail", stdin=detail)[0], 0)
|
||||
self.assertIn(detail, self.todo.read_text())
|
||||
|
||||
def test_a_plan_in_jira_gets_no_unreadable_list_either(self):
|
||||
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', f'"{JIRA_PLAN}"') + 'env-file = "~/acme.env"\n' + JIRA_SCORING)
|
||||
plan = MemoryPlan({3: {"Release": "0.1.0", "Item": "**Count the runs.**", "L": "1", "E": "2", "I": "3", "S": "1"}})
|
||||
self.enterContext(unittest.mock.patch.object(main, "plan_store", return_value=plan))
|
||||
detail = f"Touches:\n\n{UNREADABLE_BULLETS[0]}\n"
|
||||
self.assertEqual(self.run_main(*ADD, stdin=detail)[:2], (1, ""))
|
||||
self.assertEqual(self.run_main("edit", "3", "--detail", stdin=detail)[:2], (1, ""))
|
||||
self.assertEqual((list(plan.rows), plan.details), ([3], {}))
|
||||
|
||||
|
||||
class Move(TodoItem):
|
||||
def test_sets_the_items_release_and_keeps_the_rest(self):
|
||||
self.assertEqual(self.run_main("move", "3", "--release", "0.2.0"), (0, f"Moved item 3 to release 0.2.0 in {self.todo}.\n", ""))
|
||||
|
||||
@@ -3,7 +3,7 @@ import dataclasses
|
||||
|
||||
from failure import Failure
|
||||
from plan.todo_table import Item, waiting
|
||||
from touch_predictions.prediction import LABEL, overlaps, predicted, Touches
|
||||
from plan.touches import LABEL, overlaps, predicted, Touches
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
|
||||
@@ -3,7 +3,7 @@ import re
|
||||
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
from touch_predictions.prediction import Part, Touches
|
||||
from plan.touches import Part, Touches
|
||||
from touch_predictions.file_parts import part_names
|
||||
|
||||
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M)
|
||||
|
||||
@@ -49,7 +49,7 @@ import typing
|
||||
from git_cli.git_repo import default_ref, git, Git
|
||||
from failure import Failure
|
||||
from plan_store.stores import store as plan_store
|
||||
from touch_predictions.prediction import predicted, together, Touches
|
||||
from plan.touches import predicted, together, Touches
|
||||
from project_config.main import project
|
||||
from project_config.settings import ProjectConfig, TOUCH_PREDICTIONS
|
||||
from touch_predictions import record
|
||||
|
||||
@@ -3,7 +3,7 @@ import re
|
||||
|
||||
from failure import Failure
|
||||
from record_store.stores import RecordStore
|
||||
from touch_predictions.prediction import rendered, Touches
|
||||
from plan.touches import rendered, Touches
|
||||
from text_files.utc_stamp import STAMPED
|
||||
|
||||
TITLE = "# Touch predictions"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -10,53 +9,16 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from touch_predictions.beside import Beside, chunks_beside
|
||||
from adf_codec import convert
|
||||
from touch_predictions import diff_parts, file_parts, main, record
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from project_config.main import located
|
||||
from record_store.fakes import MemoryStore
|
||||
from touch_predictions.prediction import overlaps, Part, predicted, rendered, together
|
||||
from plan.touches import Part
|
||||
from plan_store.todo_md import plan_of
|
||||
from project_config.settings import ProjectConfig
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
DETAIL = """A planning call.
|
||||
|
||||
Touches:
|
||||
|
||||
- `bin/a.py`: `main`, `Plan.branch` (small)
|
||||
- `README.md`: `## Goals, and (more): things`
|
||||
- `bin/run.sh`: lines 10-20
|
||||
- `docs/new.md`
|
||||
|
||||
More prose, with `bin/b.py` named.
|
||||
"""
|
||||
|
||||
needs_docker = unittest.skipIf(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode != 0, "adf_codec runs in a container, which needs a docker daemon")
|
||||
|
||||
|
||||
def text(words: str, code: bool = False) -> dict:
|
||||
return {"type": "text", "text": words, **({"marks": [{"type": "code"}]} if code else {})}
|
||||
|
||||
|
||||
def bullet_of(*spans: dict) -> dict:
|
||||
return {"type": "listItem", "attrs": {"localId": "i"}, "content": [{"type": "paragraph", "attrs": {"localId": "p"}, "content": list(spans)}]}
|
||||
|
||||
|
||||
# A Touches list as someone types it in Jira's editor: a paragraph, then a bulleted list whose paths and names carry the code mark.
|
||||
JIRA_TOUCHES = {"type": "doc", "version": 1, "content": [
|
||||
{"type": "paragraph", "attrs": {"localId": "a"}, "content": [text("A planning call.")]},
|
||||
{"type": "paragraph", "attrs": {"localId": "b"}, "content": [text("Touches:")]},
|
||||
{"type": "bulletList", "attrs": {"localId": "c"}, "content": [
|
||||
bullet_of(text("bin/a.py", True), text(": "), text("main", True), text(", "), text("Plan.branch", True), text(" (small)")),
|
||||
bullet_of(text("a`b.md", True), text(": "), text("## The `foo` tool", True), text(" (small)"), text(", "), text("`x`", True)),
|
||||
bullet_of(text("bin/run.sh", True), text(": lines 10-20")),
|
||||
bullet_of(text("docs/new.md", True)),
|
||||
]},
|
||||
{"type": "paragraph", "attrs": {"localId": "d"}, "content": [text("More prose.")]},
|
||||
]}
|
||||
|
||||
PYTHON = """\"\"\"Docstring.\"\"\"
|
||||
import os
|
||||
|
||||
@@ -98,126 +60,6 @@ Text.
|
||||
"""
|
||||
|
||||
|
||||
class PredictedTest(unittest.TestCase):
|
||||
def test_reads_each_bullet_of_the_touches_list(self) -> None:
|
||||
self.assertEqual(predicted(DETAIL), {
|
||||
"bin/a.py": (Part("main"), Part("Plan.branch", small=True)),
|
||||
"README.md": (Part("## Goals, and (more): things"),),
|
||||
"bin/run.sh": (Part("lines 10-20"),),
|
||||
"docs/new.md": (),
|
||||
})
|
||||
|
||||
def test_a_detail_without_the_list_predicts_nothing(self) -> None:
|
||||
self.assertIsNone(predicted("Only prose, with `bin/a.py` named."))
|
||||
|
||||
def test_a_bullet_it_cannot_read_is_a_failure_that_quotes_it(self) -> None:
|
||||
for bullet in ("- bin/a.py: main", "- `bin/a.py`: main", "- `bin/a.py`: lines 20-10", "- `bin/a.py`: `main` `other`"):
|
||||
with self.subTest(bullet):
|
||||
found = predicted(f"Touches:\n\n{bullet}\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertIn(bullet, found.reason)
|
||||
|
||||
def test_an_empty_list_is_a_failure(self) -> None:
|
||||
self.assertIsInstance(predicted("Touches:\n\nProse.\n"), Failure)
|
||||
found = predicted("Touches:\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, "no bullet follows `Touches:`")
|
||||
|
||||
def test_reads_a_list_right_under_its_label_a_one_line_range_and_a_name_of_any_letters(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.py`: `Xray`, lines 5-5\n"), {"a.py": (Part("Xray"), Part("lines 5-5"))})
|
||||
|
||||
def test_rendered_reads_back(self) -> None:
|
||||
touches = predicted(DETAIL)
|
||||
assert isinstance(touches, dict)
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_name_that_holds_backticks_takes_a_longer_run_with_a_space_inside_each_end(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```, `` `x` ``\n"), {"a.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
|
||||
self.assertEqual(rendered({"a.md": (Part("## The `foo` tool", small=True), Part("``"))}), "- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```")
|
||||
|
||||
def test_a_longer_run_without_padding_spaces_is_the_text_between_its_runs(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- ``a`b.md``: ``## The `foo` tool`` (small), ``` `` ```, `` `x` ``\n"), {"a`b.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
|
||||
|
||||
def test_a_longer_run_with_a_space_at_one_end_only_keeps_it(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` x``, ``y ``, `` a ``\n"), {"a.md": (Part(" x"), Part("y "), Part("a"))})
|
||||
|
||||
@needs_docker
|
||||
def test_a_list_written_in_markdown_and_read_back_from_a_jira_description_reads_as_written(self) -> None:
|
||||
description = convert.markdown_to_adf(DETAIL)
|
||||
assert isinstance(description, dict)
|
||||
self.assertEqual(predicted(convert.adf_to_markdown(description)), predicted(DETAIL))
|
||||
|
||||
@needs_docker
|
||||
def test_a_list_typed_in_jiras_editor_reads_as_its_files_and_parts(self) -> None:
|
||||
read = convert.adf_to_markdown(JIRA_TOUCHES)
|
||||
self.assertEqual(predicted(read), {
|
||||
"bin/a.py": (Part("main"), Part("Plan.branch", small=True)),
|
||||
"a`b.md": (Part("## The `foo` tool", small=True), Part("`x`")),
|
||||
"bin/run.sh": (Part("lines 10-20"),),
|
||||
"docs/new.md": (),
|
||||
})
|
||||
|
||||
def test_a_name_ends_only_at_a_run_as_long_as_the_one_that_opens_it(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` a ``` b ``, `c``d`\n"), {"a.md": (Part("a ``` b"), Part("c``d"))})
|
||||
|
||||
def test_a_path_holds_any_character_and_a_single_backtick_keeps_a_names_spaces(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `my file.md`: ` x `\n- `` a`b.md ``\n"), {"my file.md": (Part(" x "),), "a`b.md": ()})
|
||||
|
||||
def test_rendered_reads_back_whatever_a_path_or_a_name_holds(self) -> None:
|
||||
touches = {"my file.md": (Part("## todo.md: under `Touches:` in its detail"), Part("## ``a`` and `b`", small=True), Part("`"), Part("## ends in `x`"), Part(" x "), Part("lines 2-3")), "a`b.md": (), "c, d: e.md": (Part("# T"),)}
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_bullet_with_an_unclosed_run_a_blank_name_or_a_stray_separator_is_a_failure(self) -> None:
|
||||
for bullet in ("- `a.md`: `` ## A", "- `a.md`: `` ## A `", "- `a.md`: `` ``", "- `a.md`: ", "- `a.md`:", "- `a.md`: `f`, ", "- `a.md`: `f`,`g`", "- ``", "- `a.md` (small)", "- `a.md`: `f` (small) (small)"):
|
||||
with self.subTest(bullet):
|
||||
self.assertIsInstance(predicted(f"Touches:\n\n{bullet}\n"), Failure)
|
||||
|
||||
def test_a_range_that_runs_backwards_is_a_failure_that_says_so(self) -> None:
|
||||
found = predicted("Touches:\n\n- `bin/a.py`: `f`, lines 20-10\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, "the bullet '- `bin/a.py`: `f`, lines 20-10' under `Touches:` holds a line range whose first line comes after its last")
|
||||
|
||||
def test_together_joins_items_and_keeps_small_only_where_each_says_so(self) -> None:
|
||||
joined = together([{"a.py": (Part("f", small=True), Part("g", small=True))}, {"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),)}])
|
||||
self.assertEqual(joined, {"a.py": (Part("f"), Part("g", small=True)), "b.md": ()})
|
||||
|
||||
def test_together_keeps_a_part_not_small_once_one_says_so_and_reads_on_past_a_whole_file(self) -> None:
|
||||
joined = together([{"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),), "a.py": (Part("f", small=True),), "c.py": (Part("h"),)}])
|
||||
self.assertEqual(joined, {"a.py": (Part("f"),), "b.md": (), "c.py": (Part("h"),)})
|
||||
|
||||
|
||||
class OverlapsTest(unittest.TestCase):
|
||||
def test_other_files_and_other_parts_do_not_overlap(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("g"),), "b.py": ()}), [])
|
||||
|
||||
def test_the_same_part_overlaps(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"), Part("g"))}, {"a.py": (Part("g"),)}), ["`a.py` `g`"])
|
||||
|
||||
def test_a_class_overlaps_its_method_but_not_a_name_it_only_starts(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("Plan"),)}, {"a.py": (Part("Plan.branch"), Part("Planned"))}), ["`a.py` `Plan`"])
|
||||
|
||||
def test_a_whole_file_overlaps_any_part_of_it(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": ()}, {"a.py": (Part("g", small=True),)}), ["`a.py`"])
|
||||
|
||||
def test_reads_on_past_a_file_only_one_touches_and_past_a_whole_file(self) -> None:
|
||||
theirs = {"a.py": (), "b.py": (Part("g"),)}
|
||||
self.assertEqual(overlaps({"z.py": (Part("f"),), "a.py": (), "b.py": (Part("g"),)}, theirs), ["`a.py`", "`b.py` `g`"])
|
||||
|
||||
def test_line_ranges_overlap_where_they_share_a_line(self) -> None:
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 1-10"),)}, {"x.sh": (Part("lines 10-12"),)}), ["`x.sh` lines 1-10"])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 1-9"),)}, {"x.sh": (Part("lines 10-12"),)}), [])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 10-12"),)}, {"x.sh": (Part("lines 1-10"),)}), ["`x.sh` lines 10-12"])
|
||||
self.assertEqual(overlaps({"x.sh": (Part("lines 11-12"),)}, {"x.sh": (Part("lines 1-10"),)}), [])
|
||||
|
||||
def test_a_line_range_overlaps_a_named_part_since_nothing_tells_them_apart(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("lines 1-9"),)}, {"a.py": (Part("f"),)}), ["`a.py` lines 1-9"])
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("lines 1-9"),)}), ["`a.py` `f`"])
|
||||
|
||||
def test_a_small_change_on_either_side_is_taken(self) -> None:
|
||||
self.assertEqual(overlaps({"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"),)}), [])
|
||||
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("f", small=True),)}), [])
|
||||
|
||||
|
||||
class FilePartsTest(unittest.TestCase):
|
||||
def names(self, path: str, text: str, *lines: int) -> set[str] | None:
|
||||
return file_parts.part_names(path, text, lines)
|
||||
|
||||
Reference in New Issue
Block a user