213 lines
11 KiB
Python
213 lines
11 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. A parked chunk (`parked`) counts toward none of them: its window only polls the forge, and `resume` takes it a slot under the same limits once its worker has something to do. 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 do_epic.parked import parked_chunks
|
|
from chunk_pr.approval import PARKS
|
|
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 or parked: 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 parked chunk waits in its window; one without a live window, as after a reboot, starts again as a stopped chunk does, whatever the limits, since it goes on parked. 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] = []
|
|
parked = parked_chunks(epic.folder)
|
|
if isinstance(parked, Failure):
|
|
return parked
|
|
try:
|
|
with starting(epic.folder):
|
|
windows = tmux.listed(session, run)
|
|
live = {window.name for window in windows if not window.dead} - {own}
|
|
running = {window.name for window in windows if not window.dead and not window.parked} - {own}
|
|
stopped = {window.name for window in windows if window.dead} - live
|
|
# The windows this call started that take a running slot.
|
|
taken = 0
|
|
for chunk in found:
|
|
if chunk.issue in running or chunk.issue == own:
|
|
continue
|
|
if chunk.issue in parked and chunk.issue in live:
|
|
waits.append(Waits(chunk.issue, parked[chunk.issue].waits))
|
|
elif own and (chunk.issue in stopped or chunk.issue in parked):
|
|
waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again"))
|
|
elif chunk.issue not in parked and len(running) + taken >= 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 if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run)
|
|
taken += chunk.issue not in parked
|
|
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. A chunk without a repo starts in the epic's folder, as a parked chunk does, which takes no room in its repo."""
|
|
session = tmux.session_name(tmux.EPIC, epic.key)
|
|
# PARKS reaches the chunk's worker, so its `chunk-pr merge` doesn't wait for an approval the parked chunk waits for.
|
|
handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"}
|
|
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)
|
|
|
|
|
|
def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None:
|
|
"""Takes a running slot for the parked chunk in window, which changes repo and whose worker has something to do again: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks."""
|
|
try:
|
|
with starting(epic.folder):
|
|
running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked]
|
|
if len(running) >= epic.cap:
|
|
return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"
|
|
located = epic.locate(repo)
|
|
if isinstance(located, Failure):
|
|
return located.reason
|
|
checkout, limit = located
|
|
with starting(project_lock(str(checkout), epic.home)):
|
|
if reason := refusal(repo, room_in(str(checkout), limit, (window.session, None), epic.home, run)):
|
|
return reason
|
|
tmux.unpark(window, str(checkout), run)
|
|
return None
|
|
except OSError as failure:
|
|
return f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}"
|
|
|
|
|
|
def status(key: str, home: pathlib.Path, issues: list[EpicIssue], run: tmux.Tmux) -> list[str] | Failure:
|
|
"""A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs, or why it waits. It starts nothing and checks no limit, so a chunk that has yet to start is told apart only from one that stopped."""
|
|
found, waits = chunks(issues)
|
|
parked = parked_chunks(home / STATE / key)
|
|
if isinstance(parked, Failure):
|
|
return parked
|
|
windows = tmux.listed(tmux.session_name(tmux.EPIC, key), run)
|
|
live = {window.name for window in windows if not window.dead}
|
|
again = f"run `do-epic {key}` to start it again"
|
|
reasons = {wait.issue: wait.reason for wait in waits}
|
|
for chunk in found:
|
|
if chunk.issue in parked:
|
|
reasons[chunk.issue] = parked[chunk.issue].waits + ("" if chunk.issue in live else f", and its window stopped; {again}")
|
|
elif chunk.issue not in live:
|
|
reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it once the epic and its repo have room"
|
|
return [f"{issue.key} waits: {reasons[issue.key]}" if issue.key in reasons else f"{issue.key} runs" for issue in issues if issue.key in reasons or issue.key in live]
|