178 lines
11 KiB
Python
178 lines
11 KiB
Python
"""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 do_epic.backend.protocol import EpicStore
|
|
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)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Rank:
|
|
"""One rank to ask of a tracker: the issue named key just before the issue named before."""
|
|
key: str
|
|
before: str
|
|
|
|
|
|
def reranked(store: EpicStore, order: list[str]) -> None | Failure:
|
|
"""Re-ranks the tracker's backlog so that the child issues whose keys order lists come in that sequence. Each key must name a child issue the loop filed, and only once; otherwise the call fails before it ranks any issue. The listed issues change positions only with each other: every other child issue, such as one a person filed, stays at its position in the backlog. A sub-task has no position of its own and follows its parent.
|
|
|
|
The first rank the tracker refuses ends the re-rank with a Failure that names it, since a wrongly ranked team backlog takes hours to restore; the ranks made before it stay."""
|
|
read = store.read()
|
|
if isinstance(read, Failure):
|
|
return read
|
|
children = [issue for issue in read if issue.parent == store.epic_key]
|
|
ours = {issue.key for issue in children if issue.by_loop}
|
|
if stray := next((key for key in order if key not in ours), None):
|
|
return Failure(f"{stray} is not one of the child issues of the epic {store.epic_key} that the loop filed, so the backlog was not re-ranked")
|
|
if twice := next((key for key in order if order.count(key) > 1), None):
|
|
return Failure(f"the order names {twice} twice, so the backlog was not re-ranked")
|
|
for rank in rank_moves([issue.key for issue in children], order):
|
|
if refused := store.rank(rank.key, rank.before):
|
|
return Failure(f"cannot rank {rank.key} just before {rank.before}: {refused.reason}; the re-rank stopped there, so rank the loop's issues in {store.epic_key}'s backlog by hand to come in this sequence: {', '.join(order)}")
|
|
return None
|
|
|
|
|
|
def rank_moves(backlog: list[str], order: list[str]) -> list[Rank]:
|
|
"""The ranks, in the sequence to make them, that turn backlog, a list of keys, into one where the keys order lists come in that sequence, each at a position one of them held, while every other key keeps its position. order names each key once, and each is in backlog.
|
|
|
|
Working from the backlog's end, a listed key that isn't already just before the key due after it ranks just before that key. The key due last, where it isn't already last, ranks just before the key that is, which moves away in its own turn, since it is due earlier."""
|
|
listed = set(order)
|
|
sequence = iter(order)
|
|
target = [next(sequence) if key in listed else key for key in backlog]
|
|
now = list(backlog)
|
|
ranks = []
|
|
for position in reversed(range(len(target))):
|
|
key = target[position]
|
|
due_after = target[position + 1] if position + 1 < len(target) else None
|
|
at = now.index(key)
|
|
if key not in listed or (now[at + 1] if at + 1 < len(now) else None) == due_after:
|
|
continue
|
|
rank = Rank(key, now[-1] if due_after is None else due_after)
|
|
ranks.append(rank)
|
|
now.remove(key)
|
|
now.insert(now.index(rank.before), key)
|
|
return ranks
|
|
|
|
|
|
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
|