Plan an epic's open issues before do-epic starts chunks
This commit is contained in:
@@ -153,7 +153,7 @@ The last line prints each setting's path once the config is complete.
|
||||
`do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic:
|
||||
|
||||
- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason.
|
||||
- `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. do-epic doesn't read it yet: until it picks each item's repo from the rule, an issue runs once a label `repo:<name>` records its repo, `do-epic-claude` marks work of Claude's that changes no repo, and `do-epic-human` a task of yours.
|
||||
- `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. `do-epic <EPIC-KEY>` picks by it where each open issue is worked, and records the pick as a label: `repo:<name>` for its repo, `do-epic-claude` for work of Claude's that changes no repo, and `do-epic-human` for a task of yours. Where the rule leaves an issue unclear, do-epic asks you on the terminal, and you answer with the label. Change a pick by editing the label in Jira.
|
||||
|
||||
Each repo an epic changes has a project config of its own, as in the rest of this section. `do-epic` fails and names each setting or file that is missing or invalid.
|
||||
|
||||
@@ -190,7 +190,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
|
||||
- `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily.
|
||||
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
|
||||
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. An open issue runs once a label names its repo, in Jira's backlog order, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
|
||||
- `do-epic <EPIC-KEY>` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-<EPIC-KEY>`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic files a sub-task per repo under each open issue that changes several, picks the repo of each other issue that no label names one for, asking you where that is unclear, and re-ranks the issues it filed, by the `Score = ...` line under the description's `## Scoring`. An open issue runs once a label names its repo, in Jira's backlog order, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract.
|
||||
- `judge-replay <model> [--offline]` replays loop-claude's judge on archived verdicts of the projects run on the model. It prints what each rung a review climbs to misses, and the lowest rung below those that returns every verdict, as each candidate above it does. With `--offline` it doesn't call a judge: it counts what a "?" rule, a decision table and a classifier trained on the archive decide of each verdict's kind from the worker's final message, and how many interrupts each misses. `judge-replay --help` states both replays.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count and the opening of its round commit's title, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
|
||||
- `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract.
|
||||
@@ -224,7 +224,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `deploy_release` imports `release_plan`'s `release_standing`.
|
||||
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic.
|
||||
- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the loop's issues, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic.
|
||||
- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and reads its checks, once or until they settle (`pulls.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
|
||||
- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `loop_claude`'s premises, records and `ANSWER_DESTINATIONS`.
|
||||
|
||||
+14
-5
@@ -1,6 +1,6 @@
|
||||
"""The do-epic command (docs/decisions.md → `do-epic: drives one Jira epic …`).
|
||||
|
||||
`do-epic <EPIC-KEY>` starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs loop-claude's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes.
|
||||
`do-epic <EPIC-KEY>` first plans the epic's open issues (`planning`): it splits each by repo, picks the repo of each that no label places, and re-ranks the loop's issues. Then it starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs loop-claude's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes.
|
||||
|
||||
After each cycle of a chunk in a repo, the window reads what the chunk's pull request waits on (`gates`). While that is a gate only time or a person passes, the chunk is parked (`parked`): the window frees its running slot and polls the forge, and the chunk's next cycle starts once the worker has something to do and a slot is free. `do-epic <EPIC-KEY> --status` prints what each open issue does."""
|
||||
import dataclasses
|
||||
@@ -9,7 +9,8 @@ import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.loop.chunk_start import archived_route, routed
|
||||
from do_epic import chunk_prompt, findings, finish, gates, parked, scheduler, split, status
|
||||
from do_epic import chunk_prompt, findings, finish, gates, parked, planning, scheduler, split, status
|
||||
from claude_code.reply import Limited
|
||||
from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from project_config.main import located as config_located
|
||||
@@ -46,8 +47,12 @@ HELP = f"""usage: do-epic <EPIC-KEY> [--status]
|
||||
{finish.USAGE}
|
||||
|
||||
Runs the chunks of one Jira epic, such as ABC-12, each in its own window of the tmux session epic-<EPIC-KEY>.
|
||||
An open issue of the epic runs as a chunk once it has a label and no issue blocks it.
|
||||
The label names the issue's repo, or says the work changes no repo.
|
||||
Before it starts chunks, do-epic <EPIC-KEY> plans each open issue that no label places: it files a sub-task
|
||||
per repo where the issue changes several, and else labels it `repo:<name>` for its repo, `do-epic-claude`
|
||||
for work of Claude's that changes no repo, or `do-epic-human` for a task of yours, as repo-rule.md says.
|
||||
Where the rule leaves that unclear, it asks you on the terminal, and you answer with the label.
|
||||
It then ranks the issues it filed that hold scores, by the `Score = ...` line under the epic's ## Scoring.
|
||||
An open issue runs as a chunk once it has such a label and no issue blocks it.
|
||||
As many run at once as the epic's description allows with a line such as `**Max parallel chunks:** 2`, one where it has none.
|
||||
A repo takes as many chunks as its `parallel-chunks`, and none while loop-claude runs chunks in it.
|
||||
A chunk whose worker ends its run while its pull request waits on its checks, an approval or a new review
|
||||
@@ -151,8 +156,12 @@ def epic_written(key: str, writes: tuple[str, str, tuple[str, ...]] | None, path
|
||||
|
||||
|
||||
def windows_opened(epic: EpicRun) -> Stop:
|
||||
"""What the do-epic the human runs does: starts each chunk that may start now, says why each other open issue waits, then puts the epic's session on the terminal until the human detaches."""
|
||||
"""What the do-epic the human runs does: plans the open issues (`planning`), starts each chunk that may start now, says why each other open issue waits, then puts the epic's session on the terminal until the human detaches."""
|
||||
issues = epic.store.read()
|
||||
if not isinstance(issues, Failure):
|
||||
issues = planning.planned(planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects), issues)
|
||||
if isinstance(issues, Limited):
|
||||
return Stop(1, f"the epic is not planned, so no chunk started: {issues.said}")
|
||||
started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, None)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, started.reason)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""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 loop's issues are scored and Jira's backlog re-ranked to match (`ranking`).
|
||||
|
||||
Only the do-epic the human runs plans. A chunk that finishes starts the next chunks from the labels and the order it finds, so no window waits on a question."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from claude_code.reply import Limited
|
||||
from do_epic import ranking, repo_pick, repos, split
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore
|
||||
from do_epic.config import DoEpicConfig
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from do_epic.scheduler import STATE
|
||||
from failure import Failure
|
||||
from loop_effects.effects import Effects, say
|
||||
from model_routing.ladder import Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from plan.todo_table import Item
|
||||
from plan_store.jira_epic import number
|
||||
from plan_store.scoring import weighing_texts
|
||||
from record_store.stores import goals_store, store as record_store
|
||||
|
||||
# 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]) -> list[EpicIssue] | Failure | Limited:
|
||||
"""The epic's issues, read again after each open child issue that no label placed was split or got its pick, and the loop's issues were re-ranked. issues are the epic's, as just read. A Failure or a Limited says why the epic isn't planned; what was labelled, filed or ranked before it stays."""
|
||||
unplaced = [issue for issue in issues if issue.parent == epic.key and not issue.done and split.SPLIT_LABEL not in issue.labels and repo_pick.recorded(issue) is None]
|
||||
if unplaced:
|
||||
stopped = placed(epic, issues, unplaced)
|
||||
if stopped is not None:
|
||||
return stopped
|
||||
read = epic.store.read()
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
issues = read
|
||||
order = ranked_keys(epic, issues)
|
||||
if isinstance(order, Failure):
|
||||
return order
|
||||
if [issue.key for issue in issues if issue.key in order] == order:
|
||||
return issues
|
||||
say(f"re-ranking the loop's issues in {epic.key}'s backlog", epic.effects, stdout=True)
|
||||
refused = ranking.reranked(epic.store, order)
|
||||
return refused or epic.store.read()
|
||||
|
||||
|
||||
def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue]) -> None | Failure | Limited:
|
||||
"""Splits each of unplaced by repo, or labels it with its pick. 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), 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, 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:
|
||||
say(f"{issue.key} is split into a sub-task for each of {', '.join(parts.repos)}", epic.effects, stdout=True)
|
||||
continue
|
||||
pick = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, 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:
|
||||
say(f"{issue.key} is labelled {repo_pick.label_of(pick)}", 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, 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."""
|
||||
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}`: ")
|
||||
except EOFError:
|
||||
return None
|
||||
pick = repo_pick.of_label(typed.strip())
|
||||
if pick is not None:
|
||||
return repo_pick.record(epic.store, issue, pick)
|
||||
say(f"`{typed.strip()}` is none of those labels", 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 loop's open child issues that hold scores, in the order ranking gives them; empty where fewer than two do, since one issue has no order. Every other issue keeps its position, as a person's does: an issue nobody scored, one labelled with two picks, and an item split by repo, which has no one repo whose goals to score it by."""
|
||||
ours = [issue for issue in issues if issue.parent == epic.key and issue.by_loop and not issue.done and split.SPLIT_LABEL not in issue.labels and not isinstance(repo_pick.recorded(issue), 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 len(keys) < len(numbers):
|
||||
return Failure(f"two of the loop's issues in the epic {epic.key} share a number in different Jira projects, so they cannot be ranked; move one of them")
|
||||
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, such as `Score = 100 * V / (2**S + 32)`")
|
||||
picks = {issue.key: repo_pick.recorded(issue) 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, blocked by each of its blockers among numbers, the issues ranked with it by key."""
|
||||
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)))
|
||||
@@ -34,6 +34,11 @@ from do_epic.test_do_epic import SETTINGS
|
||||
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
|
||||
|
||||
|
||||
def structured(output: object, key: str | None = "structured_output") -> subprocess.CompletedProcess[str]:
|
||||
"""claude's reply that holds output as its structured answer; as the whole result event where key is None."""
|
||||
return subprocess.CompletedProcess([], 0, json.dumps({"type": "result", key: output} if key else output), "")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Description:
|
||||
"""Stands in for an epic's description in Jira."""
|
||||
@@ -52,7 +57,7 @@ class DoEpicTest(unittest.TestCase):
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "config.toml").write_text(SETTINGS, encoding="utf-8")
|
||||
(folder / "repo-rule.md").write_text("A label that equals a repo's name names that repo.\n", encoding="utf-8")
|
||||
self.issues = [issue("ABC-20"), dataclasses.replace(issue("ABC-21", "do-epic-claude"), detail="Tidy the docs.", scores={"L": 3, "E": 2, "I": 3})]
|
||||
self.issues = [issue("ABC-20", "do-epic-human"), dataclasses.replace(issue("ABC-21", "do-epic-claude"), detail="Tidy the docs.", scores={"L": 3, "E": 2, "I": 3})]
|
||||
self.description: str | Failure = DESCRIPTION
|
||||
# What the forge answers each read of a chunk's gate, in turn; the last answers every later read. No worktree has the chunk's branch, so no chunk parks.
|
||||
self.forges = [Forge(worktrees="worktree /code/api\nbranch refs/heads/main\n")]
|
||||
@@ -126,12 +131,34 @@ class TheCommand(DoEpicTest):
|
||||
code, out, _ = self.run_main(["ABC-12"], fake, {"LOOP_CLAUDE_WORKER_MODEL": "m"})
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out)
|
||||
self.assertIn("ABC-20 waits: no label names its repo\n", out)
|
||||
self.assertIn("ABC-20 waits: it is a human's task\n", out)
|
||||
started = [args for args in fake.tmux_calls if args[0] == "new-session"]
|
||||
self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]])
|
||||
# The session is no checkout's, so nothing marks it as one's.
|
||||
self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"])
|
||||
|
||||
def test_plans_an_issue_no_label_places_before_it_starts_the_chunks(self) -> None:
|
||||
self.issues = [issue("ABC-20")]
|
||||
fake = FakeEffects(on_terminal=False, claude=[structured({"parts": []}), structured({"pick": "claude"})])
|
||||
code, out, err = self.run_main(["ABC-12"], fake)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertLess(out.index("ABC-20 is labelled do-epic-claude\n"), out.index("started ABC-20 in the tmux session epic-ABC-12\n"))
|
||||
|
||||
def test_starts_no_chunk_where_a_usage_limit_ends_the_planning(self) -> None:
|
||||
self.issues.append(issue("ABC-22"))
|
||||
limit = {"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"}
|
||||
fake = FakeEffects(claude=[structured(limit, None)])
|
||||
code, _, err = self.run_main(["ABC-12"], fake)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("the epic is not planned, so no chunk started: You've hit your limit\n", err)
|
||||
self.assertEqual([args for args in fake.tmux_calls if args[0] == "new-session"], [])
|
||||
|
||||
def test_stops_where_the_epic_cannot_be_planned(self) -> None:
|
||||
self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}, by_loop=True) for key in ("ABC-20", "ABC-21")]
|
||||
code, _, err = self.run_main(["ABC-12"], FakeEffects())
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("states `Score = ...` 0 times under ## Scoring", err)
|
||||
|
||||
def test_stops_on_an_epic_it_cannot_read(self) -> None:
|
||||
self.description = Failure("Jira answered 401")
|
||||
code, _, err = self.run_main(["ABC-12"], FakeEffects())
|
||||
@@ -298,6 +325,15 @@ class TheHumansRun(DoEpicTest):
|
||||
|
||||
class AChunksRun(DoEpicTest):
|
||||
|
||||
def test_a_finished_chunk_starts_the_next_without_planning_again(self) -> None:
|
||||
self.issues.append(issue("ABC-22"))
|
||||
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
|
||||
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertIn("the chunk finished; started no other\n", out)
|
||||
# The one claude call is the judge's: ABC-22, which no label places, waits for the human's do-epic.
|
||||
self.assertEqual(len(fake.made("claude")), 1)
|
||||
|
||||
def test_runs_cycles_until_the_judge_rules_it_finished_then_starts_the_next_chunk(self) -> None:
|
||||
self.issues.append(issue("ABC-22", "do-epic-claude"))
|
||||
self.description = DESCRIPTION.replace("2", "1")
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code.reply import Limited
|
||||
from do_epic import planning
|
||||
from do_epic.backend.fake import MemoryEpic
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from do_epic.config import load
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from do_epic.test_main import Description, DoEpicTest, structured as says
|
||||
from do_epic.test_scheduler import issue
|
||||
from failure import Failure
|
||||
from loop_claude.test_loop_claude import FakeEffects
|
||||
from plan.todo_table import parse_moves
|
||||
from project_config.test_project_config import configured
|
||||
|
||||
RANKED = "## Goals\n1. **Achieve:** Ship the import.\n\n## Audience\nThe client's team.\n\n## Scoring\n`Score = V`\n"
|
||||
LIMIT = {"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"}
|
||||
|
||||
|
||||
def scored(key: str, moves: str, *labels: str, blockers: tuple[str, ...] = (), by_loop: bool = True) -> EpicIssue:
|
||||
"""An open issue the loop filed, holding scores and moving the goals moves names."""
|
||||
parsed = parse_moves(key, moves)
|
||||
assert not isinstance(parsed, Failure), parsed
|
||||
return dataclasses.replace(issue(key, *labels, blockers=blockers), scores={"L": 1, "E": 1, "I": 1, "S": 1}, moves=parsed, by_loop=by_loop)
|
||||
|
||||
|
||||
class Planning(DoEpicTest):
|
||||
def plan(self, fake: FakeEffects) -> tuple[list[EpicIssue] | Failure | Limited, MemoryEpic, str]:
|
||||
"""What planning answers for self.issues, the store it changed and what it printed."""
|
||||
config = load(self.home)
|
||||
assert not isinstance(config, Failure), config
|
||||
store = MemoryEpic("ABC-12", list(self.issues))
|
||||
epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, fake.effects()) # type: ignore[arg-type]
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
||||
read = store.read()
|
||||
assert not isinstance(read, Failure)
|
||||
return planning.planned(epic, read), store, out.getvalue()
|
||||
|
||||
def labels(self, store: MemoryEpic) -> dict[str, tuple[str, ...]]:
|
||||
return {each.key: each.labels for each in store.issues}
|
||||
|
||||
def test_an_issue_a_label_places_is_planned_without_claude(self) -> None:
|
||||
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "split-by-repo"), issue("ABC-23", done=True)]
|
||||
fake = FakeEffects()
|
||||
found, _, out = self.plan(fake)
|
||||
self.assertEqual((found, out, fake.made("claude")), (self.issues, "", []))
|
||||
|
||||
def test_labels_an_unplaced_issue_with_the_repo_claude_picks_on_the_repoless_models_rung(self) -> None:
|
||||
self.issues = [issue("ABC-20")]
|
||||
fake = FakeEffects(claude=[says({"parts": [{"repo": "api", "change": "Add the endpoint."}]}), says({"pick": "repo", "repo": "api"})])
|
||||
found, store, out = self.plan(fake)
|
||||
self.assertEqual(found, [issue("ABC-20", "repo:api")])
|
||||
self.assertEqual(self.labels(store), {"ABC-20": ("repo:api",)})
|
||||
self.assertIn("ABC-20 is labelled repo:api\n", out)
|
||||
for args, _ in fake.made("claude"):
|
||||
self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5")
|
||||
self.assertIn("A label that equals a repo's name names that repo.", fake.made("claude")[1][1])
|
||||
|
||||
def test_labels_work_without_a_repo_as_claudes_or_a_humans(self) -> None:
|
||||
for pick, label in (("claude", "do-epic-claude"), ("human", "do-epic-human")):
|
||||
with self.subTest(pick=pick):
|
||||
self.issues = [issue("ABC-20")]
|
||||
_, store, _ = self.plan(FakeEffects(claude=[says({"parts": []}), says({"pick": pick})]))
|
||||
self.assertEqual(self.labels(store), {"ABC-20": (label,)})
|
||||
|
||||
def test_splits_an_issue_that_changes_several_repos_into_a_sub_task_for_each_and_picks_no_repo_for_it(self) -> None:
|
||||
self.issues = [issue("ABC-20")]
|
||||
fake = FakeEffects(claude=[says({"parts": [{"repo": "api", "change": "Add the endpoint."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo: api and web."})])
|
||||
found, store, out = self.plan(fake)
|
||||
assert not isinstance(found, Failure | Limited), found
|
||||
self.assertEqual([(each.key, each.parent, each.labels) for each in found], [("ABC-20", "ABC-12", ("split-by-repo",)), ("ABC-101", "ABC-20", ("repo:api",)), ("ABC-102", "ABC-20", ("repo:web",))])
|
||||
# A person filed ABC-20, so the team is told.
|
||||
self.assertEqual(store.comments, {"ABC-20": ["Split by repo: api and web."]})
|
||||
self.assertIn("ABC-20 is split into a sub-task for each of api, web\n", out)
|
||||
|
||||
def test_the_split_reads_the_checkout_of_each_repo_a_label_of_the_epic_names(self) -> None:
|
||||
checkout = self.home / "code" / "api"
|
||||
configured(self, checkout, home=self.home)
|
||||
self.issues = [issue("ABC-19", "repo:api", done=True), issue("ABC-20")]
|
||||
fake = FakeEffects(claude=[says({"parts": []}), says({"pick": "claude"})])
|
||||
self.plan(fake)
|
||||
args = fake.made("claude")[0][0]
|
||||
self.assertEqual(args[args.index("--add-dir") + 1], str(checkout))
|
||||
|
||||
def test_asks_the_human_for_the_label_of_an_issue_the_rule_leaves_unclear_until_one_is_typed(self) -> None:
|
||||
self.issues = [issue("ABC-20")]
|
||||
fake = FakeEffects(claude=[says({"parts": []}), says({"pick": "unclear", "question": "Is the importer in api or in web?"})], inputs=["api", " repo:web "])
|
||||
found, store, out = self.plan(fake)
|
||||
self.assertEqual(found, [issue("ABC-20", "repo:web")])
|
||||
self.assertIn("ABC-20, Do ABC-20: Is the importer in api or in web?\n", out)
|
||||
self.assertIn("`api` is none of those labels\n", out)
|
||||
self.assertEqual(fake.made("input"), ["The label that says where ABC-20 is worked, `repo:<name>`, `do-epic-claude` or `do-epic-human`: "] * 2)
|
||||
|
||||
def test_an_unclear_issue_waits_where_nobody_can_answer_and_the_next_is_planned(self) -> None:
|
||||
unclear = says({"pick": "unclear", "question": "Is the importer in api or in web?"})
|
||||
for fake in (FakeEffects(claude=[says({"parts": []}), unclear, says({"parts": []}), says({"pick": "claude"})], on_terminal=False), FakeEffects(claude=[says({"parts": []}), unclear, says({"parts": []}), says({"pick": "claude"})], inputs=[EOFError()])):
|
||||
with self.subTest(on_terminal=fake.terminal):
|
||||
self.issues = [issue("ABC-20"), issue("ABC-21")]
|
||||
_, store, out = self.plan(fake)
|
||||
self.assertEqual(self.labels(store), {"ABC-20": (), "ABC-21": ("do-epic-claude",)})
|
||||
if not fake.terminal:
|
||||
self.assertIn("ABC-20 waits for your answer: Is the importer in api or in web? Run `do-epic ABC-12` on a terminal to answer, or label the issue in Jira.\n", out)
|
||||
|
||||
def test_an_issue_claude_fails_on_is_named_and_the_next_is_planned(self) -> None:
|
||||
self.issues = [issue("ABC-20"), issue("ABC-21")]
|
||||
fake = FakeEffects(claude=[subprocess.CompletedProcess([], 1, "", ""), says({"parts": []}), says({"pick": "claude"})])
|
||||
_, store, out = self.plan(fake)
|
||||
self.assertEqual(self.labels(store), {"ABC-20": (), "ABC-21": ("do-epic-claude",)})
|
||||
self.assertIn("ABC-20 is not planned: the repo split exited 1\n", out)
|
||||
|
||||
def test_a_usage_limit_ends_the_planning(self) -> None:
|
||||
self.issues = [issue("ABC-20"), issue("ABC-21")]
|
||||
fake = FakeEffects(claude=[subprocess.CompletedProcess([], 0, json.dumps(LIMIT), "")])
|
||||
found, _, _ = self.plan(fake)
|
||||
self.assertIsInstance(found, Limited)
|
||||
self.assertEqual(len(fake.made("claude")), 1)
|
||||
|
||||
def test_re_ranks_the_loops_scored_issues_by_score_with_a_blocker_first_and_leaves_every_other_issue_in_place(self) -> None:
|
||||
self.description = RANKED
|
||||
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("ABC-21", "epic 1 by 9", "do-epic-claude", by_loop=False), scored("ABC-22", "epic 1 by 5", "do-epic-claude", blockers=("ABC-24",)), dataclasses.replace(issue("ABC-23", "do-epic-claude"), by_loop=True), scored("ABC-24", "epic 1 by 3", "do-epic-claude")]
|
||||
found, store, out = self.plan(FakeEffects())
|
||||
assert not isinstance(found, Failure | Limited), found
|
||||
# ABC-22 scores highest, and ABC-24 blocks it. ABC-21 is a person's, and nobody scored ABC-23.
|
||||
self.assertEqual([each.key for each in found], ["ABC-24", "ABC-21", "ABC-22", "ABC-23", "ABC-20"])
|
||||
self.assertIn("re-ranking the loop's issues in ABC-12's backlog\n", out)
|
||||
|
||||
def test_ranks_an_issue_in_a_repo_by_that_repos_goals_after_the_epics(self) -> None:
|
||||
checkout = self.home / "code" / "api"
|
||||
configured(self, checkout, home=self.home)
|
||||
(checkout / "README.md").write_text("## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
|
||||
self.description = RANKED
|
||||
self.issues = [scored("ABC-20", "repo 1 by 9", "repo:api"), scored("ABC-21", "epic 1 by 9", "do-epic-claude")]
|
||||
found, _, _ = self.plan(FakeEffects())
|
||||
assert not isinstance(found, Failure | Limited), found
|
||||
self.assertEqual([each.key for each in found], ["ABC-21", "ABC-20"])
|
||||
|
||||
def test_issues_already_in_their_order_are_not_ranked_again(self) -> None:
|
||||
self.description = RANKED
|
||||
self.issues = [scored("ABC-20", "epic 1 by 9", "do-epic-claude"), scored("ABC-21", "epic 1 by 2", "do-epic-claude")]
|
||||
found, _, out = self.plan(FakeEffects())
|
||||
self.assertEqual((found, out), (self.issues, ""))
|
||||
|
||||
def test_fails_where_the_epic_states_no_formula_to_rank_two_scored_issues_by(self) -> None:
|
||||
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), scored("ABC-21", "epic 1 by 9", "do-epic-claude")]
|
||||
found, store, _ = self.plan(FakeEffects())
|
||||
self.assertEqual(found, Failure("the epic ABC-12's description states `Score = ...` 0 times under ## Scoring; state the formula that ranks its issues once, on a line of its own, such as `Score = 100 * V / (2**S + 32)`"))
|
||||
self.assertEqual([each.key for each in store.issues], ["ABC-20", "ABC-21"])
|
||||
|
||||
def test_one_scored_issue_needs_no_formula(self) -> None:
|
||||
self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
|
||||
self.assertEqual(self.plan(FakeEffects())[0], self.issues)
|
||||
|
||||
def test_fails_where_the_tracker_cannot_be_read_after_a_pick(self) -> None:
|
||||
self.issues = [issue("ABC-20")]
|
||||
|
||||
def failing(_: object) -> subprocess.CompletedProcess[str]:
|
||||
self.store.fails = "Jira answered 503"
|
||||
return says({"parts": []})
|
||||
config = load(self.home)
|
||||
self.store = MemoryEpic("ABC-12", list(self.issues))
|
||||
epic = planning.Planned("ABC-12", config, self.store, EpicRecord(Description(self.description)), self.home, FakeEffects(claude=[failing, says({"pick": "claude"})]).effects()) # type: ignore[arg-type]
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(planning.planned(epic, list(self.issues)), Failure("Jira answered 503"))
|
||||
Reference in New Issue
Block a user