Files
claude-config/bin/do_epic/planning.py
T

188 lines
12 KiB
Python

"""What `do-epic <EPIC-KEY>` settles before it starts chunks: where each open issue is worked, and the order the loop's issues come in (docs/decisions.md → `do-epic: drives one Jira epic …`).
An open child issue that no label places is first split by repo (`split`), and where it changes one repo or none, its repo is picked (`repo_pick`). Each is a headless claude call on `repoless-model`'s rung of the shipped ladder. Where the repo rule leaves a pick unclear, the human answers on the terminal. Then the issues do-epic filed are scored and Jira's backlog re-ranked to match (`ranking`).
Planning runs only in the `do-epic <EPIC-KEY>` the human starts. A chunk that finishes starts the next chunks from the labels and the order it finds, so no window waits on a question.
Planning holds no lock: one `do-epic <EPIC-KEY>` at a time is assumed. A second one started meanwhile finds the sub-tasks the first filed, since `split` reads them before it files, unless Jira's search lags."""
import dataclasses
import pathlib
import re
from do_epic.config import DoEpicConfig
from loop_effects.effects import Effects, say
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.epic_record import EpicRecord
from failure import Failure
from record_store.stores import goals_store, store as record_store
from plan.todo_table import Item
from claude_code.reply import Limited
from plan_store.jira_epic import number
from do_epic import ranking, repo_pick, repos, split
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.ladder import Rung
from do_epic.scheduler import STATE
from plan_store.scoring import weighing_texts
# The epic's formula, stated under its `## Scoring` as a todo.md states its own.
FORMULA = re.compile(r"^`Score = ([^`]+)`$", re.M)
# An epic item has no release, and ranking wants every item of one epic in the same one.
NO_RELEASE = (0, 0, 0)
@dataclasses.dataclass(frozen=True)
class Planned:
"""The epic whose open issues are planned."""
key: str
config: DoEpicConfig
store: EpicStore
record: EpicRecord
home: pathlib.Path
effects: Effects
def planned(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Failure | Limited | None]:
"""The epic's issues as far as they are planned, and why the planning stopped early, None where it didn't. issues are the epic's, as just read.
Each open child issue that no label places, and that isn't split already, is split or gets its pick. Then the issues do-epic filed are re-ranked. What was labelled, filed or ranked before a Failure or a Limited stays, and the issues returned show it."""
unplaced = [issue for issue in issues if issue.parent == epic.key and not issue.done and not split.is_split(issue, issues) and repo_pick.recorded(issue, epic.config.label_repos) is None]
added: dict[str, str] = {}
stopped = placed(epic, issues, unplaced, added) if unplaced else None
if added:
read = epic.store.read()
# A search may not show a label added a moment ago, so each label added here counts whatever the read says. A sub-task the search doesn't show yet starts on the next run.
issues = [labelled(each, added.get(each.key)) for each in (issues if isinstance(read, Failure) else read)]
stopped = stopped or (read if isinstance(read, Failure) else None)
if stopped is not None:
return issues, stopped
order = ranked_keys(epic, issues)
if isinstance(order, Failure):
return issues, order
if [issue.key for issue in issues if issue.key in order] == order:
return issues, None
say(f"re-ranking the issues do-epic filed in {epic.key}'s backlog", epic.effects, stdout=True)
refused = ranking.reranked(epic.store, order)
if refused:
return issues, refused
# A search may not show the new order yet, so the issues are put in it here, as `reranked` put them in Jira: each ranked issue in a position a ranked issue held.
by_key, ranked = {issue.key: issue for issue in issues}, iter(order)
return [by_key[next(ranked)] if issue.key in order else issue for issue in issues], None
def labelled(issue: EpicIssue, label: str | None) -> EpicIssue:
"""issue with label among its labels; issue itself where label is None."""
return issue if label is None or label in issue.labels else dataclasses.replace(issue, labels=tuple(sorted((*issue.labels, label))))
def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], added: dict[str, str]) -> None | Failure | Limited:
"""Splits each of unplaced by repo, or labels it with its pick, and notes in added the label each got, by its key. An issue that claude or the tracker fails on is named and left for the next run, as is one whose question the human doesn't answer; a usage limit ends the planning."""
rung = planning_rung(epic.config.repoless_model)
language = epic.record.language()
# Claude reads every repo a label of the epic names, a finished issue's too, to predict which of them an issue changes.
places = located(epic, [repo for issue in issues if isinstance(repo := repo_pick.recorded(issue, epic.config.label_repos), repo_pick.Repo)])
if failed := next((each for each in (rung, language, places) if isinstance(each, Failure)), None):
return failed
assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(places, dict)
folder = epic.home / STATE / epic.key
folder.mkdir(parents=True, exist_ok=True)
checkouts = tuple(str(place.checkout) for place in places.values())
for issue in unplaced:
say(f"planning {issue.key}", epic.effects, stdout=True)
parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder))
if isinstance(parts, split.Split) and parts.repos:
added[issue.key] = split.SPLIT_LABEL
say(f"{issue.key} is split into a sub-task for each of {', '.join(parts.repos)}", epic.effects, stdout=True)
continue
pick: repo_pick.Pick | repo_pick.Unclear | Failure | Limited | None = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, epic.config.label_repos, epic.config.repo_rule, rung, epic.effects.claude, str(folder))
if isinstance(pick, repo_pick.Unclear):
pick = answered(epic, issue, pick.question)
if isinstance(pick, Limited):
return pick
if isinstance(pick, Failure):
say(f"{issue.key} is not planned: {pick.reason}", epic.effects, stdout=True)
elif pick is not None and not isinstance(pick, repo_pick.Unclear):
added[issue.key] = repo_pick.label_of(pick)
say(f"{issue.key} is labelled {added[issue.key]}", epic.effects, stdout=True)
return None
def planning_rung(model: str) -> Rung | Failure:
"""The rung each planning call runs on: the model's cheapest on the shipped ladder."""
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return ladder
project = ladder.project_rung(model)
return project.rung if project else Failure(f"`repoless-model` names {model}, which is not on the routing ladder {SHIPPED}")
def answered(epic: Planned, issue: EpicIssue, question: str) -> repo_pick.Pick | None | Failure:
"""The pick the human types for an issue the repo rule leaves unclear, once it is recorded; None where nobody is at a terminal to answer, or the human answers with Enter alone, so the issue waits for the next run. The answer is the label to give the issue, so that it is spelt as a person would spell it in Jira.
A repo's name is not checked against the repos do-epic knows: an epic's first issue in a repo names one it has not seen."""
if not epic.effects.on_terminal():
say(f"{issue.key} waits for your answer: {question} Run `do-epic {epic.key}` on a terminal to answer, or label the issue in Jira.", epic.effects, stdout=True)
return None
say(f"\n{issue.key}, {issue.summary}: {question}", epic.effects)
while True:
try:
typed = epic.effects.input(f"The label that says where {issue.key} is worked, `{repo_pick.REPO_PREFIX}<name>`, `{repo_pick.CLAUDE_LABEL}` or `{repo_pick.HUMAN_LABEL}`{repo_pick.also(epic.config.label_repos)}, or Enter alone to leave it waiting: ")
except EOFError:
return None
label = typed.strip()
if not label:
return None
pick = repo_pick.of_label(label, epic.config.label_repos)
if pick is not None:
return repo_pick.record(epic.store, issue, pick)
named = f"; the repo {label}'s label is `{repo_pick.REPO_PREFIX}{label}`" if repo_pick.of_label(repo_pick.REPO_PREFIX + label, {}) else ""
say(f"`{label}` is none of those labels{named}", epic.effects)
def located(epic: Planned, picks: list[repo_pick.Repo]) -> dict[str, repos.Located] | Failure:
"""Each picked repo's checkout and project config, by the repo's name."""
places: dict[str, repos.Located] = {}
for name in sorted({pick.name for pick in picks}):
place = repos.locate(name, [each.checkout for each in places.values()], epic.config, epic.home, epic.effects.git)
if isinstance(place, Failure):
return place
places[name] = place
return places
def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure:
"""The keys of the open child issues do-epic filed that hold scores and one pick, in the order ranking gives them; empty where fewer than two do, since one issue has no order.
Every other issue keeps its position: a person's issue, one nobody scored, one with no pick yet or with two, and an item split by repo, since several repos' goals would score it."""
ours = [issue for issue in issues if issue.parent == epic.key and issue.by_loop and not issue.done and not split.is_split(issue, issues) and (pick := repo_pick.recorded(issue, epic.config.label_repos)) is not None and not isinstance(pick, Failure) and not ranking.unscored(item_of(issue, {}), issue.key)]
if len(ours) < 2:
return []
numbers = {issue.key: number(issue.key) for issue in ours}
keys = {id_: key for key, id_ in numbers.items()}
if clash := next(((key, keys[id_]) for key, id_ in numbers.items() if keys[id_] != key), None):
return Failure(f"{clash[0]} and {clash[1]} share a number in different Jira projects, so the issues do-epic filed in the epic {epic.key} cannot be ranked; move one of the two to the other's Jira project")
scoring, goals = epic.record.section("Scoring"), epic.record.section("Goals")
if failed := next((each for each in (scoring, goals) if isinstance(each, Failure)), None):
return Failure(f"the epic {epic.key}'s description: {failed.reason}")
assert isinstance(scoring, str) and isinstance(goals, str)
formulas = FORMULA.findall(scoring)
if len(formulas) != 1:
return Failure(f"the epic {epic.key}'s description states `Score = ...` {len(formulas)} times under ## Scoring; state the formula that ranks its issues once, on a line of its own and inside backticks, such as `Score = 100 * V / (2**S + 32)`")
picks = {issue.key: repo_pick.recorded(issue, epic.config.label_repos) for issue in ours}
places = located(epic, [pick for pick in picks.values() if isinstance(pick, repo_pick.Repo)])
if isinstance(places, Failure):
return places
rankings: dict[str, ranking.RepoRanking] = {}
for name, place in places.items():
texts = weighing_texts(goals_store(place.config), record_store(place.config, "decisions"), record_store(place.config, "comprehension-history"))
if isinstance(texts, Failure):
return Failure(f"{name}: {texts.reason}")
rankings[name] = ranking.RepoRanking(*texts, place.config.readability_floor)
items = [ranking.EpicItem(item_of(issue, numbers), pick.name if isinstance(pick := picks[issue.key], repo_pick.Repo) else None) for issue in ours]
scored = ranking.ranked(items, formulas[0], goals, rankings)
return scored if isinstance(scored, Failure) else [keys[item.id] for item, _ in scored]
def item_of(issue: EpicIssue, numbers: dict[str, int]) -> Item:
"""The issue as ranking scores it. numbers holds the number of each issue ranked with it, by key; the item is blocked by those of them that block the issue."""
return Item(numbers.get(issue.key, 0), NO_RELEASE, issue.exempt, issue.summary, issue.scores, issue.moves, tuple(sorted(numbers[key] for key in issue.blockers if key in numbers)))