Run do-epic <EPIC-KEY>: a tmux window per chunk, under the epic's cap and each repo's parallel-chunks, never beside loop-claude
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
"""What a do-epic cycle's worker is told: its task, from the issue, and its first prompt. The resumed prompt and the rung sentences are the ones loop-claude's cycles use, naming do-epic."""
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from loop_claude.cycle import prompts
|
||||
from model_routing.ladder import ProjectRung
|
||||
from model_routing.route import Route
|
||||
|
||||
# The entry point's name as the worker, the judge and the human read it.
|
||||
DRIVER = "do-epic"
|
||||
|
||||
|
||||
def task(issue: EpicIssue, epic: str, checkout: str | None) -> str:
|
||||
"""The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None."""
|
||||
where = f"in the checkout {checkout}, on the branch {issue.key}" if checkout else "which changes no repo: work in the folder you start in"
|
||||
return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "")
|
||||
|
||||
|
||||
def fresh(task: str, premises: str, route: Route, project: ProjectRung | None, facts: str) -> str:
|
||||
"""A chunk's first prompt. facts is empty: do-epic runs no preflight."""
|
||||
routed = f"{DRIVER} runs you on {route.rung}, routed by the issue's L of {route.likelihood}. Where a sentence below names item {route.item}, it means the issue." if route.item else ""
|
||||
opening = " ".join(filter(None, [routed, *prompts.rung_sentences(DRIVER, route, project)]))
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE}\n\n{opening and f'{opening}{chr(10)}{chr(10)}'}The issue sets the chunk's scope. The goals below choose between ways to deliver that scope, and never widen it: the epic's first, then code health (~/.claude/CLAUDE.md → \"Shared goal\"), then the repo's.\n\nFrom {premises}"
|
||||
|
||||
|
||||
# The worker names no plan items: the chunk's one item is its issue.
|
||||
WORKER = prompts.worker_prompts(DRIVER, fresh, "")
|
||||
@@ -1,6 +1,6 @@
|
||||
"""A Jira epic's description as the record of do-epic, the tool that will drive one epic.
|
||||
|
||||
The description holds a language line and the sections Goals, Audience, Scoring (the formula and the bar) and Decisions. They are read and written one at a time through `EpicDescription`, and a write leaves every other line of the markdown as it was. Goals and Audience change only where the human approved in an interrupt, which `write_section` takes as `approved`; `EpicDescription` refuses the change otherwise."""
|
||||
The description holds a language line, a line that caps the chunks running at once, and the sections Goals, Audience, Scoring (the formula and the bar) and Decisions. They are read and written one at a time through `EpicDescription`, and a write leaves every other line of the markdown as it was. Goals and Audience change only where the human approved in an interrupt, which `write_section` takes as `approved`; `EpicDescription` refuses the change otherwise."""
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
@@ -13,6 +13,9 @@ from project_config.settings import language_fault
|
||||
|
||||
SECTIONS = ("Goals", "Audience", "Scoring", "Decisions")
|
||||
LANGUAGE_LINE = re.compile(r"^\*\*Language:\*\* (.*?)\s*$")
|
||||
# The line that caps how many of the epic's chunks run at once. Three readers, seated as the human who writes an epic's description, picked this spelling from four candidates, 2-1 over `**Parallel chunks:**`, which reads as a count of what runs now.
|
||||
CAP = "**Max parallel chunks:**"
|
||||
CAP_LINE = re.compile(rf"^{re.escape(CAP)}(.*?)\s*$")
|
||||
|
||||
|
||||
def read_section(text: str, name: str) -> str | Failure:
|
||||
@@ -59,6 +62,17 @@ def language_in(text: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def parallel_chunks_in(text: str) -> int | Failure:
|
||||
"""How many of the epic's chunks may run at once, as the description's CAP line says; 1 where it has none, as a project's `parallel-chunks` is where its config leaves it out."""
|
||||
for line, fenced in fenced_lines(text):
|
||||
if not fenced and (found := CAP_LINE.match(line)):
|
||||
value = found.group(1).strip()
|
||||
if re.fullmatch(r"[1-9][0-9]*", value):
|
||||
return int(value)
|
||||
return Failure(f"the epic's description caps its chunks with `{CAP} {value}`, which is not a whole number of 1 or more, such as `{CAP} 2`")
|
||||
return 1
|
||||
|
||||
|
||||
def with_language(text: str, language: str) -> str | Failure:
|
||||
"""text with its language line naming language, put first where there is none."""
|
||||
if fault := language_fault(language):
|
||||
@@ -84,6 +98,10 @@ class EpicRecord:
|
||||
text = self.description.read()
|
||||
return text if isinstance(text, Failure) else language_in(text)
|
||||
|
||||
def parallel_chunks(self) -> int | Failure:
|
||||
text = self.description.read()
|
||||
return text if isinstance(text, Failure) else parallel_chunks_in(text)
|
||||
|
||||
def write_section(self, name: str, body: str, approved: bool = False) -> Held | Failure:
|
||||
"""Writes body as the ## name section. approved says the human approved the change in an interrupt, which Goals and Audience need."""
|
||||
return self.written(lambda text: with_section(text, name, body), frozenset({name}) if approved else frozenset())
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""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, which loop-claude's cycles share (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from agent_cycle import tmux
|
||||
from agent_cycle.direct_message import tell
|
||||
from agent_cycle.routing import judge_rung
|
||||
from agent_cycle.run import Cycle, run_cycle
|
||||
from agent_cycle.stop import Stop
|
||||
from agent_cycle.verdicts import Finished, TakenIn
|
||||
from claude_code.session import session_named
|
||||
from do_epic import chunk_prompt, scheduler
|
||||
from do_epic.backend.jira import JiraEpic
|
||||
from do_epic.backend.protocol import EpicIssue, EpicStore
|
||||
from do_epic.config import DoEpicConfig, load
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from do_epic.repo_pick import recorded, Repo
|
||||
from do_epic.repos import locate
|
||||
from failure import Failure
|
||||
from loop_claude.loop.chunk_start import archived_route, routed
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from loop_claude.loop.main import setup_version
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.project.model_choice import get_or_ask_models, Models
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from loop_effects.effects import Effects, say
|
||||
from loop_state.paths import Paths
|
||||
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
|
||||
from plan_store.jira_epic import ISSUE_KEY
|
||||
from project_config.settings import Epic
|
||||
from record_store.jira_description import EpicDescription
|
||||
from transcript_archive.project_key import project_key
|
||||
|
||||
HELP = f"""usage: do-epic <EPIC-KEY>
|
||||
|
||||
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 is a chunk once a label names its repo, or names it work without a repo, and nothing 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.
|
||||
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. Apart from loop-claude's archive, whose readers, such as judge-replay and the routing figures, read loop-claude's prompts.
|
||||
ARCHIVE = ".claude/do-epic-transcripts"
|
||||
|
||||
# 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
|
||||
|
||||
@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) -> int:
|
||||
try:
|
||||
stop = run(argv, env, paths, launcher, effects, backend)
|
||||
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) -> Stop:
|
||||
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == scheduler.CHUNK_FLAG else (None, argv)
|
||||
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)
|
||||
return windows_opened(epic) if chunk is None else chunk_run(chunk, epic)
|
||||
|
||||
|
||||
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 f"started no chunk in the tmux session {epic.session}", 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
|
||||
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 found.checkout, found.config.parallel_chunks
|
||||
|
||||
return scheduler.start_chunks(scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env), issues, own, epic.effects.tmux)
|
||||
|
||||
|
||||
@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 project's letters aren't needed to tell it."""
|
||||
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 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."""
|
||||
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
|
||||
root = chunk_root(issue, epic)
|
||||
if isinstance(root, Stop):
|
||||
return root
|
||||
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)
|
||||
while True:
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
cycle = next_cycle(loop_run, loop, epic)
|
||||
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
|
||||
if isinstance(concluded.verdict, Finished):
|
||||
return handed_on(key, epic)
|
||||
|
||||
|
||||
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) -> str | Stop:
|
||||
"""The folder the issue's chunk works in: its repo's checkout, or the epic's folder for work without a repo."""
|
||||
pick = recorded(issue)
|
||||
if isinstance(pick, Failure):
|
||||
return Stop(1, pick.reason)
|
||||
if not isinstance(pick, Repo):
|
||||
folder = epic.paths.home / scheduler.STATE / epic.key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
return str(folder)
|
||||
found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git)
|
||||
return Stop(1, found.reason) if isinstance(found, Failure) else str(found.checkout)
|
||||
|
||||
|
||||
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, epic: EpicRun) -> 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. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting's model, `repoless-model`, and the shipped ladder."""
|
||||
issue = issue_read(loop.window.name, epic)
|
||||
if isinstance(issue, Stop):
|
||||
return issue
|
||||
in_repo = isinstance(recorded(issue), Repo)
|
||||
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.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."""
|
||||
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.")
|
||||
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 "")
|
||||
@@ -0,0 +1,161 @@
|
||||
"""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 agent_cycle import tmux
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from do_epic.epic_record import CAP
|
||||
from do_epic.repo_pick import HumanTask, recorded, Repo
|
||||
from do_epic.split import SPLIT_LABEL
|
||||
from failure import Failure
|
||||
from loop_claude.loop.chunk_windows import epic_chunks, HANDED, LOCK, project_lock, starting
|
||||
from project_config.settings import PARALLEL_CHUNKS
|
||||
from transcript_archive.project_key import project_key
|
||||
|
||||
# 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, 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]
|
||||
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"))
|
||||
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. None is the human's `do-epic <EPIC-KEY>`, which restarts each stopped chunk. 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)
|
||||
@@ -0,0 +1,165 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from agent_cycle import escalation_mark, judge, tmux
|
||||
from do_epic import chunk_prompt, main
|
||||
from do_epic.backend.fake import MemoryEpic
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from do_epic.test_do_epic import SETTINGS
|
||||
from do_epic.test_scheduler import issue
|
||||
from failure import Failure
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.test_loop_claude import FakeEffects
|
||||
from loop_state.paths import paths_from
|
||||
from model_routing.ladder import Rung
|
||||
from model_routing.route import Route
|
||||
|
||||
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Description:
|
||||
"""Stands in for an epic's description in Jira."""
|
||||
text: str | Failure
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
return self.text
|
||||
|
||||
|
||||
class DoEpicTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
self.home = pathlib.Path(made.name).resolve()
|
||||
folder = self.home / ".claude-projects" / "do-epic"
|
||||
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.description: str | Failure = DESCRIPTION
|
||||
|
||||
def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]:
|
||||
return MemoryEpic(key, list(self.issues)), EpicRecord(Description(self.description)) # type: ignore[arg-type]
|
||||
|
||||
def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, env or {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
|
||||
class TheCommand(DoEpicTest):
|
||||
def test_prints_the_help_for_anything_but_one_epic_key(self) -> None:
|
||||
for argv, code in ((["--help"], 0), (["-h"], 0), ([], 1), (["abc"], 1), (["ABC-12", "ABC-13"], 1), (["--chunk", "x", "ABC-12"], 1)):
|
||||
with self.subTest(argv=argv):
|
||||
ran_code, out, err = self.run_main(argv, FakeEffects())
|
||||
self.assertEqual((ran_code, (err if code else out).split(" ", 1)[1]), (code, main.HELP + "\n"))
|
||||
|
||||
def test_refuses_a_tmux_too_old_naming_do_epic(self) -> None:
|
||||
code, _, err = self.run_main(["ABC-12"], FakeEffects(tmux_version="tmux 3.1"))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("do-epic runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1", err)
|
||||
|
||||
def test_starts_the_chunks_and_says_why_each_other_issue_waits(self) -> None:
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
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)
|
||||
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", "-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_stops_on_an_epic_it_cannot_read(self) -> None:
|
||||
self.description = Failure("Jira answered 401")
|
||||
code, _, err = self.run_main(["ABC-12"], FakeEffects())
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("Jira answered 401\n", err)
|
||||
|
||||
def test_a_chunk_outside_a_tmux_window_says_how_to_run_do_epic(self) -> None:
|
||||
fake = FakeEffects()
|
||||
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("--chunk is how do-epic starts itself in a tmux window; run do-epic <EPIC-KEY>\n", err)
|
||||
self.assertEqual(fake.dms, ["do-epic --chunk ABC-21 ABC-12 stopped: --chunk is how do-epic starts itself in a tmux window; run do-epic <EPIC-KEY>"])
|
||||
|
||||
def test_a_chunk_of_an_issue_the_epic_lacks_stops(self) -> None:
|
||||
code, _, err = self.run_main(["--chunk", "ABC-99", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("ABC-99 is no issue of the epic ABC-12\n", err)
|
||||
|
||||
|
||||
class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
def cycle(self, env: dict[str, str] | None = None) -> main.Cycle:
|
||||
fake = FakeEffects(git=[Failure("no git"), Failure("no git")])
|
||||
paths = paths_from(self.home)
|
||||
config = main.load(self.home)
|
||||
assert not isinstance(config, Failure)
|
||||
store, record = self.backend(config, "ABC-12")
|
||||
epic = main.EpicRun("ABC-12", config, store, record, paths, env or {}, pathlib.Path("/b/do-epic"), fake.effects())
|
||||
root = main.chunk_root(self.issues[1], epic)
|
||||
assert isinstance(root, str)
|
||||
loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects())
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
found = main.next_cycle(LoopRun(1, root, "", "", chunk="ABC-21"), loop, epic)
|
||||
assert isinstance(found, main.Cycle), found
|
||||
return found
|
||||
|
||||
def test_routes_on_the_repoless_model_by_the_issues_scores(self) -> None:
|
||||
cycle = self.cycle()
|
||||
assert cycle.project is not None
|
||||
self.assertEqual(cycle.project.rung.model, "claude-opus-5-5")
|
||||
self.assertEqual(cycle.route, Route(cycle.project.worker_rung(3), 21, 3, 5))
|
||||
self.assertEqual(cycle.judge.model, "claude-opus-5-5")
|
||||
self.assertEqual(self.cycle({"LOOP_CLAUDE_WORKER_MODEL": "off-the-ladder"}).route, Route(Rung("off-the-ladder")))
|
||||
|
||||
def test_works_in_the_epics_folder_and_archives_apart_from_loop_claude(self) -> None:
|
||||
cycle = self.cycle()
|
||||
self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/do-epic/ABC-12"), self.home / ".claude/do-epic-transcripts/ABC-12", ""))
|
||||
|
||||
def test_the_premises_are_the_epics_goals_and_audience(self) -> None:
|
||||
self.assertEqual(self.cycle().premises, "the epic ABC-12's description:\n## Goals\nShip the import.\n\n## Audience\nThe client's team.")
|
||||
|
||||
def test_the_task_is_the_issue(self) -> None:
|
||||
self.assertEqual(self.cycle().task, "Work the Jira issue ABC-21 of the epic ABC-12 as one chunk, which changes no repo: work in the folder you start in. Its summary: Do ABC-21\n\nIts description:\n\nTidy the docs.")
|
||||
|
||||
def test_an_issue_without_scores_runs_on_the_projects_rung(self) -> None:
|
||||
self.issues[1] = dataclasses.replace(self.issues[1], scores={})
|
||||
cycle = self.cycle()
|
||||
assert cycle.project is not None
|
||||
self.assertEqual(cycle.route, Route(cycle.project.rung))
|
||||
|
||||
|
||||
class WhatAWorkerJudgeAndHumanRead(DoEpicTest):
|
||||
def test_every_prompt_names_do_epic_and_never_loop_claude(self) -> None:
|
||||
cycle = ACycleOfAChunkWithoutARepo.cycle(self) # type: ignore[arg-type]
|
||||
prompts = cycle.prompts
|
||||
texts = [
|
||||
prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, ""),
|
||||
prompts.resumed("the work remaining", cycle.route, cycle.project),
|
||||
prompts.typed("Which one?", "The first.", cycle.route, cycle.project, True),
|
||||
judge.judge_rules(prompts.answer_destinations, prompts.driver),
|
||||
str(judge.judge_schema(prompts.driver)),
|
||||
]
|
||||
for text in texts:
|
||||
self.assertNotIn("loop-claude", text)
|
||||
self.assertIn(f"do-epic runs you on {cycle.route.rung}, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue.", texts[0])
|
||||
self.assertNotIn("Chunk items:", texts[1])
|
||||
# The worker's prompt and the judge's rules word the request for a higher rung alike, from one place.
|
||||
for text in (texts[0], texts[3]):
|
||||
self.assertIn(escalation_mark.asks_higher_rung(chunk_prompt.DRIVER), text)
|
||||
self.assertEqual(escalation_mark.asks_higher_rung(chunk_prompt.DRIVER), "asking do-epic for a higher rung")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from agent_cycle import tmux
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from do_epic.epic_record import parallel_chunks_in
|
||||
from do_epic.scheduler import Chunk, chunks, CHUNK_FLAG, Epic, RepoRoom, refusal, start_chunks, Started, Waits
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def issue(key: str, *labels: str, done: bool = False, blockers: tuple[str, ...] = (), parent: str = "ABC-12") -> EpicIssue:
|
||||
return EpicIssue(key, f"Do {key}", "", tuple(sorted(labels)), None, "Done" if done else "To Do", done, parent, blockers=blockers)
|
||||
|
||||
|
||||
class TheCapLine(unittest.TestCase):
|
||||
def test_reads_the_epics_cap(self) -> None:
|
||||
self.assertEqual(parallel_chunks_in("**Language:** Swedish\n**Max parallel chunks:** 3\n\n## Goals\nShip.\n"), 3)
|
||||
|
||||
def test_an_epic_without_the_line_runs_one_chunk_at_once(self) -> None:
|
||||
self.assertEqual(parallel_chunks_in("## Goals\nShip.\n"), 1)
|
||||
self.assertEqual(parallel_chunks_in("```\n**Max parallel chunks:** 3\n```\n"), 1)
|
||||
|
||||
def test_refuses_a_cap_that_is_no_whole_number_of_1_or_more(self) -> None:
|
||||
for value in ("0", "many", "2.5", "-1", ""):
|
||||
found = parallel_chunks_in(f"**Max parallel chunks:** {value}\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, f"the epic's description caps its chunks with `**Max parallel chunks:** {value}`, which is not a whole number of 1 or more, such as `**Max parallel chunks:** 2`")
|
||||
|
||||
|
||||
class WhichIssuesAreChunks(unittest.TestCase):
|
||||
def test_an_open_issue_with_a_repo_or_claude_work_is_a_chunk_in_rank_order(self) -> None:
|
||||
found = chunks([issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "repo:web", done=True)])
|
||||
self.assertEqual(found, ([Chunk("ABC-20", "api"), Chunk("ABC-21", None)], []))
|
||||
|
||||
def test_a_split_item_is_no_chunk_but_its_sub_tasks_are(self) -> None:
|
||||
found = chunks([issue("ABC-20", "split-by-repo"), issue("ABC-23", "repo:api", parent="ABC-20"), issue("ABC-24", "repo:web", parent="ABC-20")])
|
||||
self.assertEqual(found, ([Chunk("ABC-23", "api"), Chunk("ABC-24", "web")], []))
|
||||
|
||||
def test_an_issue_waits_for_its_pick_its_human_and_its_blockers(self) -> None:
|
||||
found = chunks([
|
||||
issue("ABC-20"),
|
||||
issue("ABC-21", "do-epic-human"),
|
||||
issue("ABC-22", "repo:api", "repo:web"),
|
||||
issue("ABC-23", "repo:api", blockers=("ABC-20", "ABC-30", "XYZ-1")),
|
||||
issue("ABC-30", "repo:api", done=True),
|
||||
])
|
||||
self.assertEqual(found, ([], [
|
||||
Waits("ABC-20", "no label names its repo"),
|
||||
Waits("ABC-21", "it is a human's task"),
|
||||
Waits("ABC-22", "ABC-22 is labelled with 2 picks: repo:api, repo:web; remove all but the right one"),
|
||||
Waits("ABC-23", "ABC-20 and XYZ-1 block it"),
|
||||
]))
|
||||
|
||||
|
||||
class RoomInARepo(unittest.TestCase):
|
||||
def test_a_repo_with_room_and_no_loop_claude_takes_a_chunk(self) -> None:
|
||||
self.assertIsNone(refusal("api", RepoRoom(limit=2, running=1, loop_claude=False)))
|
||||
|
||||
def test_a_full_repo_takes_none(self) -> None:
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=2, loop_claude=False)), "api runs as many chunks as its `parallel-chunks` allows: 2")
|
||||
|
||||
def test_a_repo_loop_claude_runs_chunks_in_takes_none(self) -> None:
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=0, loop_claude=True)), "loop-claude runs chunks in api")
|
||||
|
||||
|
||||
class Tmux:
|
||||
"""Stands in for tmux: `windows` are the rows of `list-windows -a`, as session, name, dead and root; a started window joins them."""
|
||||
|
||||
def __init__(self, *windows: tuple[str, str, bool, str], owners: dict[str, str] | None = None) -> None:
|
||||
self.windows, self.owners, self.calls = list(windows), owners or {}, []
|
||||
|
||||
def __call__(self, args: list[str]) -> subprocess.CompletedProcess[str]:
|
||||
self.calls.append(args)
|
||||
out = ""
|
||||
if args[0] == "list-windows" and "-a" in args:
|
||||
out = "".join(f"{session}\t{name}\t{int(dead)}\t@{at}\t{root}\n" for at, (session, name, dead, root) in enumerate(self.windows))
|
||||
elif args[0] == "list-windows":
|
||||
out = "".join(f"{name}\t{int(dead)}\t@{at}\n" for at, (session, name, dead, _) in enumerate(self.windows) if f"={session}" == args[2])
|
||||
elif args[0] == "show-options":
|
||||
out = self.owners.get(args[3].removeprefix("=").removesuffix(":"), "") + "\n"
|
||||
elif args[0] in ("new-session", "new-window"):
|
||||
session = args[args.index("-s") + 1] if args[0] == "new-session" else args[args.index("-t") + 1].removeprefix("=").removesuffix(":")
|
||||
self.windows.append((session, args[args.index("-n") + 1], False, args[args.index("-c") + 1]))
|
||||
out = f"@{len(self.windows) - 1}\n"
|
||||
elif args[0] == "kill-window":
|
||||
self.windows[int(args[2].removeprefix("@"))] = ("", "", True, "")
|
||||
return subprocess.CompletedProcess(args, 0, out, "")
|
||||
|
||||
def started(self) -> list[tuple[str, str, str]]:
|
||||
"""Each window started, as its session, its name and its command's words after the launcher."""
|
||||
return [(args[3].removeprefix("=").removesuffix(":"), args[args.index("-n") + 1], " ".join(args[args.index("--") + 2:])) for args in self.calls if args[0] in ("new-session", "new-window")]
|
||||
|
||||
|
||||
class StartingAnEpicsChunks(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.home = pathlib.Path(folder.name)
|
||||
|
||||
def epic(self, cap: int, **limits: int) -> Epic:
|
||||
"""An epic whose repos are checked out under the home folder, each with its `parallel-chunks`."""
|
||||
def locate(name: str) -> tuple[pathlib.Path, int] | Failure:
|
||||
return (self.home / "code" / name, limits[name]) if name in limits else Failure(f"no project config names {name}")
|
||||
return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"LOOP_CLAUDE_X": "1", "OTHER": "2"})
|
||||
|
||||
def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started:
|
||||
found = start_chunks(epic, issues, own, run)
|
||||
assert not isinstance(found, Failure), found
|
||||
return found
|
||||
|
||||
def test_starts_a_window_per_chunk_up_to_the_epics_cap(self) -> None:
|
||||
run = Tmux()
|
||||
found = self.start(self.epic(2, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "repo:web")], run)
|
||||
self.assertEqual(found, Started(["ABC-20", "ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")]))
|
||||
self.assertEqual(run.started(), [("epic-ABC-12", "ABC-20", f"{CHUNK_FLAG} ABC-20 ABC-12"), ("epic-ABC-12", "ABC-21", f"{CHUNK_FLAG} ABC-21 ABC-12")])
|
||||
self.assertEqual([args[args.index("-c") + 1] for args in run.calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / ".local/state/do-epic/ABC-12")])
|
||||
self.assertIn("LOOP_CLAUDE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")])
|
||||
self.assertNotIn("OTHER=2", run.calls[[args[0] for args in run.calls].index("new-session")])
|
||||
|
||||
def test_a_running_chunk_counts_and_is_not_started_twice(self) -> None:
|
||||
run = Tmux(("epic-ABC-12", "ABC-20 ?", False, str(self.home / "code/api")))
|
||||
found = self.start(self.epic(2, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")]))
|
||||
|
||||
def test_a_repo_takes_its_parallel_chunks_across_epics(self) -> None:
|
||||
run = Tmux(("epic-XYZ-1", "XYZ-5", False, str(self.home / "code/api")))
|
||||
found = self.start(self.epic(3, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:web")], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "api runs as many chunks as its `parallel-chunks` allows: 1")]))
|
||||
|
||||
def test_never_starts_in_a_repo_loop_claude_runs_chunks_in(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
found = self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run)
|
||||
self.assertEqual(found, Started([], [Waits("ABC-20", "loop-claude runs chunks in api")]))
|
||||
|
||||
def test_a_stopped_loop_claude_window_keeps_no_repo(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", True, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
self.assertEqual(self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run).started, ["ABC-20"])
|
||||
|
||||
def test_a_repo_that_cannot_be_located_waits_with_the_reason(self) -> None:
|
||||
found = self.start(self.epic(3), [issue("ABC-20", "repo:api")], Tmux())
|
||||
self.assertEqual(found, Started([], [Waits("ABC-20", "no project config names api")]))
|
||||
|
||||
def test_the_human_restarts_a_stopped_chunk_in_place_of_its_window(self) -> None:
|
||||
run = Tmux(("epic-ABC-12", "ABC-20", True, str(self.home / "code/api")))
|
||||
self.assertEqual(self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], run).started, ["ABC-20"])
|
||||
self.assertIn(["kill-window", "-t", "@0"], run.calls)
|
||||
|
||||
def test_a_finished_chunk_leaves_its_room_and_restarts_no_stopped_chunk(self) -> None:
|
||||
run = Tmux(("epic-ABC-12", "ABC-20", False, str(self.home / "code/api")), ("epic-ABC-12", "ABC-21", True, str(self.home / "code/api")))
|
||||
found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run, own="ABC-20")
|
||||
self.assertEqual(found, Started(["ABC-22"], [Waits("ABC-21", "its window stopped; run `do-epic ABC-12` to start it again")]))
|
||||
|
||||
def test_holds_each_repos_starting_lock_that_loop_claude_holds(self) -> None:
|
||||
self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], Tmux())
|
||||
self.assertTrue((self.home / ".local/state/loop-claude/api/starting").is_file())
|
||||
self.assertTrue((self.home / ".local/state/do-epic/ABC-12/starting").is_file())
|
||||
|
||||
|
||||
class WindowsAcrossSessions(unittest.TestCase):
|
||||
def test_lists_each_window_with_its_session_and_root(self) -> None:
|
||||
run = Tmux(("epic-ABC-12", "ABC-20 ?", False, "/code/api"), ("loop-api", "item-3", True, ""))
|
||||
self.assertEqual(tmux.everywhere(run), [tmux.Placed("epic-ABC-12", tmux.Listed("ABC-20", "@0", False), "/code/api"), tmux.Placed("loop-api", tmux.Listed("item-3", "@1", True), "")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user