Merge remote-tracking branch 'origin/main' into item-411
CI / tests (pull_request) Has been cancelled
CI / tests (pull_request) Has been cancelled
# Conflicts: # README.md # bin/do_epic/chunk_prompt.py # bin/do_epic/main.py # bin/do_epic/test_main.py
This commit is contained in:
@@ -2,6 +2,10 @@
|
||||
import dataclasses
|
||||
|
||||
from do_epic.backend.protocol import EpicIssue
|
||||
from do_epic import findings
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from text_files.markdown_text import listed
|
||||
import pathlib
|
||||
from model_routing.ladder import ProjectRung
|
||||
from loop_claude.cycle import prompts
|
||||
from model_routing.route import Route
|
||||
@@ -11,10 +15,10 @@ from agent_cycle.worker_prompts import WorkerPrompts
|
||||
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."""
|
||||
def task(issue: EpicIssue, epic: str, checkout: str | None, launcher: pathlib.Path, language: str) -> 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. launcher is the do-epic that runs the chunk, and language the one the epic's Jira text is in."""
|
||||
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 "")
|
||||
return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {findings.instructions(epic, launcher, language)} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "")
|
||||
|
||||
|
||||
CODE_HEALTH = '~/.claude/CLAUDE.md → "Shared goal"'
|
||||
@@ -28,7 +32,13 @@ def fresh(task: str, premises: str, route: Route, project: ProjectRung | None, f
|
||||
|
||||
|
||||
# The worker names no plan items: the chunk's one item is its issue.
|
||||
WORKER = prompts.worker_prompts(DRIVER, fresh, "")
|
||||
# The epic's records come first, as its goals do; a chunk without a repo is handed only those and the human's rules, so the names that mention a repo's then name nothing it reads.
|
||||
NAMES = prompts.RecordNames(
|
||||
quote_sources=listed(("the epic's description", "the repo's goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or"),
|
||||
answer_destinations="the epic's description under ## Decisions, the repo's goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the repo's plan or a comment",
|
||||
records_named="the epic's scoring and decisions, then the repo's working rules and decisions, then the human's rules for every project",
|
||||
)
|
||||
WORKER = prompts.worker_prompts(DRIVER, fresh, "", NAMES)
|
||||
|
||||
# What a worker does with a reviewer's feedback, as the decision asks (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
|
||||
FEEDBACK = 'Where a reviewer left feedback, fix what is reasonable and push the fix, answer each other comment in its thread, and change the setup so our review would have caught the finding (~/.claude/CLAUDE.md → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first"). Then merge the pull request as before.'
|
||||
|
||||
@@ -89,6 +89,19 @@ def with_language(text: str, language: str) -> str | Failure:
|
||||
return line + "\n" + "\n" * bool(text.strip()) + text
|
||||
|
||||
|
||||
def decision_titled(decisions: str, title: str) -> str | None:
|
||||
"""The entry under the ### title heading of decisions, a ## Decisions section's body; None where it has no such heading."""
|
||||
found: list[str] | None = None
|
||||
for line, fenced in fenced_lines(decisions):
|
||||
if not fenced and line.startswith("### "):
|
||||
if found is not None:
|
||||
break
|
||||
found = [] if line[4:].strip() == title else None
|
||||
elif found is not None:
|
||||
found.append(line)
|
||||
return None if found is None else "\n".join(found).strip()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class EpicRecord:
|
||||
"""One epic's record, kept in its description."""
|
||||
@@ -110,6 +123,28 @@ class EpicRecord:
|
||||
"""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())
|
||||
|
||||
def append_decision(self, title: str, entry: str) -> bool | Failure:
|
||||
"""Adds entry under a ### title heading at the end of ## Decisions, leaving the decisions before it as they are. False where the section already holds that entry under that title, so recording a decision twice keeps one; a Failure where it holds another entry under it, so one title names one decision."""
|
||||
title, entry = title.strip(), entry.strip()
|
||||
if not title or "\n" in title:
|
||||
return Failure("the title must be one line of text")
|
||||
if not entry:
|
||||
return Failure("pipe the decision's text in")
|
||||
held = self.description.held()
|
||||
if isinstance(held, Failure):
|
||||
return held
|
||||
before = read_section(held.text, "Decisions")
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
same = decision_titled(before, title)
|
||||
if same is not None:
|
||||
return False if same == entry else Failure(f"## Decisions already holds another decision titled {title!r}: give this one a title of its own")
|
||||
text = with_section(held.text, "Decisions", f"{before}\n\n### {title}\n\n{entry}".strip())
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
wrote = dataclasses.replace(self.description, approved=frozenset()).write(text, held.version)
|
||||
return wrote if isinstance(wrote, Failure) else True
|
||||
|
||||
def write_language(self, language: str) -> Held | Failure:
|
||||
return self.written(lambda text: with_language(text, language), frozenset())
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""What a chunk's worker writes into its epic: a finding, filed as an issue, and a decision, appended to the description.
|
||||
|
||||
A finding about one of the epic's goals is filed in the epic, and one about a repo's goals by that repo's rules (docs/decisions.md → `do-epic: drives one Jira epic …` → "Findings"). A decision that governs the epic goes under the description's ## Decisions, where the judge of each later chunk reads it."""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from do_epic.backend.protocol import EpicStore
|
||||
from failure import Failure
|
||||
from text_files.piped_text import piped
|
||||
|
||||
# Three readers, seated as the human and as a chunk's worker, picked each spelling from four: `<EPIC-KEY> --file` over `--file <EPIC-KEY>`, `add` and `--finding`, and `--record-decision` over `--decision` and `--decide`.
|
||||
FILE = "--file"
|
||||
LABEL = "--label"
|
||||
RECORD_DECISION = "--record-decision"
|
||||
# The labels that say where an issue is worked, as do-epic's scheduler reads them.
|
||||
LABELS = f"`{REPO_PREFIX}<name>` for the repo that works it, `{CLAUDE_LABEL}` for work of Claude's that changes no repo, or `{HUMAN_LABEL}` for a task of the human's"
|
||||
# Under the epic's folder, the file a do-epic holds locked while it appends a decision.
|
||||
DECISIONS_LOCK = "decisions.lock"
|
||||
USAGE = f"""do-epic <EPIC-KEY> {FILE} <summary> [{LABEL} <label>] [<<'EOF' detail EOF]
|
||||
do-epic <EPIC-KEY> {RECORD_DECISION} <title> <<'EOF' entry EOF"""
|
||||
HELP = f"""{FILE} files a finding about one of the epic's goals as an open issue of the epic, with the markdown piped in as its description.
|
||||
{LABEL} is {LABELS}; without one the issue waits until someone labels it.
|
||||
A finding about a repo's own goals goes into that repo's plan instead.
|
||||
{RECORD_DECISION} appends a decision that governs the epic to its description's ## Decisions, under the title, with the markdown piped in as its text."""
|
||||
|
||||
|
||||
def instructions(epic: str, launcher: pathlib.Path, language: str) -> str:
|
||||
"""What a chunk's first prompt says about filing a finding and recording a decision in the epic with the key epic. launcher is the do-epic that runs the chunk, and language the one the epic's Jira text is in."""
|
||||
return (
|
||||
f"File a finding about one of the epic's goals in the epic, with `{launcher} {epic} {FILE} \"<summary>\" {LABEL} <label>` and its detail on stdin. "
|
||||
f"The label is {LABELS}; leave it out where you cannot tell, and the issue waits for the human. "
|
||||
"Where filing fails and says the issue may exist, ask the human to look before you file it again. "
|
||||
"File a finding about a repo's goals by that repo's rules. Where unsure which, ask the human. "
|
||||
f"Record a decision that governs the epic, such as an answer the human typed, with `{launcher} {epic} {RECORD_DECISION} \"<title>\"` and its text on stdin. "
|
||||
f"Write the issue and the decision in {language}, the epic's language."
|
||||
)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def decisions_locked(folder: pathlib.Path) -> typing.Iterator[None]:
|
||||
"""Holds the epic's DECISIONS_LOCK, in its folder, so two chunks that record a decision at once write one after the other. Raises OSError where the file cannot be made or locked."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with open(folder / DECISIONS_LOCK, "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def parsed(words: list[str]) -> tuple[str, str, str | None] | None:
|
||||
"""What the words after the epic's key ask for: the flag, the summary or title, and the label, None without one. None where they aren't spelt as USAGE has them. A word that opens with `--` is no summary, title or label."""
|
||||
if not words or words[0] not in (FILE, RECORD_DECISION):
|
||||
return None
|
||||
label: str | None = None
|
||||
rest = words[1:]
|
||||
if words[0] == FILE and LABEL in rest:
|
||||
at = rest.index(LABEL)
|
||||
if at + 1 >= len(rest):
|
||||
return None
|
||||
label, rest = rest[at + 1], rest[:at] + rest[at + 2:]
|
||||
if len(rest) != 1 or any(word.startswith("--") for word in (*rest, label or "")):
|
||||
return None
|
||||
return words[0], rest[0], label
|
||||
|
||||
|
||||
def written(epic: str, flag: str, value: str, label: str | None, store: EpicStore, record: EpicRecord, stdin: typing.TextIO, folder: pathlib.Path) -> str | Failure:
|
||||
"""Files the finding or records the decision, as flag says, and answers the line to print. folder is the epic's, where the lock for its decisions lies."""
|
||||
text = piped(stdin)
|
||||
if flag == FILE:
|
||||
if label and of_label(label) is None:
|
||||
return Failure(f"cannot file the finding in the epic {epic}: do-epic doesn't read the label {label!r}; write {LABELS}")
|
||||
key = store.file(epic, value, text, (label,) if label else ())
|
||||
if isinstance(key, Failure):
|
||||
return Failure(f"cannot file the finding in the epic {epic}: {key.reason}")
|
||||
return f"Filed {key} in the epic {epic}." + ("" if label else f" It waits until someone labels it: {LABELS}.")
|
||||
try:
|
||||
with decisions_locked(folder):
|
||||
added = record.append_decision(value, text)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot record the decision in the epic {epic}'s description: cannot lock {failure.filename or folder / DECISIONS_LOCK}: {failure.strerror}")
|
||||
if isinstance(added, Failure):
|
||||
return Failure(f"cannot record the decision in the epic {epic}'s description: {added.reason}")
|
||||
return f"Recorded the decision in the epic {epic}'s description." if added else f"The epic {epic}'s description already holds that decision."
|
||||
+38
-9
@@ -5,12 +5,14 @@
|
||||
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 sys
|
||||
import typing
|
||||
|
||||
from loop_claude.loop.chunk_start import archived_route, routed
|
||||
from do_epic import chunk_prompt, gates, parked, scheduler
|
||||
from do_epic import chunk_prompt, findings, gates, parked, scheduler
|
||||
from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from loop_claude.project.records import CONSEQUENCE, read_records
|
||||
from agent_cycle.run import Cycle, run_cycle
|
||||
from do_epic.config import DoEpicConfig, load
|
||||
from loop_effects.effects import Effects, say
|
||||
@@ -31,7 +33,6 @@ 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
|
||||
@@ -40,6 +41,7 @@ from agent_cycle.direct_message import tell
|
||||
from agent_cycle import tmux
|
||||
|
||||
HELP = f"""usage: do-epic <EPIC-KEY> [--status]
|
||||
{findings.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.
|
||||
@@ -51,6 +53,7 @@ is parked: it frees its place for the next chunk, and its window's name says wha
|
||||
on once the checks pass, the approval comes or a reviewer comments, and a place is free; until one is, the
|
||||
name says `awaits a slot`. 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.
|
||||
{findings.HELP}
|
||||
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"
|
||||
@@ -87,9 +90,9 @@ class EpicRun:
|
||||
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:
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend = jira_backend, stdin: typing.TextIO = sys.stdin, forge_at: typing.Callable[[str], Run] = runner) -> int:
|
||||
try:
|
||||
stop = run(argv, env, paths, launcher, effects, backend, forge_at)
|
||||
stop = run(argv, env, paths, launcher, effects, backend, stdin, forge_at)
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
except Exception as crash:
|
||||
@@ -103,12 +106,16 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
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:
|
||||
def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend, stdin: typing.TextIO, 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)):
|
||||
# What the words after the epic's key write into the epic, where they are a filing or a decision.
|
||||
writes = findings.parsed(words[1:]) if chunk is None else None
|
||||
if (len(words) != 1 and not writes) 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)
|
||||
if writes:
|
||||
return epic_written(words[0], writes, paths, backend, stdin)
|
||||
# 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)
|
||||
@@ -129,6 +136,15 @@ def status_printed(epic: EpicRun) -> Stop:
|
||||
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 epic_written(key: str, writes: tuple[str, str, str | None], paths: Paths, backend: Backend, stdin: typing.TextIO) -> Stop:
|
||||
"""Files a finding in the epic, or records a decision in its description. It needs no tmux, so a chunk's worker may run it anywhere."""
|
||||
config = load(paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return Stop(1, config.reason)
|
||||
done = findings.written(key, *writes, *backend(config, key), stdin, paths.home / scheduler.STATE / key)
|
||||
return Stop(1, done.reason) if isinstance(done, Failure) else Stop(0, done)
|
||||
|
||||
|
||||
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)
|
||||
@@ -338,8 +354,10 @@ def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun, news
|
||||
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 ""
|
||||
language = epic.record.language()
|
||||
if isinstance(language, Failure):
|
||||
return Stop(1, language.reason)
|
||||
records = records_read(loop.root if in_repo else None, epic)
|
||||
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)
|
||||
@@ -355,7 +373,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun, news
|
||||
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)
|
||||
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, epic.launcher, language or epic.config.language), 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:
|
||||
@@ -363,6 +381,17 @@ def repoless_models(epic: EpicRun) -> Models:
|
||||
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 records_read(root: str | None, epic: EpicRun) -> str | Failure:
|
||||
"""The epic's Scoring and Decisions, from its description, then the records of the repo checked out at root, where the chunk has one, then the human's rules."""
|
||||
sections: list[tuple[str, str]] = []
|
||||
for name in ("Scoring", "Decisions"):
|
||||
body = epic.record.section(name)
|
||||
if isinstance(body, Failure):
|
||||
return Failure(f"the epic {epic.key}'s description: {body.reason} - {CONSEQUENCE}.")
|
||||
sections.append((f"the epic {epic.key}'s description, ## {name}", body))
|
||||
return read_records(root, epic.paths.home, epic.paths.claude_dir, tuple(sections))
|
||||
|
||||
|
||||
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] = []
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
import io
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from do_epic.test_main import DESCRIPTION, DoEpicTest
|
||||
from do_epic.epic_record import EpicRecord
|
||||
from failure import Failure
|
||||
from loop_claude.test_loop_claude import FakeEffects
|
||||
from record_store.held import Held
|
||||
from do_epic import main
|
||||
from do_epic.backend.fake import MemoryEpic
|
||||
from loop_state.paths import paths_from
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class WrittenDescription:
|
||||
"""Stands in for an epic's description in Jira that takes writes: kept holds each text it held, the last one now. It refuses a write that claims the human's approval, and notes in locked whether lock was held during each write."""
|
||||
kept: list[str]
|
||||
lock: pathlib.Path
|
||||
locked: list[bool] = dataclasses.field(default_factory=list)
|
||||
approved: frozenset[str] | None = frozenset()
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.kept[-1]
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
return self.text
|
||||
|
||||
def held(self) -> Held | Failure:
|
||||
return Held(self.text)
|
||||
|
||||
def write(self, text: str, version: str | None) -> Held | Failure:
|
||||
if self.approved != frozenset():
|
||||
return Failure(f"approved is {self.approved!r}")
|
||||
with open(self.lock, "a") as other:
|
||||
try:
|
||||
fcntl.flock(other, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
self.locked.append(False)
|
||||
except BlockingIOError:
|
||||
self.locked.append(True)
|
||||
self.kept.append(text)
|
||||
return Held(text)
|
||||
|
||||
|
||||
class FindingsTest(DoEpicTest):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.store = MemoryEpic("ABC-12", list(self.issues))
|
||||
self.written = WrittenDescription([DESCRIPTION], self.home / ".local/state/do-epic/ABC-12/decisions.lock")
|
||||
self.keys: list[str] = []
|
||||
|
||||
def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]:
|
||||
self.keys.append(key)
|
||||
return self.store, EpicRecord(self.written) # type: ignore[arg-type]
|
||||
|
||||
def run_with(self, argv: list[str], stdin: str = "") -> tuple[int, str, str, FakeEffects]:
|
||||
out, err, fake = io.StringIO(), io.StringIO(), FakeEffects()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, io.StringIO(stdin))
|
||||
# Without the time each line of do-epic opens with.
|
||||
return code, out.getvalue().replace("<1790000000> ", ""), err.getvalue().replace("<1790000000> ", ""), fake
|
||||
|
||||
|
||||
class FilingAFinding(FindingsTest):
|
||||
def test_files_an_issue_under_the_epic_with_the_detail_piped_in_and_doesnt_start_anything(self) -> None:
|
||||
code, out, err, fake = self.run_with(["ABC-12", "--file", "Retry the import on a 503"], "The client times out.\n")
|
||||
self.assertEqual((code, out, err), (0, "Filed ABC-102 in the epic ABC-12. It waits until someone labels it: `repo:<name>` for the repo that works it, `do-epic-claude` for work of Claude's that changes no repo, or `do-epic-human` for a task of the human's.\n", ""))
|
||||
self.assertEqual(self.keys, ["ABC-12"])
|
||||
filed = self.store.issues[-1]
|
||||
self.assertEqual((filed.key, filed.summary, filed.detail, filed.labels, filed.parent, filed.by_loop), ("ABC-102", "Retry the import on a 503", "The client times out.", (), "ABC-12", True))
|
||||
self.assertEqual(fake.calls, [], "filing needs no tmux, clone or claude")
|
||||
|
||||
def test_a_label_says_where_the_issue_is_worked(self) -> None:
|
||||
for argv, label in ((["ABC-12", "--file", "Retry", "--label", "repo:api"], "repo:api"), (["ABC-12", "--file", "--label", "do-epic-claude", "Retry"], "do-epic-claude"), (["ABC-12", "--file", "Retry", "--label", "do-epic-human"], "do-epic-human")):
|
||||
with self.subTest(argv=argv):
|
||||
code, out, _, _ = self.run_with(argv)
|
||||
filed = self.store.issues[-1]
|
||||
self.assertEqual((code, out, filed.labels, filed.detail), (0, f"Filed {filed.key} in the epic ABC-12.\n", (label,), ""))
|
||||
|
||||
def test_refuses_a_label_the_scheduler_doesnt_read(self) -> None:
|
||||
for label in ("api", "repo:", "repo:a b"):
|
||||
with self.subTest(label=label):
|
||||
code, out, err, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", label])
|
||||
self.assertEqual((code, out, len(self.store.issues)), (1, "", 2))
|
||||
self.assertEqual(err, f"cannot file the finding in the epic ABC-12: do-epic doesn't read the label {label!r}; write `repo:<name>` for the repo that works it, `do-epic-claude` for work of Claude's that changes no repo, or `do-epic-human` for a task of the human's\n")
|
||||
|
||||
def test_says_why_an_issue_was_not_filed(self) -> None:
|
||||
self.store.fails = "Jira answered 401"
|
||||
code, _, err, _ = self.run_with(["ABC-12", "--file", "Retry"])
|
||||
self.assertEqual((code, err), (1, "cannot file the finding in the epic ABC-12: Jira answered 401\n"))
|
||||
|
||||
def test_stops_where_the_machines_settings_cannot_be_read(self) -> None:
|
||||
(self.home / ".claude-projects/do-epic/config.toml").unlink()
|
||||
code, out, err, _ = self.run_with(["ABC-12", "--file", "Retry"])
|
||||
self.assertEqual((code, out, len(self.store.issues)), (1, "", 2))
|
||||
self.assertIn("config.toml", err)
|
||||
|
||||
def test_prints_the_help_for_a_filing_spelt_wrong(self) -> None:
|
||||
for argv in (["ABC-12", "--file"], ["ABC-12", "--file", "a", "b"], ["ABC-12", "--file", "a", "--label"], ["ABC-12", "--file", "a", "--labels", "x"], ["--file", "ABC-12", "a"], ["ABC-12", "--file", "--label", "x"], ["ABC-12", "--file", "--lable"], ["ABC-12", "--file", "a", "--label", "--x"], ["--chunk", "ABC-20", "ABC-12", "--file", "a"]):
|
||||
with self.subTest(argv=argv):
|
||||
code, out, err, _ = self.run_with(argv)
|
||||
self.assertEqual((code, out, err, len(self.store.issues)), (1, "", main.HELP + "\n", 2))
|
||||
|
||||
|
||||
class RecordingADecision(FindingsTest):
|
||||
def test_appends_the_entry_to_the_descriptions_decisions(self) -> None:
|
||||
code, out, err, fake = self.run_with(["ABC-12", "--record-decision", "Imports retry three times"], "2026-11-18, the human's answer. Valid while the client's API rate-limits.\n")
|
||||
self.assertEqual((code, out, err, fake.calls), (0, "Recorded the decision in the epic ABC-12's description.\n", "", []))
|
||||
self.assertEqual(self.written.text, DESCRIPTION + "\n## Decisions\n\n### Imports retry three times\n\n2026-11-18, the human's answer. Valid while the client's API rate-limits.\n")
|
||||
self.assertEqual(self.run_with(["ABC-12", "--record-decision", "Merges squash"], "Always.")[0], 0)
|
||||
self.assertTrue(self.written.text.endswith("rate-limits.\n\n### Merges squash\n\nAlways.\n"), self.written.text)
|
||||
self.assertIn("## Goals\nShip the import.\n\n## Audience\nThe client's team.\n", self.written.text)
|
||||
self.assertEqual((self.keys, self.written.locked), (["ABC-12", "ABC-12"], [True, True]))
|
||||
|
||||
def test_recording_a_decision_twice_keeps_one(self) -> None:
|
||||
self.run_with(["ABC-12", "--record-decision", "Merges squash"], "Always.\n\n```\n### not a title\n```\n")
|
||||
self.run_with(["ABC-12", "--record-decision", "Imports retry"], "Three times.")
|
||||
held = self.written.text
|
||||
code, out, err, _ = self.run_with(["ABC-12", "--record-decision", " Merges squash "], "Always.\n\n```\n### not a title\n```")
|
||||
self.assertEqual((code, out, err, self.written.text), (0, "The epic ABC-12's description already holds that decision.\n", "", held))
|
||||
self.assertEqual(len(self.written.kept), 3)
|
||||
|
||||
def test_refuses_another_decision_under_a_title_the_description_holds(self) -> None:
|
||||
self.run_with(["ABC-12", "--record-decision", "Merges squash"], "Always.")
|
||||
held = self.written.text
|
||||
code, out, err, _ = self.run_with(["ABC-12", "--record-decision", "Merges squash"], "Always")
|
||||
self.assertEqual((code, out, self.written.text), (1, "", held))
|
||||
self.assertEqual(err, "cannot record the decision in the epic ABC-12's description: ## Decisions already holds another decision titled 'Merges squash': give this one a title of its own\n")
|
||||
|
||||
def test_says_why_the_lock_was_not_taken(self) -> None:
|
||||
self.written.lock.parent.parent.mkdir(parents=True)
|
||||
self.written.lock.parent.write_text("")
|
||||
code, out, err, _ = self.run_with(["ABC-12", "--record-decision", "Merges squash"], "Always.")
|
||||
self.assertEqual((code, out, self.written.text), (1, "", DESCRIPTION))
|
||||
self.assertRegex(err, f"^cannot record the decision in the epic ABC-12's description: cannot lock {self.written.lock.parent}: \\w")
|
||||
|
||||
def test_refuses_a_decision_without_a_title_or_a_body(self) -> None:
|
||||
for argv, stdin, reason in ((["ABC-12", "--record-decision", "Merges squash"], " \n", "pipe the decision's text in"), (["ABC-12", "--record-decision", "two\nlines"], "Always.", "the title must be one line of text"), (["ABC-12", "--record-decision", " "], "Always.", "the title must be one line of text"), (["ABC-12", "--record-decision", "Merges squash"], "## Goals\nNone.", "the body of ## Decisions holds a level 1 or 2 heading, which would start another section")):
|
||||
with self.subTest(argv=argv, stdin=stdin):
|
||||
code, out, err, _ = self.run_with(argv, stdin)
|
||||
self.assertEqual((code, out, err, self.written.text), (1, "", f"cannot record the decision in the epic ABC-12's description: {reason}\n", DESCRIPTION))
|
||||
|
||||
def test_prints_the_help_for_a_decision_spelt_wrong(self) -> None:
|
||||
for argv in (["ABC-12", "--record-decision"], ["ABC-12", "--record-decision", "a", "b"], ["ABC-12", "--decide", "a"]):
|
||||
with self.subTest(argv=argv):
|
||||
code, out, err, _ = self.run_with(argv, "Always.")
|
||||
self.assertEqual((code, out, err, self.written.text), (1, "", main.HELP + "\n", DESCRIPTION))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import unittest
|
||||
unittest.main()
|
||||
@@ -80,7 +80,7 @@ class DoEpicTest(unittest.TestCase):
|
||||
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, self.forge_at)
|
||||
code = main.main(argv, env or {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, forge_at=self.forge_at)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
|
||||
@@ -165,11 +165,27 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
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_records_are_the_epics_scoring_and_decisions_then_the_humans_rules(self) -> None:
|
||||
self.description = DESCRIPTION + "\n## Scoring\nE + I, bar 4.\n\n## Decisions\n### Merges squash\nAlways.\n"
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude/CLAUDE.md").write_text("# Global\n", encoding="utf-8")
|
||||
self.assertEqual(self.cycle().records, "From the epic ABC-12's description, ## Scoring:\nE + I, bar 4.\n\nFrom the epic ABC-12's description, ## Decisions:\n### Merges squash\nAlways.\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
|
||||
|
||||
def test_stops_where_a_section_of_the_epics_records_cannot_be_read(self) -> None:
|
||||
self.description = DESCRIPTION + "\n## Scoring\nA.\n\n## Scoring\nB.\n"
|
||||
with self.assertRaises(AssertionError) as raised:
|
||||
self.cycle()
|
||||
self.assertIn("the epic ABC-12's description: the epic's description has ## Scoring more than once - the judge cannot read the records.", str(raised.exception))
|
||||
|
||||
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.")
|
||||
task = self.cycle().task
|
||||
self.assertTrue(task.startswith("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. File a finding"), task)
|
||||
self.assertIn('with `/b/do-epic ABC-12 --file "<summary>" --label <label>` and its detail on stdin', task)
|
||||
self.assertIn("Write the issue and the decision in English, the epic's language.", task)
|
||||
self.assertTrue(task.endswith(" Its summary: Do ABC-21\n\nIts description:\n\nTidy the docs."), task)
|
||||
|
||||
def test_an_issue_without_scores_runs_on_the_projects_rung(self) -> None:
|
||||
self.issues[1] = dataclasses.replace(self.issues[1], scores={})
|
||||
@@ -320,16 +336,19 @@ class AChunksRun(DoEpicTest):
|
||||
(checkout / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
|
||||
(checkout / "AGENTS.md").write_text("Squash every merge.\n", encoding="utf-8")
|
||||
self.issues = [dataclasses.replace(issue("ABC-20", "repo:api"), scores={"L": 2, "E": 1, "I": 1})]
|
||||
self.description = DESCRIPTION + "\n## Decisions\nKeep the v1 endpoints.\n"
|
||||
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
|
||||
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
|
||||
self.assertEqual(code, 0, err)
|
||||
prompt = " ".join([what for seam, what in fake.calls if seam == "stream_claude"][0])
|
||||
self.assertIn(f"Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout {checkout}, on the branch ABC-20.", prompt)
|
||||
self.assertIn(f"Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout {checkout}, on the branch ABC-20. File a finding", prompt)
|
||||
self.assertIn("Ship the import.", prompt)
|
||||
self.assertIn("The repo's goals, which rank after the epic's and after code health, are from", prompt)
|
||||
self.assertIn("Serve the API.", prompt)
|
||||
self.assertIn("the chunk finished; ", out)
|
||||
self.assertIn("Squash every merge.", [what[1] for seam, what in fake.calls if seam == "claude"][0])
|
||||
self.assertIn("the chunk finished; started no other\n", out)
|
||||
judge_prompt = [what[1] for seam, what in fake.calls if seam == "claude"][0]
|
||||
self.assertIn("The records: the epic's scoring and decisions, then the repo's working rules and decisions, then the human's rules for every project:\nFrom the epic ABC-12's description, ## Decisions:\nKeep the v1 endpoints.\n\nFrom AGENTS.md:\nSquash every merge.", judge_prompt)
|
||||
self.assertIn("writing it into the epic's description under ## Decisions, the repo's goals file's Goals or Audience, AGENTS.md, docs/decisions.md, the repo's plan or a comment", judge_prompt)
|
||||
|
||||
def test_a_chunk_without_a_repo_reads_no_forge(self) -> None:
|
||||
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
|
||||
|
||||
@@ -293,7 +293,16 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
|
||||
class TheFirstPrompt(unittest.TestCase):
|
||||
def test_the_task_names_the_checkout_and_branch_and_quotes_a_description_only_where_there_is_one(self) -> None:
|
||||
self.assertEqual(chunk_prompt.task(issue("ABC-20"), "ABC-12", "/code/api"), "Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout /code/api, on the branch ABC-20. Its summary: Do ABC-20")
|
||||
labels = "`repo:<name>` for the repo that works it, `do-epic-claude` for work of Claude's that changes no repo, or `do-epic-human` for a task of the human's"
|
||||
told = (
|
||||
f"File a finding about one of the epic's goals in the epic, with `/b/do-epic ABC-12 --file \"<summary>\" --label <label>` and its detail on stdin. The label is {labels}; leave it out where you cannot tell, and the issue waits for the human. "
|
||||
"Where filing fails and says the issue may exist, ask the human to look before you file it again. File a finding about a repo's goals by that repo's rules. Where unsure which, ask the human. "
|
||||
"Record a decision that governs the epic, such as an answer the human typed, with `/b/do-epic ABC-12 --record-decision \"<title>\"` and its text on stdin. Write the issue and the decision in Swedish, the epic's language."
|
||||
)
|
||||
self.assertEqual(chunk_prompt.task(issue("ABC-20"), "ABC-12", "/code/api", pathlib.Path("/b/do-epic"), "Swedish"), f"Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout /code/api, on the branch ABC-20. {told} Its summary: Do ABC-20")
|
||||
|
||||
def test_an_answer_the_judge_quoted_names_the_epics_description_first(self) -> None:
|
||||
self.assertTrue(chunk_prompt.WORKER.answered("Q", "A", Route(Rung("off-the-ladder")), None, False).startswith("Your question: Q\n\nthe epic's description, "))
|
||||
|
||||
def test_opens_with_the_task_then_the_rung_then_the_premises(self) -> None:
|
||||
rest = f"The issue sets the chunk's scope. The goals below choose between ways to deliver that scope, and never widen it. The epic's goals rank first, then code health ({chunk_prompt.CODE_HEALTH}), then the repo's.\n\nFrom P"
|
||||
|
||||
Reference in New Issue
Block a user