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

122 lines
8.3 KiB
Python

"""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 dataclasses
import fcntl
import pathlib
import typing
from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, label_of, LabelRepos, of_label, REPO_PREFIX, team_label
from do_epic.backend.protocol import EpicIssue, EpicStore, REVIEW_LABEL
from do_epic.epic_record import EpicRecord
from failure import Failure
from text_files.markdown_text import listed
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"
BLOCKED_BY = "--blocked-by"
PARENT = "--parent"
RECORD_DECISION = "--record-decision"
def worked_by(team: LabelRepos) -> str:
"""The labels that say where an issue is worked, as do-epic's scheduler reads them: for each repo the team's table names, the label on its first line for that repo, and `repo:<name>` for any other repo."""
named = [f"`{label}` for the repo {name}" for name in sorted(set(team.values())) if (label := team_label(name, team))]
repos = ", ".join([*named, f"`{REPO_PREFIX}<name>` for {'any other repo' if named else 'the repo'} that works it"])
return f"{repos}, `{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>]... [{BLOCKED_BY} <KEY>] [{PARENT} <KEY>] [<<'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.
A finding about a repo's own goals goes into that repo's plan instead.
{LABEL} is {worked_by({})}; without one, the next `do-epic <EPIC-KEY>` you run picks where the issue is worked.
A second {LABEL}, `{REVIEW_LABEL}`, marks the issue as a repo's release review, which the epic's finishing files.
{BLOCKED_BY} <KEY> makes the new issue wait for the issue <KEY>, which is a child issue of the epic or a sub-task of one.
{PARENT} <KEY> files the new issue as a sub-task of the child issue <KEY>.
Where a repo's rules ask for a change to ship as more than one pull request, file each step after the first with {BLOCKED_BY} set to the step before it.
{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, team: LabelRepos, issue: EpicIssue | None = None) -> 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. Where issue is the chunk's own, it also says how to file the next pull request of a change as an issue that waits for it."""
next_step = ""
if issue:
parent = f" {PARENT} {issue.parent}" if issue.parent != epic else ""
pick = next((found for each in issue.labels if (found := of_label(each, team))), None)
label = f" {LABEL} {label_of(pick, team)}" if pick else ""
next_step = f"Where the repo's rules ask for a change to ship as more than one pull request, finish only this issue's pull request, and file only the next one as an issue that waits for it, with `{launcher} {epic} {FILE} \"<summary>\" {BLOCKED_BY} {issue.key}{parent}{label}` and its detail on stdin. "
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 {worked_by(team)}; leave it out where you cannot tell, and the next `do-epic` the human runs picks it. "
"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"{next_step}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
@dataclasses.dataclass(frozen=True)
class Write:
"""What the words after the epic's key ask for: the flag, and its summary or title. A finding may also carry labels, the issue that blocks it and the child issue it is a sub-task of."""
flag: str
value: str
labels: tuple[str, ...] = ()
blocked_by: str | None = None
parent: str | None = None
def parsed(words: list[str]) -> Write | None:
"""The Write the words after the epic's key ask for. None where they aren't spelt as USAGE has them. A word that opens with `--` is no summary, title, label or key."""
if not words or words[0] not in (FILE, RECORD_DECISION):
return None
taken: dict[str, list[str]] = {LABEL: [], BLOCKED_BY: [], PARENT: []}
rest = words[1:]
for option in taken if words[0] == FILE else ():
while option in rest:
at = rest.index(option)
if at + 1 >= len(rest):
return None
taken[option].append(rest[at + 1])
rest = rest[:at] + rest[at + 2:]
if len(rest) != 1 or len(taken[BLOCKED_BY]) > 1 or len(taken[PARENT]) > 1 or any(word.startswith("--") for word in (*rest, *sum(taken.values(), []))) or any(not word.strip() for option in (BLOCKED_BY, PARENT) for word in taken[option]):
return None
return Write(words[0], rest[0], tuple(taken[LABEL]), *(taken[option][0] if taken[option] else None for option in (BLOCKED_BY, PARENT)))
def written(epic: str, write: Write, store: EpicStore, team: LabelRepos, record: EpicRecord, stdin: typing.TextIO, folder: pathlib.Path) -> str | Failure:
"""Files the finding or records the decision, as write says, and answers the line to print. folder is the epic's, where the lock for its decisions lies."""
text = piped(stdin)
flag, value, labels = write.flag, write.value, write.labels
if flag == FILE:
if unread := [label for label in labels if of_label(label, team) is None and label != REVIEW_LABEL]:
return Failure(f"cannot file the finding in the epic {epic}: do-epic doesn't read the label {unread[0]!r}; write {worked_by(team)}")
if len(picks := [label for label in labels if of_label(label, team)]) > 1:
return Failure(f"cannot file the finding in the epic {epic}: {listed(picks, 'and')} each say who works it; write one of them")
key = store.file(write.parent or epic, value, text, labels, write.blocked_by)
if isinstance(key, Failure):
return Failure(f"cannot file the finding in the epic {epic}: {key.reason}")
return f"Filed {key} {f'under {write.parent} in ' if write.parent else 'in '}the epic {epic}." + (f" It is blocked by {write.blocked_by}." if write.blocked_by else "") + ("" if any(of_label(label, team) for label in labels) else f" It has no label that says where it is worked, so the next `do-epic {epic}` picks one: {worked_by(team)}.")
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."