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

163 lines
7.6 KiB
Python

"""Which of an epic's issues run as chunks now, each in its own window of the epic's tmux session (docs/decisions.md → `do-epic: drives one Jira epic …`).
Three limits hold a chunk back: the epic's cap of chunks at once, its repo's `parallel-chunks`, counted across every epic, and a loop-claude that runs chunks in its repo. do-epic checks a repo and starts a chunk in it while holding the lock loop-claude holds when it starts one (`chunk_windows.starting`), so the two never start chunks in one checkout together."""
import dataclasses
import pathlib
import typing
from do_epic.epic_record import CAP
from loop_claude.loop.chunk_windows import epic_chunks, HANDED, LOCK, project_lock, starting
from do_epic.backend.protocol import EpicIssue
from failure import Failure
from do_epic.repo_pick import HumanTask, recorded, Repo
from project_config.settings import PARALLEL_CHUNKS
from transcript_archive.project_key import project_key
from do_epic.split import SPLIT_LABEL
from agent_cycle import tmux
# Under the home folder, a folder per epic key holds the epic's LOCK. A chunk without a repo works there.
STATE = ".local/state/do-epic"
# The flag that tells the do-epic in a window its chunk, as `--chunk ABC-34 ABC-12`. Nobody types it, so no panel picked it.
CHUNK_FLAG = "--chunk"
@dataclasses.dataclass(frozen=True)
class Chunk:
"""An issue to work as one chunk, in the window named for its key."""
issue: str
# The name of the repo it changes; None for work without a repo.
repo: str | None
@dataclasses.dataclass(frozen=True)
class Waits:
"""An open issue that doesn't run now, and why."""
issue: str
reason: str
@dataclasses.dataclass(frozen=True)
class Started:
# The issues whose chunks started.
started: list[str]
waits: list[Waits]
@dataclasses.dataclass(frozen=True)
class RepoRoom:
"""What limits the chunks in one repo's checkout."""
# The repo's `parallel-chunks`.
limit: int
# How many chunks of any epic run there.
running: int
# Whether a loop-claude runs chunks there.
loop_claude: bool
@dataclasses.dataclass(frozen=True)
class Epic:
"""The epic whose chunks start."""
key: str
# How many of its chunks may run at once.
cap: int
# The checkout of the repo with this name and its `parallel-chunks`, or why the repo cannot be used.
locate: typing.Callable[[str], tuple[pathlib.Path, int] | Failure]
home: pathlib.Path
# The do-epic script each window runs.
launcher: pathlib.Path
env: typing.Mapping[str, str]
@property
def folder(self) -> pathlib.Path:
return self.home / STATE / self.key
def chunks(issues: list[EpicIssue]) -> tuple[list[Chunk], list[Waits]]:
"""The open issues to work as chunks, in the tracker's rank order, and those that wait. An item split by repo is worked through its sub-tasks, and what blocks it blocks them. A blocker outside the epic blocks until the human removes the link, since its state is unknown."""
by_key = {issue.key: issue for issue in issues}
found: list[Chunk] = []
waits: list[Waits] = []
for issue in issues:
if issue.done or SPLIT_LABEL in issue.labels:
continue
pick = recorded(issue)
parent = by_key.get(issue.parent)
blocking = [key for key in (*issue.blockers, *(parent.blockers if parent else ())) if key not in by_key or not by_key[key].done]
outside = [key for key in blocking if key not in by_key]
if isinstance(pick, Failure):
waits.append(Waits(issue.key, pick.reason))
elif pick is None:
waits.append(Waits(issue.key, "no label names its repo"))
elif isinstance(pick, HumanTask):
waits.append(Waits(issue.key, "it is a human's task"))
elif blocking:
waits.append(Waits(issue.key, f"{' and '.join(blocking)} block{'s' if len(blocking) == 1 else ''} it" + (f"; do-epic cannot see {' and '.join(outside)}, outside the epic, finish: remove such a link in Jira once its issue is done" if outside else "")))
else:
found.append(Chunk(issue.key, pick.name if isinstance(pick, Repo) else None))
return found, waits
def refusal(repo: str, room: RepoRoom) -> str | None:
"""Why the repo takes no further chunk; None where it takes one."""
if room.loop_claude:
return f"loop-claude runs chunks in {repo}"
if room.running >= room.limit:
return f"{repo} runs as many chunks as its `{PARALLEL_CHUNKS}` allows: {room.limit}"
return None
def start_chunks(epic: Epic, issues: list[EpicIssue], own: str | None, run: tmux.Tmux) -> Started | Failure:
"""Starts a do-epic in a new window for each of the epic's chunks that may start now. own is the issue of the chunk that asks, which has finished: it counts as running nowhere, and no stopped chunk starts again. Where own is None, the human's `do-epic <EPIC-KEY>` asks, and each stopped chunk starts again. A Failure says why a window could not start; those before it run."""
session = tmux.session_name(tmux.EPIC, epic.key)
found, waits = chunks(issues)
started: list[str] = []
try:
with starting(epic.folder):
windows = tmux.listed(session, run)
running = {window.name for window in windows if not window.dead} - {own}
stopped = {window.name for window in windows if window.dead} - running
for chunk in found:
if chunk.issue in running or chunk.issue == own:
continue
if own and chunk.issue in stopped:
waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again"))
elif len(running) + len(started) >= epic.cap:
waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"))
else:
now = start_chunk(epic, chunk, own, windows, run)
if isinstance(now, Failure):
return now
if isinstance(now, str):
waits.append(Waits(chunk.issue, now))
else:
windows = now
started.append(chunk.issue)
except OSError as failure:
return Failure(f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}")
return Started(started, sorted(waits, key=lambda wait: [issue.key for issue in issues].index(wait.issue)))
def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure:
"""Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none. It holds the repo's lock from the check to the start. Raises OSError where that lock cannot be taken."""
session = tmux.session_name(tmux.EPIC, epic.key)
handed = {name: value for name, value in epic.env.items() if name.startswith(HANDED)}
command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key]
if chunk.repo is None:
return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), handed, command, windows, False, run)
located = epic.locate(chunk.repo)
if isinstance(located, Failure):
return located.reason
checkout, limit = located
with starting(project_lock(str(checkout), epic.home)):
if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)):
return reason
return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run)
def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pathlib.Path, run: tmux.Tmux) -> RepoRoom:
"""The room in a repo's checkout under its limit. leaving is the session and name of a window whose chunk finished, which no longer counts."""
theirs = [placed for placed in epic_chunks(checkout, run) if (placed.session, placed.window.name) != leaving]
loop_session = tmux.session_name(tmux.LOOP, project_key(checkout, home))
loops = any(not window.dead for window in tmux.listed(loop_session, run)) and tmux.owner(loop_session, run) == checkout
return RepoRoom(limit, len(theirs), loops)