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

108 lines
7.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, of_label, REPO_PREFIX, REVIEW_LABEL
from do_epic.epic_record import EpicRecord
from do_epic.backend.protocol import EpicStore
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"
# 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>]... [{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.
{LABEL} is {LABELS}; 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} makes the new issue blocked by that issue of the epic, or one of its sub-tasks, and {PARENT} files a sub-task under that child issue of the epic. A repo whose rules ask for a change to ship as more than one pull request gets an issue for each, the next one blocked by the one before.
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 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"Where the repo's rules ask for a change to ship as more than one pull request, file the next one as its own issue with `{launcher} {epic} {FILE} \"<summary>\" {BLOCKED_BY} <this issue's key>`, and `{PARENT} <its parent's key>` as well where this issue is a sub-task, then finish only this one. "
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
@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:
"""What 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(), []))):
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, 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)
flag, value, labels = write.flag, write.value, write.labels
if flag == FILE:
if unread := [label for label in labels if of_label(label) 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 {LABELS}")
if len(picks := [label for label in labels if of_label(label)]) > 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) for label in labels) else f" It has no label that says where it is worked, so the next `do-epic {epic}` picks one: {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."