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

382 lines
21 KiB
Python

"""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.
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
import pathlib
import typing
from loop_claude.loop.chunk_start import archived_route, routed
from do_epic import chunk_prompt, gates, parked, scheduler
from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo
from loop_claude.loop.close import closed_cycle
from agent_cycle.run import Cycle, run_cycle
from do_epic.config import DoEpicConfig, load
from loop_effects.effects import Effects, say
from project_config.settings import Epic
from record_store.jira_description import EpicDescription
from do_epic.backend.protocol import EpicIssue, EpicStore
from do_epic.epic_record import EpicRecord
from failure import Failure
from agent_cycle.verdicts import Finished, TakenIn
from loop_claude.project.model_choice import get_or_ask_models, Models
from plan_store.jira_epic import ISSUE_KEY
from do_epic.backend.jira import JiraEpic
from agent_cycle.routing import judge_rung
from do_epic.repos import locate
from loop_claude.loop.this_loop import Loop
from loop_claude.loop.reload import LoopRun
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from forge.commands import Run, runner
from claude_code.session import session_named
from loop_claude.loop.main import setup_version
from agent_cycle.stop import Stop
from agent_cycle.direct_message import tell
from agent_cycle import tmux
HELP = f"""usage: do-epic <EPIC-KEY> [--status]
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.
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 pull request waits on its checks or on an approval is parked: it frees its place for the next
chunk, its window's name says what it awaits, and it goes on once the checks pass, the approval comes or a
reviewer comments. A parked chunk survives a reboot: run do-epic <EPIC-KEY> again to go on polling.
--status starts no chunk: it prints each open issue with whether its chunk runs, or why it waits.
The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml."""
# Under the home folder, where a chunk's cycles are archived, a folder per epic. It is not loop-claude's archive, since that archive's readers, such as judge-replay and the routing figures, read loop-claude's prompts.
ARCHIVE = ".claude/do-epic-transcripts"
# The flag that prints what each open issue does. lilleman named it when planning release 0.12.0 (the decision's "Long gates").
STATUS_FLAG = "--status"
# How often a parked chunk reads its pull request's gate: a reviewer answers in hours, and each read is three or four calls to the forge.
POLL_SECONDS = 60
# The store of an epic's issues and its record, for the epic with this key.
Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]]
def jira_backend(config: DoEpicConfig, key: str) -> tuple[EpicStore, EpicRecord]:
epic = Epic(config.jira_url, key)
return JiraEpic(epic, config.env_file), EpicRecord(EpicDescription(epic, config.env_file))
@dataclasses.dataclass(frozen=True)
class EpicRun:
"""What stays the same through one run of do-epic on an epic."""
key: str
config: DoEpicConfig
store: EpicStore
record: EpicRecord
paths: Paths
env: typing.Mapping[str, str]
launcher: pathlib.Path
effects: Effects
# The runner of git's and the forge's commands in a folder.
forge_at: typing.Callable[[str], Run] = runner
@property
def session(self) -> str:
return tmux.session_name(tmux.EPIC, self.key)
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend = jira_backend, forge_at: typing.Callable[[str], Run] = runner) -> int:
try:
stop = run(argv, env, paths, launcher, effects, backend, forge_at)
except KeyboardInterrupt:
stop = Stop(130, "")
except Exception as crash:
tell(f"do-epic {' '.join(argv)} crashed: {crash!r}", effects)
raise
if stop.reason:
say(stop.reason, effects, stdout=not stop.code)
# A chunk's stop is DMed, as loop-claude's is, so a chunk left overnight never ends unseen.
if stop.reason and argv[:1] == [scheduler.CHUNK_FLAG]:
tell(f"do-epic {' '.join(argv)} stopped: {stop.reason}", effects)
return stop.code
def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend, forge_at: typing.Callable[[str], Run]) -> Stop:
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == scheduler.CHUNK_FLAG else (None, argv)
status = chunk is None and words[1:] == [STATUS_FLAG]
words = words[:1] if status else words
if len(words) != 1 or not ISSUE_KEY.fullmatch(words[0]) or (chunk is not None and not ISSUE_KEY.fullmatch(chunk)):
return Stop(0 if words in (["-h"], ["--help"]) else 1, HELP)
# Before anything starts: a clone, a claude session or a tmux window.
if reason := tmux.unusable(effects.tmux, chunk_prompt.DRIVER):
return Stop(1, reason)
config = load(paths.home)
if isinstance(config, Failure):
return Stop(1, config.reason)
store, record = backend(config, words[0])
epic = EpicRun(words[0], config, store, record, paths, env, launcher, effects, forge_at)
if status:
return status_printed(epic)
return windows_opened(epic) if chunk is None else chunk_run(chunk, epic)
def status_printed(epic: EpicRun) -> Stop:
"""What `do-epic <EPIC-KEY> --status` does: prints a line per open issue, and starts nothing."""
issues = epic.store.read()
lines = issues if isinstance(issues, Failure) else scheduler.status(epic.key, epic.paths.home, issues, epic.effects.tmux)
return Stop(1, lines.reason) if isinstance(lines, Failure) else Stop(0, "\n".join(lines) or f"the epic {epic.key} has no open issue")
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."""
started = chunks_started(epic, None)
if isinstance(started, Failure):
return Stop(1, started.reason)
say(f"started {', '.join(started.started)} in the tmux session {epic.session}" if started.started else "started no chunk", epic.effects, stdout=True)
for wait in started.waits:
say(f"{wait.issue} waits: {wait.reason}", epic.effects, stdout=True)
if not tmux.listed(epic.session, epic.effects.tmux):
return Stop(0, "")
if not epic.effects.on_terminal():
say(f"not on a terminal; see the chunks with `tmux attach -t ={epic.session}`", epic.effects, stdout=True)
return Stop(0, "")
shown = tmux.show(epic.session, "TMUX" in epic.env)
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if epic.effects.tmux_on_terminal(shown) else Stop(0, "")
def chunks_started(epic: EpicRun, own: str | None) -> scheduler.Started | Failure:
"""scheduler.start_chunks on the epic's issues and cap, read afresh; own is the issue of the chunk that asks."""
issues = epic.store.read()
if isinstance(issues, Failure):
return issues
scheduled = scheduled_epic(epic)
return scheduled if isinstance(scheduled, Failure) else scheduler.start_chunks(scheduled, issues, own, epic.effects.tmux)
def scheduled_epic(epic: EpicRun) -> scheduler.Epic | Failure:
"""The epic as scheduler limits its chunks: with its cap, read afresh, and each repo's checkout."""
cap = epic.record.parallel_chunks()
if isinstance(cap, Failure):
return cap
# The checkouts located so far, from whose remotes repos.locate tells where to clone a repo that is missing.
seen: list[pathlib.Path] = []
def located(name: str) -> tuple[pathlib.Path, int] | Failure:
found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git)
if isinstance(found, Failure):
return found
seen.append(found.checkout)
return real(found.checkout), found.config.parallel_chunks
return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env)
@dataclasses.dataclass(frozen=True)
class RoutingIssue:
"""An issue as what routes its chunk (agent_cycle.routing.Scored)."""
issue: EpicIssue
@property
def id(self) -> int:
"""The number in the issue's key. A Route keeps a number, and one chunk's archive holds one issue, so the number tells the issue without its project's letters."""
return int(self.issue.key.rpartition("-")[2])
@property
def likelihood(self) -> int:
return self.issue.scores["L"]
@property
def escape_and_impact(self) -> int:
return self.issue.scores.get("E", 0) + self.issue.scores.get("I", 0)
def real(checkout: pathlib.Path) -> pathlib.Path:
"""The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other."""
return checkout.resolve()
def chunk_run(key: str, epic: EpicRun) -> Stop:
"""Runs the cycles of the chunk of the issue called key until one stops the loop, or the judge rules the chunk finished. A chunk in a repo parks after each cycle that leaves its pull request waiting on a gate, and before its first where it was parked when its window last ended, as at a reboot."""
pane = epic.env.get("TMUX_PANE")
if not pane:
return Stop(1, f"{scheduler.CHUNK_FLAG} is how do-epic starts itself in a tmux window; run do-epic <EPIC-KEY>")
issue = issue_read(key, epic)
if isinstance(issue, Stop):
return issue
place = chunk_root(issue, epic)
if isinstance(place, Stop):
return place
root, in_repo = place
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects)
loop_run = LoopRun(0, root, "", "", chunk=key)
# What a chunk that was parked is told as it resumes; empty for a chunk that wasn't.
news = parked_through(issue, loop, epic, starts=True) if in_repo else ""
while True:
if isinstance(news, Stop):
return news
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
cycle = next_cycle(loop_run, loop, in_repo, epic, news)
if isinstance(cycle, Stop):
return cycle
loop_run = dataclasses.replace(loop_run, task=cycle.task)
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, chunk_prompt.DRIVER, loop)
if isinstance(closed, Stop):
return closed
loop_run = closed
news = parked_through(issue, loop, epic, starts=False) if in_repo else ""
# A chunk that was parked has work again, whatever the judge ruled before its pull request passed the gate.
if isinstance(concluded.verdict, Finished) and news == "":
return handed_on(key, epic)
def parked_through(issue: EpicIssue, loop: Loop, epic: EpicRun, starts: bool) -> str | Stop:
"""Keeps the chunk of issue parked for as long as its pull request waits on a gate, and returns once its worker has something to do: what to tell that worker, or empty where the chunk was never parked. starts says the window just started, where the chunk is parked only if its file says so: nothing is read from the forge for a chunk that starts afresh.
A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` takes it a slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again.
"""
key, folder = issue.key, epic.paths.home / scheduler.STATE / epic.key
recorded_as = parked.parked_chunks(folder)
if isinstance(recorded_as, Failure):
return Stop(1, recorded_as.reason)
if starts and key not in recorded_as:
return ""
# What the chunk is parked on; None while it isn't parked.
on = recorded_as[key].on if key in recorded_as else None
# What the window's name says the chunk awaits, and the last reason said for staying parked.
shown = said = None
while True:
now = gates.gate(key, loop.root, epic.forge_at)
if on is None and not isinstance(now, gates.Gate):
if isinstance(now, Failure):
say(f"cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: {now.reason}", epic.effects, stdout=True)
return ""
stays = None
if isinstance(now, gates.Gate) and now.on != on:
failed = parked.park(folder, parked.Parked(key, now.worktree, now.pull, str(loop.session.id), now.on))
if failed is not None:
return Stop(1, failed.reason)
say(f"parked: pull request #{now.pull} awaits {now.on}", epic.effects, stdout=True)
elif isinstance(now, Failure):
stays = f"cannot read the gate: {now.reason}"
elif isinstance(now, gates.Open):
full = resumed(issue, loop, epic)
if full is None:
failed = parked.unpark(folder, key)
return Stop(1, failed.reason) if failed is not None else f"{DRIVER_PARKED} its pull request awaited {on}. It resumes now: {now.news}."
stays = f"{now.news}, but the chunk stays parked: {full}"
awaits = SLOT if isinstance(now, gates.Open) else now.on if isinstance(now, gates.Gate) else shown or on
if awaits != shown:
tmux.park(loop.window, str(awaits), epic.effects.tmux)
shown = awaits
if on is None:
# Once the window shows as parked, so the chunks that start count it as running nowhere.
started = chunks_started(epic, key)
say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
on = now.on if isinstance(now, gates.Gate) else on
if stays is not None and stays != said:
say(f"{stays}; trying again every {POLL_SECONDS} seconds", epic.effects, stdout=True)
said = stays
epic.effects.sleep(POLL_SECONDS)
# How the news for a chunk that was parked opens.
DRIVER_PARKED = f"{chunk_prompt.DRIVER} parked the chunk while"
# What a parked chunk awaits, in its window's name, once its worker has something to do but no running slot is free.
SLOT = "a slot"
def resumed(issue: EpicIssue, loop: Loop, epic: EpicRun) -> str | None:
"""scheduler.resume for the parked chunk of issue, on the epic's cap and repos read afresh: None once it holds a running slot, else why it stays parked."""
pick = recorded(issue)
scheduled = scheduled_epic(epic)
if isinstance(scheduled, Failure):
return scheduled.reason
return scheduler.resume(scheduled, pick.name, loop.window, epic.effects.tmux) if isinstance(pick, Repo) else f"no label of {issue.key} names its repo any longer"
def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop:
"""The epic's issue called key, read afresh."""
issues = epic.store.read()
if isinstance(issues, Failure):
return Stop(1, issues.reason)
found = [issue for issue in issues if issue.key == key]
return found[0] if found else Stop(1, f"{key} is no issue of the epic {epic.key}")
def chunk_root(issue: EpicIssue, epic: EpicRun) -> tuple[str, bool] | Stop:
"""The folder the issue's chunk works in, and whether it is a repo's checkout: the epic's folder holds work without a repo. The chunk keeps both to its end, whatever the issue's labels become. The stop where the labels make the issue no chunk."""
pick = recorded(issue)
if isinstance(pick, Failure):
return Stop(1, pick.reason)
if isinstance(pick, ClaudeWork):
folder = epic.paths.home / scheduler.STATE / epic.key
folder.mkdir(parents=True, exist_ok=True)
return str(folder), False
if not isinstance(pick, Repo):
return Stop(1, f"{issue.key} is no chunk: {'it is a human\'s task' if isinstance(pick, HumanTask) else 'no label names its repo'}")
found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git)
return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), True)
def handed_on(key: str, epic: EpicRun) -> Stop:
"""The stop of a do-epic whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits."""
started = chunks_started(epic, key)
if isinstance(started, Failure):
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
say(f"the chunk finished; started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True)
return Stop(0, "")
def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | Stop:
"""The cycle loop_run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder."""
issue = issue_read(loop.window.name, epic)
if isinstance(issue, Stop):
return issue
premises = premises_read(loop.root if in_repo else None, epic)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
# The epic's records join the repo's with todo.md item 413; until then a chunk without a repo has none.
records = read_records(loop.root, epic.paths.home, epic.paths.claude_dir) if in_repo else ""
if isinstance(records, Failure):
return Stop(1, records.reason)
models = get_or_ask_models(project_key(loop.root, epic.paths.home), epic.paths, epic.env, chunk_prompt.DRIVER, epic.effects) if in_repo else repoless_models(epic)
if isinstance(models, Stop):
return models
ladder_file = project_ladder_file(loop.root, epic.paths.home) if in_repo else SHIPPED
if isinstance(ladder_file, Failure):
return Stop(1, ladder_file.reason)
ladder = read_ladder(ladder_file)
if isinstance(ladder, Failure):
return Stop(1, ladder.reason)
archive_folder = epic.paths.home / ARCHIVE / epic.key
project = ladder.project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: RoutingIssue(issue) if "L" in issue.scores else None)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", epic.effects, stdout=True)
return Cycle(config=setup_version(epic.paths.claude_dir, epic.effects.git), effects=epic.effects, facts="", judge=judge_rung(ladder, models.judge), premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=chunk_prompt.task(issue, epic.key, loop.root if in_repo else None), prompts=chunk_prompt.unparked(news) if news else chunk_prompt.WORKER, taken_in=lambda entries: TakenIn(), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
def repoless_models(epic: EpicRun) -> Models:
"""The models of a chunk without a repo: `repoless-model`, unless the environment names another for the run, as it may for loop-claude."""
return Models(epic.env.get("LOOP_CLAUDE_JUDGE_MODEL") or epic.config.repoless_model, epic.env.get("LOOP_CLAUDE_WORKER_MODEL") or epic.config.repoless_model)
def premises_read(root: str | None, epic: EpicRun) -> str | Failure:
"""The epic's Goals and Audience, from its description, then those of the repo checked out at root, where the chunk has one. A Failure where the epic lacks either: no chunk runs without premises."""
bodies: list[str] = []
for name in ("Goals", "Audience"):
body = epic.record.section(name)
if isinstance(body, Failure):
return Failure(f"the epic {epic.key}'s description: {body.reason} - no premises.")
if not body.strip():
return Failure(f"the epic {epic.key}'s description has no text under a `## {name}` heading - no premises.")
bodies.append(body)
theirs = read_premises(root, epic.paths.home) if root else ""
if isinstance(theirs, Failure):
return theirs
return f"the epic {epic.key}'s description:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}" + (f"\n\nThe repo's goals, which rank after the epic's and after code health, are from {theirs}" if theirs else "")