From 95535b4fb35ac457a25f23737bf386f72833abd8 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 15:33:51 +0100 Subject: [PATCH 01/22] Read a team's own repo labels as do-epic's picks, and treat an item a person filed sub-tasks under as split --- README.md | 4 +-- bin/do_epic/config.py | 29 +++++++++++++++++++-- bin/do_epic/findings.py | 10 +++---- bin/do_epic/finish.py | 22 ++++++++-------- bin/do_epic/human_tasks.py | 16 ++++++------ bin/do_epic/main.py | 16 ++++++------ bin/do_epic/planning.py | 18 ++++++------- bin/do_epic/repo_pick.py | 25 +++++++++++------- bin/do_epic/scheduler.py | 49 ++++++++++++++++++++--------------- bin/do_epic/split.py | 29 ++++++++++++--------- bin/do_epic/status.py | 5 ++-- bin/do_epic/test_do_epic.py | 25 ++++++++++++++++++ bin/do_epic/test_findings.py | 9 +++++++ bin/do_epic/test_finish.py | 21 ++++++++++----- bin/do_epic/test_planning.py | 15 +++++++++++ bin/do_epic/test_repo_pick.py | 35 +++++++++++++++++++------ bin/do_epic/test_scheduler.py | 34 ++++++++++++++++++------ bin/do_epic/test_split.py | 29 ++++++++++++++++++--- bin/do_epic/test_status.py | 2 +- docs/decisions.md | 4 +-- 20 files changed, 278 insertions(+), 119 deletions(-) diff --git a/README.md b/README.md index 250d1d18..800ead37 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ The last line prints each setting's path once the config is complete. `do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic: -- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason. +- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason. A `[label-repos]` table maps each label your team gives an issue to the repo it is worked in, such as `twu-4 = "tenant-web-ui-4"`; do-epic reads such a label as it reads its own `repo:`. Where the team's label is the repo's name, map the name to itself, as in `core-4 = "core-4"`. - `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. `do-epic ` uses it to pick where each open issue without such a label is worked, and records the pick as a label: `repo:` for its repo, `do-epic-claude` for work of Claude's that changes no repo, and `do-epic-human` for a task of yours. Where the rule leaves an issue unclear, do-epic asks you on the terminal. Answer with the label, or with Enter alone to leave the issue waiting. Change a pick by editing the label in Jira. An epic's description states the formula that ranks the issues do-epic files in it: once under `## Scoring`, on a line of its own and inside backticks, such as `` `Score = 100 * V / (2**S + 32)` ``. Without that line do-epic says so and leaves the backlog's order as it is. @@ -192,7 +192,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `command-patterns [] [--calls ]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls ` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys. - `compress-archives` gzips each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them; Install's crontab line runs it daily. - `deploy-release [--cut] []` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says. -- `do-epic ` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. Then it puts the scored issues that do-epic itself filed in order of score. An open issue runs once a label names its repo or marks it as Claude's, in Jira's backlog order, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract. +- `do-epic ` runs the chunks of one Jira epic whose items span repos, or have none, each in its own window of the tmux session `epic-`, on the same cycle, judge and interrupt as loop-claude. The epic's description is its record: goals, audience, scoring and decisions. Before it starts chunks, do-epic plans each open issue that no label places yet, as "Set up a project" says. It files a sub-task per repo where the issue changes several repos. An issue your team filed a sub-task under is left as it is, and worked through those sub-tasks. Otherwise it labels the issue with where it is worked, and asks you where that is unclear. Then it puts the scored issues that do-epic itself filed in order of score. An open issue runs once a label names its repo or marks it as Claude's, in Jira's backlog order, as many at once as a line such as `**Max parallel chunks:** 2` in the epic's description allows, 1 without it, and as each repo's `parallel-chunks` allows. A chunk whose pull request waits on a gate parks. An open task of yours that blocks another issue gets a window that DMs you once and reads the epic every minute; once you close the task, the issues it blocked may start. do-epic closes the epic only once you confirm every goal. Install → "Set up a project" says how to set it up; `do-epic --help` states the flags and the contract. - `do-epic-e2e` runs `do-epic` against a sandbox epic on a real Jira site, as Test says. - `judge-replay [--offline]` replays loop-claude's judge on archived verdicts of the projects run on the model. It prints what each rung a review climbs to misses, and the lowest rung below those that returns every verdict, as each candidate above it does. With `--offline` it doesn't call a judge: it counts what a "?" rule, a decision table and a classifier trained on the archive decide of each verdict's kind from the worker's final message, and how many interrupts each misses. `judge-replay --help` states both replays. - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count and the opening of its round commit's title, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 04f4ed74..ecbbdc17 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -8,18 +8,26 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d clone-folder = "~/code" language = "Swedish" + [label-repos] + twu-4 = "tenant-web-ui-4" + - `jira-url` is the Jira site's address: https, a host, and no path. - `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.claude-projects` and outside the clone folder, which hold git checkouts. `~/.claude-projects/.env` is fine. - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. - `jira-finish-transition` and `jira-finish-status` name the workflow transition that moves a finished chunk's issue and closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic moves no issue to done and closes no epic. +- `[label-repos]` maps a label the team gives an issue to the repo it is worked in, such as `twu-4` to `tenant-web-ui-4`. do-epic reads such a label as it reads its own `repo:`. A team whose label is the repo's name maps the name to itself. - `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank.""" import dataclasses import pathlib import re +import types from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINISH, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE +from do_epic.backend.protocol import LABEL +from do_epic.repo_pick import of_label, REPO_NAME, LabelRepos, REVIEW_LABEL +from do_epic.split import SPLIT_LABEL from failure import Failure from text_files.markdown_text import listed from model_routing.ladder_file import read_ladder, SHIPPED @@ -30,7 +38,8 @@ JIRA_URL = "jira-url" REPOLESS_MODEL = "repoless-model" CLONE_FOLDER = "clone-folder" SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL) -OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH) +LABEL_REPOS = "label-repos" +OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, LABEL_REPOS) LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}." @@ -46,6 +55,19 @@ class DoEpicConfig: repo_rule: str # How a finished epic closes; None where the config doesn't say. finish: Finish | None = None + # The team's own label for a repo, mapped to the repo's name; empty where the config has no LABEL_REPOS table. + label_repos: LabelRepos = types.MappingProxyType({}) + + +def label_repo_faults(table: object) -> list[str]: + """What is wrong with the LABEL_REPOS table: an entry that is no label of a team's mapped to a repo's name.""" + if not isinstance(table, dict): + return [f"`{LABEL_REPOS}` is {table!r}, not a table of labels, such as `twu-4 = \"tenant-web-ui-4\"` under `[{LABEL_REPOS}]`"] + return [ + *(f"`{LABEL_REPOS}` maps {label!r}, a label do-epic gives a meaning of its own" for label in table if of_label(label, {}) is not None or label in (REVIEW_LABEL, SPLIT_LABEL)), + *(f"`{LABEL_REPOS}` maps {label!r}, which Jira takes as no label" for label in table if not LABEL.fullmatch(label)), + *(f"`{LABEL_REPOS}` maps {label!r} to {repo!r}, not a repo's name in letters, digits, dots, hyphens and underscores" for label, repo in table.items() if not (isinstance(repo, str) and REPO_NAME.fullmatch(repo))), + ] def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: @@ -78,10 +100,13 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi *([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []), *([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []), *finish_faults(values), + *label_repo_faults(values.get(LABEL_REPOS, {})), *([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []), ] if faults: return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}") # Without a fault, each value above is present and of the type asserted here. assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str) - return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values)) + labels = values.get(LABEL_REPOS, {}) + assert isinstance(labels, dict) + return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels)) diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py index 54a11837..b2264940 100644 --- a/bin/do_epic/findings.py +++ b/bin/do_epic/findings.py @@ -6,7 +6,7 @@ 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.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX, LabelRepos, REVIEW_LABEL from do_epic.epic_record import EpicRecord from do_epic.backend.protocol import EpicStore from failure import Failure @@ -68,18 +68,18 @@ def parsed(words: list[str]) -> tuple[str, str, tuple[str, ...]] | None: return words[0], rest[0], tuple(labels) -def written(epic: str, flag: str, value: str, labels: tuple[str, ...], store: EpicStore, record: EpicRecord, stdin: typing.TextIO, folder: pathlib.Path) -> str | Failure: +def written(epic: str, flag: str, value: str, labels: tuple[str, ...], store: EpicStore, team: LabelRepos, 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 unread := [label for label in labels if of_label(label) is None and label != REVIEW_LABEL]: + 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 {LABELS}") - if len(picks := [label for label in labels if of_label(label)]) > 1: + 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(epic, value, text, labels) 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 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}.") + return f"Filed {key} in the epic {epic}." + ("" 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: {LABELS}.") try: with decisions_locked(folder): added = record.append_decision(value, text) diff --git a/bin/do_epic/finish.py b/bin/do_epic/finish.py index 8608d37a..f6a42d57 100644 --- a/bin/do_epic/finish.py +++ b/bin/do_epic/finish.py @@ -17,7 +17,7 @@ from do_epic import findings from do_epic.split import finished from text_files.markdown_text import listed from text_files.piped_text import piped -from do_epic.repo_pick import recorded, Repo, REPO_PREFIX, REVIEW_LABEL +from do_epic.repo_pick import recorded, Repo, REPO_PREFIX, LabelRepos, REVIEW_LABEL # Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it. CLOSE = "--close-epic" @@ -38,23 +38,23 @@ def still_open(issues: list[EpicIssue]) -> list[str]: return [issue.key for issue in issues if not finished(issues, issue.key)] -def repo_of(issue: EpicIssue) -> str | None: +def repo_of(issue: EpicIssue, team: LabelRepos) -> str | None: """The name of the repo the issue's labels record; None where they record none.""" - pick = recorded(issue) + pick = recorded(issue, team) return pick.name if isinstance(pick, Repo) else None -def unreviewed(issues: list[EpicIssue]) -> list[str]: +def unreviewed(issues: list[EpicIssue], team: LabelRepos) -> list[str]: """The repos the epic changed that have no release review, sorted. The epic changed a repo where a done issue names it, and a repo has its review once an issue labelled REVIEW_LABEL names it, open or done.""" - reviewed = {repo_of(issue) for issue in issues if REVIEW_LABEL in issue.labels} - changed = {repo_of(issue) for issue in issues if issue.done and REVIEW_LABEL not in issue.labels} + reviewed = {repo_of(issue, team) for issue in issues if REVIEW_LABEL in issue.labels} + changed = {repo_of(issue, team) for issue in issues if issue.done and REVIEW_LABEL not in issue.labels} return sorted(repo for repo in changed - reviewed if repo is not None) -def task(epic: str, issues: list[EpicIssue], launcher: pathlib.Path, language: str) -> str: +def task(epic: str, issues: list[EpicIssue], team: LabelRepos, launcher: pathlib.Path, language: str) -> str: """The finishing chunk's task, for the epic with the key epic as issues has it. launcher is the do-epic that runs the chunk, and language the one the epic's Jira text is in.""" opening = f"Finish the epic {epic}, which holds no open issue, as one chunk that changes no repo: work in the folder you start in." - if lacking := unreviewed(issues): + if lacking := unreviewed(issues, team): return ( f"{opening} Each repo the epic changed takes a release review first, and {listed(lacking, 'and')} {'has' if len(lacking) == 1 else 'have'} none. " f"File one issue per such repo, with `{launcher} {epic} {findings.FILE} \"\" {findings.LABEL} {REPO_PREFIX} {findings.LABEL} {REVIEW_LABEL}` and its detail on stdin, both in {language}, the epic's language. " @@ -71,11 +71,11 @@ def task(epic: str, issues: list[EpicIssue], launcher: pathlib.Path, language: s f"3. Once the human has confirmed every goal, write a summary in {language}, the epic's language, for the people who work the epic: what shipped in each repo, and each goal's evidence. " f"Post it and close the epic with `{launcher} {epic} {CLOSE}`, the summary on stdin. That is the chunk's very last step, and the chunk is finished once it succeeds.\n\n" f"{findings.instructions(epic, launcher, language)} Record each goal's confirmation as such a decision.\n\n" - "The epic's issues, each done:\n\n" + "\n".join(f"- {issue.key}{f' ({repo})' if (repo := repo_of(issue)) else ''}: {issue.summary}" for issue in issues) + "The epic's issues, each done:\n\n" + "\n".join(f"- {issue.key}{f' ({repo})' if (repo := repo_of(issue, team)) else ''}: {issue.summary}" for issue in issues) ) -def closed(epic: str, store: EpicStore, stdin: typing.TextIO) -> str | Failure: +def closed(epic: str, store: EpicStore, team: LabelRepos, stdin: typing.TextIO) -> str | Failure: """Posts the summary piped in on the epic with the key epic and closes it, and answers the line to print; a Failure, with nothing posted, while the epic isn't ready to close.""" # Whether the human confirmed each goal isn't checked here: a decision that records it is the worker's own text, so only the task and the judge, who reads the human's answers, can hold the worker to it. issues = store.read() @@ -86,7 +86,7 @@ def closed(epic: str, store: EpicStore, stdin: typing.TextIO) -> str | Failure: return Failure(f"cannot close the epic {epic}: {already.reason if isinstance(already, Failure) else 'it is closed already'}") if waiting := still_open(issues): return Failure(f"cannot close the epic {epic}: {listed(waiting, 'and')} {'is' if len(waiting) == 1 else 'are'} open") - if lacking := unreviewed(issues): + if lacking := unreviewed(issues, team): return Failure(f"cannot close the epic {epic}: no issue labelled {REVIEW_LABEL} reviews {listed(lacking, 'or')}") done = store.close(piped(stdin)) return Failure(f"cannot close the epic {epic}: {done.reason}") if isinstance(done, Failure) else f"Posted the summary on the epic {epic} and closed it." diff --git a/bin/do_epic/human_tasks.py b/bin/do_epic/human_tasks.py index 2eff5f23..5ef39162 100644 --- a/bin/do_epic/human_tasks.py +++ b/bin/do_epic/human_tasks.py @@ -7,7 +7,7 @@ from project_config.settings import by_name, ProjectConfig from loop_effects.effects import Effects, say from do_epic.backend.protocol import EpicIssue, EpicStore from failure import Failure -from do_epic.repo_pick import recorded, Repo +from do_epic.repo_pick import recorded, Repo, LabelRepos from do_epic import scheduler from agent_cycle.direct_message import tell from agent_cycle import tmux @@ -16,9 +16,9 @@ from agent_cycle import tmux AWAITS = "a human's task" -def holds_up(key: str, issues: list[EpicIssue]) -> list[str]: +def holds_up(key: str, issues: list[EpicIssue], team: LabelRepos) -> list[str]: """The keys of the open issues that the human's task called key holds up; none where it is no such task, is closed, or an issue blocks it.""" - if not any(chunk.human and chunk.issue == key for chunk in scheduler.chunks(issues)[0]): + if not any(chunk.human and chunk.issue == key for chunk in scheduler.chunks(issues, team)[0]): return [] return scheduler.held_up(issues)[key] @@ -27,17 +27,17 @@ def message(task: EpicIssue, epic: str, held: list[str]) -> str: return f"do-epic {epic} awaits you: {task.key}, \"{task.summary}\", blocks {' and '.join(held)}. do-epic goes on once you close {task.key} in Jira." -def notifier_checkout(issues: list[EpicIssue], home: pathlib.Path) -> str | None: +def notifier_checkout(issues: list[EpicIssue], team: LabelRepos, home: pathlib.Path) -> str | None: """The checkout of the first of issues whose repo has a git checkout and a project config that names a notifier: where the DM finds that notifier, since the window runs in no checkout. None where there is none.""" for issue in issues: - pick = recorded(issue) + pick = recorded(issue, team) found = by_name(pick.name, home) if isinstance(pick, Repo) else None if isinstance(found, ProjectConfig) and found.notifier and (found.top / ".git").exists(): return str(found.top) return None -def awaited(task: EpicIssue, epic: str, store: EpicStore, window: tmux.Window, poll: int, home: pathlib.Path, effects: Effects) -> None: +def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, window: tmux.Window, poll: int, home: pathlib.Path, effects: Effects) -> None: """Waits in window for the human to close the human's task `task` of the epic called epic, and returns once it no longer holds up any issue. A read of the epic that fails is said once and tried again.""" tmux.park(window, AWAITS, effects.tmux) told, said = False, None @@ -47,13 +47,13 @@ def awaited(task: EpicIssue, epic: str, store: EpicStore, window: tmux.Window, p if issues.reason != said: say(f"cannot read the epic, so cannot tell whether {task.key} is closed; trying again every {poll} seconds: {issues.reason}", effects, stdout=True) said = issues.reason - elif not (held := holds_up(task.key, issues)): + elif not (held := holds_up(task.key, issues, team)): return elif not told: text = message(task, epic, held) say(text, effects, stdout=True) # The issues it holds up come first; any other issue of the epic may do where they have no repo with a notifier. - where = notifier_checkout(sorted(issues, key=lambda issue: issue.key not in held), home) + where = notifier_checkout(sorted(issues, key=lambda issue: issue.key not in held), team, home) if where is None: say("no DM went out: no issue of the epic has a repo whose project config names a notifier and whose checkout exists", effects, stdout=True) told = where is None or tell(text, effects, where) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 0fa60304..1ade4c6f 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -139,7 +139,7 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: def status_printed(epic: EpicRun) -> Stop: """What `do-epic --status` does: prints a line per open issue, and doesn't start anything.""" issues = epic.store.read() - lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.effects.tmux) + lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.config.label_repos, epic.effects.tmux) 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") @@ -149,7 +149,7 @@ def epic_written(key: str, writes: tuple[str, str, tuple[str, ...]] | None, path if isinstance(config, Failure): return Stop(1, config.reason) store, record = backend(config, key) - done = findings.written(key, *writes, store, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, stdin) + done = findings.written(key, *writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin) return Stop(1, done.reason) if isinstance(done, Failure) else Stop(0, done) @@ -208,7 +208,7 @@ def scheduled_epic(epic: EpicRun) -> scheduler.Epic | Failure: seen.append(found.checkout) return real(found.checkout), found.config.parallel_chunks - return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env) + return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos) @dataclasses.dataclass(frozen=True) @@ -244,8 +244,8 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: issue = None if key == epic.key else issue_read(key, epic) if isinstance(issue, Stop): return issue - if issue and isinstance(recorded(issue), HumanTask): - human_tasks.awaited(issue, epic.key, epic.store, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects) + if issue and isinstance(recorded(issue, epic.config.label_repos), HumanTask): + human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects) return handed_on(key, epic) place = chunk_root(key, issue, epic) if isinstance(place, Stop): @@ -355,7 +355,7 @@ def issue_read(key: str, epic: EpicRun) -> EpicIssue | Stop: def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, str | None] | Stop: """The folder the chunk called key works in, and the name of the repo whose checkout it is: None for the epic's folder, which holds work without a repo, as the epic's finishing is. issue is None for the epic's finishing. The chunk keeps both to its end, whatever its issue's labels become. The stop where the labels make the issue no chunk.""" - pick = recorded(issue) if issue else ClaudeWork() + pick = recorded(issue, epic.config.label_repos) if issue else ClaudeWork() if isinstance(pick, Failure): return Stop(1, pick.reason) if isinstance(pick, ClaudeWork): @@ -399,7 +399,7 @@ def handed_on(key: str, epic: EpicRun) -> Stop: def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue] | Stop: """The issues, with each item split by repo whose sub-tasks are all done moved to done in the tracker and read as done; the stop where one cannot move. Its last sub-task to finish closes it, and one an earlier run left open closes with it.""" for item in issues: - if split.SPLIT_LABEL in item.labels and not item.done and split.finished(issues, item.key): + if split.is_split(item, issues) and not item.done and split.finished(issues, item.key): moved = epic.store.finish_issue(item.key) if isinstance(moved, Failure): return Stop(1, f"the chunk finished, but its split item {item.key} could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") @@ -451,7 +451,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> return Stop(1, issues.reason) if not finish.due(issues): return EpicReopened() - return finish.task(epic.key, issues, epic.launcher, language), None + return finish.task(epic.key, issues, epic.config.label_repos, epic.launcher, language), None def repoless_models(epic: EpicRun) -> Models: diff --git a/bin/do_epic/planning.py b/bin/do_epic/planning.py index 201c9099..57fb203f 100644 --- a/bin/do_epic/planning.py +++ b/bin/do_epic/planning.py @@ -44,8 +44,8 @@ class Planned: def planned(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Failure | Limited | None]: """The epic's issues as far as they are planned, and why the planning stopped early, None where it didn't. issues are the epic's, as just read. - Each open child issue that no label places is split or gets its pick. Then the issues do-epic filed are re-ranked. What was labelled, filed or ranked before a Failure or a Limited stays, and the issues returned show it.""" - unplaced = [issue for issue in issues if issue.parent == epic.key and not issue.done and split.SPLIT_LABEL not in issue.labels and repo_pick.recorded(issue) is None] + Each open child issue that no label places, and that isn't split already, is split or gets its pick. Then the issues do-epic filed are re-ranked. What was labelled, filed or ranked before a Failure or a Limited stays, and the issues returned show it.""" + unplaced = [issue for issue in issues if issue.parent == epic.key and not issue.done and not split.is_split(issue, issues) and repo_pick.recorded(issue, epic.config.label_repos) is None] added: dict[str, str] = {} stopped = placed(epic, issues, unplaced, added) if unplaced else None if added: @@ -79,7 +79,7 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad rung = planning_rung(epic.config.repoless_model) language = epic.record.language() # Claude reads every repo a label of the epic names, a finished issue's too, to predict which of them an issue changes. - places = located(epic, [repo for issue in issues if isinstance(repo := repo_pick.recorded(issue), repo_pick.Repo)]) + places = located(epic, [repo for issue in issues if isinstance(repo := repo_pick.recorded(issue, epic.config.label_repos), repo_pick.Repo)]) if failed := next((each for each in (rung, language, places) if isinstance(each, Failure)), None): return failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(places, dict) @@ -88,12 +88,12 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad checkouts = tuple(str(place.checkout) for place in places.values()) for issue in unplaced: say(f"planning {issue.key}", epic.effects, stdout=True) - parts = split.split(epic.store, issue, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder)) + parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder)) if isinstance(parts, split.Split) and parts.repos: added[issue.key] = split.SPLIT_LABEL say(f"{issue.key} is split into a sub-task for each of {', '.join(parts.repos)}", epic.effects, stdout=True) continue - pick: repo_pick.Pick | repo_pick.Unclear | Failure | Limited | None = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, epic.config.repo_rule, rung, epic.effects.claude, str(folder)) + pick: repo_pick.Pick | repo_pick.Unclear | Failure | Limited | None = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, epic.config.label_repos, epic.config.repo_rule, rung, epic.effects.claude, str(folder)) if isinstance(pick, repo_pick.Unclear): pick = answered(epic, issue, pick.question) if isinstance(pick, Limited): @@ -131,10 +131,10 @@ def answered(epic: Planned, issue: EpicIssue, question: str) -> repo_pick.Pick | label = typed.strip() if not label: return None - pick = repo_pick.of_label(label) + pick = repo_pick.of_label(label, epic.config.label_repos) if pick is not None: return repo_pick.record(epic.store, issue, pick) - named = f"; the repo {label}'s label is `{repo_pick.REPO_PREFIX}{label}`" if repo_pick.of_label(repo_pick.REPO_PREFIX + label) else "" + named = f"; the repo {label}'s label is `{repo_pick.REPO_PREFIX}{label}`" if repo_pick.of_label(repo_pick.REPO_PREFIX + label, {}) else "" say(f"`{label}` is none of those labels{named}", epic.effects) @@ -153,7 +153,7 @@ def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure: """The keys of the open child issues do-epic filed that hold scores and one pick, in the order ranking gives them; empty where fewer than two do, since one issue has no order. Every other issue keeps its position: a person's issue, one nobody scored, one with no pick yet or with two, and an item split by repo, since several repos' goals would score it.""" - ours = [issue for issue in issues if issue.parent == epic.key and issue.by_loop and not issue.done and split.SPLIT_LABEL not in issue.labels and (pick := repo_pick.recorded(issue)) is not None and not isinstance(pick, Failure) and not ranking.unscored(item_of(issue, {}), issue.key)] + ours = [issue for issue in issues if issue.parent == epic.key and issue.by_loop and not issue.done and not split.is_split(issue, issues) and (pick := repo_pick.recorded(issue, epic.config.label_repos)) is not None and not isinstance(pick, Failure) and not ranking.unscored(item_of(issue, {}), issue.key)] if len(ours) < 2: return [] numbers = {issue.key: number(issue.key) for issue in ours} @@ -167,7 +167,7 @@ def ranked_keys(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure: formulas = FORMULA.findall(scoring) if len(formulas) != 1: return Failure(f"the epic {epic.key}'s description states `Score = ...` {len(formulas)} times under ## Scoring; state the formula that ranks its issues once, on a line of its own and inside backticks, such as `Score = 100 * V / (2**S + 32)`") - picks = {issue.key: repo_pick.recorded(issue) for issue in ours} + picks = {issue.key: repo_pick.recorded(issue, epic.config.label_repos) for issue in ours} places = located(epic, [pick for pick in picks.values() if isinstance(pick, repo_pick.Repo)]) if isinstance(places, Failure): return places diff --git a/bin/do_epic/repo_pick.py b/bin/do_epic/repo_pick.py index 75fe6431..be040d53 100644 --- a/bin/do_epic/repo_pick.py +++ b/bin/do_epic/repo_pick.py @@ -4,6 +4,7 @@ An item is worked in a repo, or has no repo and is either Claude's work, done wi import dataclasses import json import re +import typing from claude_code.reply import Claude, claude_reply, Limited from do_epic.backend.protocol import EpicIssue, EpicStore @@ -20,6 +21,9 @@ REVIEW_LABEL = "do-epic-release-review" # A repo's name is a folder name and part of a clone address, so claude's answer or a label a person typed must not hold a slash, a colon or a leading dot. REPO_NAME = re.compile(r"\w[\w.-]*") +# A team's own label for a repo, mapped to the repo's name: the `[label-repos]` table of do-epic's config (config.py). Three readers, seated as those who write and read that config, picked `label-repos` from four candidates, over `repo-aliases`, `repo-labels` and `team-labels`, 2-1; each would misread `repo-labels` as mapping a repo to its label. +LabelRepos = typing.Mapping[str, str] + PICK_SCHEMA = { "type": "object", "properties": { @@ -61,15 +65,18 @@ def label_of(pick: Pick) -> str: return f"{REPO_PREFIX}{pick.name}" if isinstance(pick, Repo) else CLAUDE_LABEL if isinstance(pick, ClaudeWork) else HUMAN_LABEL -def recorded(issue: EpicIssue) -> Pick | None | Failure: - """The pick the issue's labels record; None where they record no pick, a Failure where they record more than one.""" - picks = [pick for label in issue.labels if (pick := of_label(label)) is not None] - if len(picks) > 1: - return Failure(f"{issue.key} is labelled with {len(picks)} picks: {', '.join(label_of(pick) for pick in picks)}; remove all but the right one") - return picks[0] if picks else None +def recorded(issue: EpicIssue, team: LabelRepos) -> Pick | None | Failure: + """The pick the issue's labels record; None where they record no pick, a Failure where they record more than one. Two labels that name one repo, such as the team's and `repo:`, record one pick.""" + picks = {label: pick for label in issue.labels if (pick := of_label(label, team)) is not None} + if len(set(picks.values())) > 1: + return Failure(f"{issue.key} is labelled with {len(picks)} picks: {', '.join(picks)}; remove all but the right one") + return next(iter(picks.values()), None) -def of_label(label: str) -> Pick | None: +def of_label(label: str, team: LabelRepos) -> Pick | None: + """The pick the label records: one of do-epic's own, or one the team's table maps to a repo.""" + if label in team: + return Repo(team[label]) if label == CLAUDE_LABEL: return ClaudeWork() if label == HUMAN_LABEL: @@ -77,9 +84,9 @@ def of_label(label: str) -> Pick | None: return Repo(label[len(REPO_PREFIX):]) if label.startswith(REPO_PREFIX) and REPO_NAME.fullmatch(label[len(REPO_PREFIX):]) else None -def picked(store: EpicStore, issue: EpicIssue, rule: str, rung: Rung, claude: Claude, cwd: str) -> Pick | Unclear | Failure | Limited: +def picked(store: EpicStore, issue: EpicIssue, team: LabelRepos, rule: str, rung: Rung, claude: Claude, cwd: str) -> Pick | Unclear | Failure | Limited: """The pick for a child issue of the epic: the one its labels record, else claude's by rule, recorded on the issue. An unclear pick is not recorded; the human's answer is, with record.""" - known = recorded(issue) + known = recorded(issue, team) if known is not None: return known reply = claude_reply(claude, ["--json-schema", json.dumps(PICK_SCHEMA), *rung.flags(), "--tools", ""], cwd, prompt(rule, issue), "the repo pick") diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 8109a4e9..dae39991 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -9,11 +9,11 @@ from do_epic.epic_record import CAP from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_chunks, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure -from do_epic.repo_pick import HumanTask, recorded, Repo +from do_epic.repo_pick import HumanTask, Pick, recorded, Repo, LabelRepos from project_config.settings import PARALLEL_CHUNKS from do_epic.parked import parked_chunks from chunk_pr.approval import PARKS -from do_epic.split import SPLIT_LABEL +from do_epic.split import is_split from agent_cycle import tmux # Under the home folder, a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. @@ -71,6 +71,8 @@ class Epic: # The do-epic script each window runs. launcher: pathlib.Path env: typing.Mapping[str, str] + # The team's own labels for its repos. + team: LabelRepos @property def folder(self) -> pathlib.Path: @@ -88,39 +90,44 @@ def held_up(issues: list[EpicIssue]) -> dict[str, list[str]]: by_key = {issue.key: issue for issue in issues} held: dict[str, list[str]] = {} for issue in issues: - if not issue.done and SPLIT_LABEL not in issue.labels: + if not issue.done and not is_split(issue, issues): for key in open_blockers(issue, by_key): held.setdefault(key, []).append(issue.key) return held -def chunks(issues: list[EpicIssue]) -> tuple[list[Chunk], list[Waits]]: - """The open issues to work as chunks, in the tracker's rank order, and those that wait. An item split by repo is worked through its sub-tasks, and what blocks it blocks them. A blocker outside the epic blocks until the human removes the link, since its state is unknown. A human's task gets a window only while it holds up another issue and nothing holds it up; that window waits for the human.""" +def chunks(issues: list[EpicIssue], team: LabelRepos) -> tuple[list[Chunk], list[Waits]]: + """The open issues to work as chunks, in the tracker's rank order, and those that wait. A split item is worked through its sub-tasks, and what blocks it blocks them. team maps the team's own labels to repos.""" by_key = {issue.key: issue for issue in issues} holding = held_up(issues) found: list[Chunk] = [] waits: list[Waits] = [] for issue in issues: - if issue.done or SPLIT_LABEL in issue.labels: + if issue.done or is_split(issue, issues): continue - pick = recorded(issue) - blocking = open_blockers(issue, by_key) - outside = [key for key in blocking if key not in by_key] - if isinstance(pick, Failure): - waits.append(Waits(issue.key, pick.reason)) - elif pick is None: - waits.append(Waits(issue.key, "no label names its repo")) - elif isinstance(pick, HumanTask) and not blocking and issue.key in holding: - found.append(Chunk(issue.key, None, human=True)) - elif isinstance(pick, HumanTask): - waits.append(Waits(issue.key, "it is a human's task")) - elif blocking: - waits.append(Waits(issue.key, f"{' and '.join(blocking)} block{'s' if len(blocking) == 1 else ''} it" + (f"; do-epic cannot see {' and '.join(outside)}, outside the epic, finish: remove such a link in Jira once its issue is done" if outside else ""))) + turn = turn_of(issue, recorded(issue, team), open_blockers(issue, by_key), by_key, issue.key in holding) + if isinstance(turn, Chunk): + found.append(turn) else: - found.append(Chunk(issue.key, pick.name if isinstance(pick, Repo) else None)) + waits.append(turn) return found, waits +def turn_of(issue: EpicIssue, pick: Pick | None | Failure, blocking: list[str], by_key: dict[str, EpicIssue], holds: bool) -> Chunk | Waits: + """The open issue's chunk, or why it waits. blocking are its open blockers, and holds says it holds up another open issue. A human's task gets a window only while it holds up another issue and nothing holds it up; that window waits for the human. A blocker outside the epic blocks until the human removes the link, since its state is unknown.""" + if isinstance(pick, Failure): + return Waits(issue.key, pick.reason) + if pick is None: + return Waits(issue.key, "no label names its repo") + if isinstance(pick, HumanTask): + return Chunk(issue.key, None, human=True) if holds and not blocking else Waits(issue.key, "it is a human's task") + if blocking: + outside = [key for key in blocking if key not in by_key] + unseen = f"; do-epic cannot see {' and '.join(outside)}, outside the epic, finish: remove such a link in Jira once its issue is done" if outside else "" + return Waits(issue.key, f"{' and '.join(blocking)} block{'s' if len(blocking) == 1 else ''} it{unseen}") + return Chunk(issue.key, pick.name if isinstance(pick, Repo) else None) + + def refusal(repo: str, room: RepoRoom) -> str | None: """Why the repo takes no further chunk; None where it takes one.""" if room.loop_claude: @@ -133,7 +140,7 @@ def refusal(repo: str, room: RepoRoom) -> str | None: def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, 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. Where finishing is set, no issue is open, and the one chunk to start is the epic's finishing (finish.py), in a window named for the epic's key. own is the key of the chunk that asks, which has finished or parked: it counts as running nowhere, and no stopped chunk starts again. Where own is None, the human's `do-epic ` asks, and each stopped chunk starts again. A parked chunk waits in its window; one without a live window, as after a reboot, starts again as a stopped chunk does, whatever the limits, since it goes on parked. A Failure says why a window could not start; those before it run.""" session = tmux.session_name(tmux.EPIC, epic.key) - found, waits = chunks(issues) + found, waits = chunks(issues, epic.team) if finishing: found.append(Chunk(epic.key, None)) started: list[str] = [] diff --git a/bin/do_epic/split.py b/bin/do_epic/split.py index 5332249a..01c58026 100644 --- a/bin/do_epic/split.py +++ b/bin/do_epic/split.py @@ -7,7 +7,7 @@ import json from claude_code.reply import Claude, claude_reply, Limited from do_epic.backend.protocol import EpicIssue, EpicStore from failure import Failure -from do_epic.repo_pick import label_of, of_label, Repo, REPO_NAME +from do_epic.repo_pick import label_of, of_label, Repo, REPO_NAME, LabelRepos from model_routing.ladder import Rung from claude_code.entries import structured_output @@ -59,22 +59,27 @@ class Split: tasks: tuple[str, ...] -def split(store: EpicStore, issue: EpicIssue, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str) -> Split | Failure | Limited: - """Splits the epic's child issue into a sub-task per repo it changes, where that is more than one. by_person says a person filed the issue, and checkouts are the epic's repos that claude may read. An item that changes one repo or none is left as it is, for repo_pick, and one already marked SPLIT_LABEL is left alone. +def is_split(item: EpicIssue, issues: list[EpicIssue]) -> bool: + """Whether the item is worked through its sub-tasks: it is marked SPLIT_LABEL, or a person filed a sub-task under it. A sub-task do-epic filed doesn't count without the mark, since a run that failed between the two leaves the next run to file the lacking ones.""" + return SPLIT_LABEL in item.labels or any(task.parent == item.key and not task.by_loop for task in issues) - A sub-task of the item already labelled for a repo counts as that repo's, so a run that failed after filing some sub-tasks, or a person's own sub-task, leaves the next run to file only the lacking ones. The comment on a person's issue is posted once its sub-tasks are filed, just before the item is marked. A failure after the comment but before the mark posts it again on the next run.""" - if SPLIT_LABEL in issue.labels: + +def split(store: EpicStore, issue: EpicIssue, team: LabelRepos, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str) -> Split | Failure | Limited: + """Splits the epic's child issue into a sub-task per repo it changes, where that is more than one. by_person says a person filed the issue, and checkouts are the epic's repos that claude may read. An item that changes one repo or none is left as it is, for repo_pick, and one already split (is_split) is left alone. + + A sub-task of the item already labelled for a repo counts as that repo's, so a run that failed after filing some sub-tasks leaves the next run to file only the lacking ones. The comment on a person's issue is posted once its sub-tasks are filed, just before the item is marked. A failure after the comment but before the mark posts it again on the next run.""" + read = store.read() + if isinstance(read, Failure): + return read + if is_split(issue, read): return Split((), ()) predicted = prediction(issue, by_person, rule, language, checkouts, rung, claude, cwd) if isinstance(predicted, Failure | Limited): return predicted - read = store.read() - if isinstance(read, Failure): - return read - have = {pick.name for task in read if task.parent == issue.key for label in task.labels if isinstance(pick := of_label(label), Repo)} + have = {pick.name for task in read if task.parent == issue.key for label in task.labels if isinstance(pick := of_label(label, team), Repo)} repos = tuple(dict.fromkeys([*sorted(have), *(part.repo for part in predicted.parts)])) if len(repos) < 2: - # Left as it is even where an earlier, failed run filed one sub-task and this prediction names only that repo: marking the item split would make a person's own sub-task for one repo turn their ordinary issue into a tracking parent. The stray sub-task is labelled for its repo and harmless. + # Left as it is even where an earlier, failed run filed one sub-task and this prediction names only that repo. The stray sub-task is labelled for its repo and harmless. return Split((), ()) if by_person and not predicted.comment: return Failure("the repo split gave no comment for the team on a person's issue") @@ -106,12 +111,12 @@ def task_summary(repo: str, summary: str) -> str: def finished(issues: list[EpicIssue], key: str) -> bool: - """Whether the item named key is done. An item marked SPLIT_LABEL that has sub-tasks is done once each of them is, whatever its own status; any other item is done by its own status, and a key no issue has isn't done.""" + """Whether the item named key is done. A split item (is_split) that has sub-tasks is done once each of them is, whatever its own status; any other item is done by its own status, and a key no issue has isn't done.""" item = next((issue for issue in issues if issue.key == key), None) tasks = [issue for issue in issues if issue.parent == key] if item is None: return False - return all(task.done for task in tasks) if SPLIT_LABEL in item.labels and tasks else item.done + return all(task.done for task in tasks) if is_split(item, issues) and tasks else item.done def prediction(issue: EpicIssue, by_person: bool, rule: str, language: str, checkouts: tuple[str, ...], rung: Rung, claude: Claude, cwd: str) -> Prediction | Failure | Limited: diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py index be8bfe01..846d2f9e 100644 --- a/bin/do_epic/status.py +++ b/bin/do_epic/status.py @@ -2,6 +2,7 @@ import datetime import pathlib +from do_epic.repo_pick import LabelRepos from do_epic.scheduler import chunks, HUMAN_WAIT, STATE from do_epic.backend.protocol import EpicIssue from failure import Failure @@ -17,9 +18,9 @@ def since(folder: pathlib.Path, chunk: Parked) -> str: return "" -def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], run: tmux.Tmux) -> list[str] | Failure: +def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, run: tmux.Tmux) -> list[str] | Failure: """A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. It doesn't start anything or check any limit, so the line of a chunk that has yet to start doesn't say which limit holds it back.""" - found, waits = chunks(issues) + found, waits = chunks(issues, team) folder = home / STATE / key parked = parked_chunks(folder) if isinstance(parked, Failure): diff --git a/bin/do_epic/test_do_epic.py b/bin/do_epic/test_do_epic.py index c4881bb6..a581f50f 100644 --- a/bin/do_epic/test_do_epic.py +++ b/bin/do_epic/test_do_epic.py @@ -38,6 +38,31 @@ class ConfigTest(unittest.TestCase): self.write() self.assertEqual(load(self.home), DoEpicConfig(self.folder, "https://acme.atlassian.net", self.home / "jira.env", self.home / "code", "English", "claude-opus-5-5", "A label that equals a repo's name names that repo.\n")) + def test_reads_the_teams_labels_for_its_repos(self) -> None: + self.write(SETTINGS + '[label-repos]\ntwu-4 = "tenant-web-ui-4"\n"core-4" = "core-4"\n') + found = load(self.home) + assert isinstance(found, DoEpicConfig), found + self.assertEqual(dict(found.label_repos), {"twu-4": "tenant-web-ui-4", "core-4": "core-4"}) + + def test_names_each_entry_that_is_no_label_mapped_to_a_repo(self) -> None: + self.write(SETTINGS + '[label-repos]\n"repo:api" = "api"\ndo-epic-human = "api"\nsplit-by-repo = "api"\ndo-epic-release-review = "api"\n"two words" = "api"\nweb = "../web"\ncore = 4\n') + reason = self.failure() + for fault in ( + "`label-repos` maps 'repo:api', a label do-epic gives a meaning of its own", + "`label-repos` maps 'do-epic-human', a label do-epic gives a meaning of its own", + "`label-repos` maps 'split-by-repo', a label do-epic gives a meaning of its own", + "`label-repos` maps 'do-epic-release-review', a label do-epic gives a meaning of its own", + "`label-repos` maps 'two words', which Jira takes as no label", + "`label-repos` maps 'web' to '../web', not a repo's name in letters, digits, dots, hyphens and underscores", + "`label-repos` maps 'core' to 4, not a repo's name", + ): + self.assertIn(fault, reason) + self.assertEqual(reason.count("`label-repos` maps"), 7) + + def test_refuses_a_label_repos_that_is_no_table(self) -> None: + self.write('label-repos = "twu-4"\n' + SETTINGS) + self.assertIn("`label-repos` is 'twu-4', not a table of labels, such as `twu-4 = \"tenant-web-ui-4\"` under `[label-repos]`", self.failure()) + def test_reads_a_clone_folder_and_language_the_config_sets(self) -> None: self.write(SETTINGS + 'clone-folder = "/srv/repos"\nlanguage = "Brazilian Portuguese"\n') found = load(self.home) diff --git a/bin/do_epic/test_findings.py b/bin/do_epic/test_findings.py index a9dab106..0f34197e 100644 --- a/bin/do_epic/test_findings.py +++ b/bin/do_epic/test_findings.py @@ -83,6 +83,15 @@ class FilingAFinding(FindingsTest): 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_a_label_of_the_teams_says_where_the_issue_is_worked(self) -> None: + with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + config.write('\n[label-repos]\ntwu-4 = "tenant-web-ui-4"\n') + code, out, _, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", "twu-4"]) + filed = self.store.issues[-1] + self.assertEqual((code, out, filed.labels), (0, f"Filed {filed.key} in the epic ABC-12.\n", ("twu-4",))) + code, _, err, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", "twu-4", "--label", "repo:api"]) + self.assertEqual((code, err), (1, "cannot file the finding in the epic ABC-12: twu-4 and repo:api each say who works it; write one of them\n")) + def test_a_release_review_takes_its_label_beside_its_repo(self) -> None: code, out, _, _ = self.run_with(["ABC-12", "--file", "Review api", "--label", "repo:api", "--label", "do-epic-release-review"]) filed = self.store.issues[-1] diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 7ead16b2..4f819cb9 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -35,24 +35,31 @@ class WhenTheFinishingIsDue(DoEpicTest): def test_a_repo_lacks_its_review_while_a_done_issue_names_it_and_no_review_does(self) -> None: done = [issue("ABC-20", "repo:web", done=True), issue("ABC-21", "repo:api", done=True), issue("ABC-22", "do-epic-claude", done=True), issue("ABC-23", "repo:docs")] - self.assertEqual(finish.unreviewed(done), ["api", "web"]) - self.assertEqual(finish.unreviewed([*done, issue("ABC-30", "repo:api", "do-epic-release-review")]), ["web"]) - self.assertEqual(finish.unreviewed([issue("ABC-30", "repo:api", "do-epic-release-review", done=True)]), [], "a review alone changes no repo") + self.assertEqual(finish.unreviewed(done, {}), ["api", "web"]) + self.assertEqual(finish.unreviewed([*done, issue("ABC-30", "repo:api", "do-epic-release-review")], {}), ["web"]) + self.assertEqual(finish.unreviewed([issue("ABC-30", "repo:api", "do-epic-release-review", done=True)], {}), [], "a review alone changes no repo") + + def test_a_label_of_the_teams_names_the_repo_a_done_issue_changed_and_a_review_covers(self) -> None: + team = {"twu-4": "tenant-web-ui-4"} + done = [issue("ABC-20", "twu-4", done=True)] + self.assertEqual(finish.unreviewed(done, team), ["tenant-web-ui-4"]) + self.assertEqual(finish.unreviewed([*done, issue("ABC-30", "repo:tenant-web-ui-4", "do-epic-release-review")], team), []) + self.assertIn("- ABC-20 (tenant-web-ui-4): ", finish.task("ABC-12", [*done, issue("ABC-30", "repo:tenant-web-ui-4", "do-epic-release-review", done=True)], team, LAUNCHER, "Swedish")) class TheFinishingChunksTask(DoEpicTest): def test_first_asks_for_one_review_issue_per_repo_that_lacks_one(self) -> None: - task = finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "repo:web", done=True)], LAUNCHER, "Swedish") + task = finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True), issue("ABC-21", "repo:web", done=True)], {}, LAUNCHER, "Swedish") self.assertIn("Finish the epic ABC-12", task) self.assertIn("first, and api and web have none. ", task) - self.assertIn("first, and api has none. ", finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True)], LAUNCHER, "Swedish")) + self.assertIn("first, and api has none. ", finish.task("ABC-12", [issue("ABC-20", "repo:api", done=True)], {}, LAUNCHER, "Swedish")) self.assertIn('`/b/do-epic ABC-12 --file "" --label repo: --label do-epic-release-review`', task) self.assertIn("`Release review of ABC-12`", task) self.assertIn("in Swedish", task) self.assertNotIn("--close-epic", task) def test_then_has_the_human_confirm_each_goal_before_the_summary_and_the_closing(self) -> None: - task = finish.task("ABC-12", REVIEWED, LAUNCHER, "Swedish") + task = finish.task("ABC-12", REVIEWED, {}, LAUNCHER, "Swedish") self.assertIn("Finish the epic ABC-12", task) self.assertIn("A goal is met only where the human confirms it", task) self.assertIn("ask the human to approve the set", task) @@ -99,7 +106,7 @@ class ClosingTheEpic(DoEpicTest): def closed(self) -> Failure: return Failure("Jira answered 503") - self.assertEqual(finish.closed("ABC-12", Unreadable("ABC-12", list(REVIEWED)), io.StringIO("Shipped.")), Failure("cannot close the epic ABC-12: Jira answered 503")) + self.assertEqual(finish.closed("ABC-12", Unreadable("ABC-12", list(REVIEWED)), {}, io.StringIO("Shipped.")), Failure("cannot close the epic ABC-12: Jira answered 503")) def test_the_jira_backend_closes_an_epic_by_the_transition_the_settings_name(self) -> None: with open(self.home / ".claude-projects/do-epic/config.toml", "a", encoding="utf-8") as settings: diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index 2f8e9ef9..2b4513a9 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -56,6 +56,21 @@ class Planning(DoEpicTest): found, _, out = self.plan(fake) self.assertEqual((found, out, fake.made("claude")), (self.issues, "", [])) + def test_an_epic_shaped_as_a_teams_is_planned_without_claude_and_without_a_write(self) -> None: + with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + config.write('\n[label-repos]\ntwu-4 = "tenant-web-ui-4"\ncore-4 = "core-4"\n') + self.issues = [ + issue("ABC-19", "twu-4"), + issue("ABC-20"), + issue("ABC-23", "core-4", parent="ABC-20"), + issue("ABC-24", "twu-4", parent="ABC-20"), + issue("ABC-21", "urgent"), + issue("ABC-25", "core-4", parent="ABC-21"), + ] + fake = FakeEffects() + found, store, out = self.plan(fake) + self.assertEqual((found, store.issues, out, fake.made("claude")), (self.issues, self.issues, "", [])) + def test_labels_an_unplaced_issue_with_the_repo_claude_picks_on_the_repoless_models_rung(self) -> None: self.issues = [issue("ABC-20")] fake = FakeEffects(claude=[says({"parts": [{"repo": "api", "change": "Add the endpoint."}]}), says({"pick": "repo", "repo": "api"})]) diff --git a/bin/do_epic/test_repo_pick.py b/bin/do_epic/test_repo_pick.py index 1ba93122..f582e3cf 100644 --- a/bin/do_epic/test_repo_pick.py +++ b/bin/do_epic/test_repo_pick.py @@ -31,6 +31,9 @@ def says(output: object) -> Claude: return Claude(json.dumps({"type": "result", "structured_output": output})) +TEAM = {"twu-4": "tenant-web-ui-4", "core-4": "core-4"} + + class RepoPick(unittest.TestCase): def setUp(self) -> None: self.store = MemoryEpic("ABC-12") @@ -43,7 +46,7 @@ class RepoPick(unittest.TestCase): return read[0] def pick(self, claude: Claude): # type: ignore[no-untyped-def] - return picked(self.store, self.issue(), RULE, RUNG, claude, "/rules") + return picked(self.store, self.issue(), {}, RULE, RUNG, claude, "/rules") def test_records_the_claude_pick_as_a_label_on_the_issue(self) -> None: self.assertEqual(self.pick(says({"pick": "repo", "repo": "payments-api"})), Repo("payments-api")) @@ -73,7 +76,7 @@ class RepoPick(unittest.TestCase): store = MemoryEpic("ABC-12") store.file("ABC-12", "Clean up the docs.", "", ()) claude = says({"pick": "claude"}) - picked(store, store.read()[0], RULE, RUNG, claude, "/rules") # type: ignore[index] + picked(store, store.read()[0], {}, RULE, RUNG, claude, "/rules") # type: ignore[index] self.assertIn("Labels: none\n\n(no description)\n", claude.calls[0][2]) def test_records_a_pick_without_a_repo_as_claudes_work_or_a_human_task(self) -> None: @@ -82,9 +85,9 @@ class RepoPick(unittest.TestCase): store = MemoryEpic("ABC-12") key = store.file("ABC-12", "Clean up the docs.", "", ()) issue = store.read()[0] # type: ignore[index] - self.assertEqual(picked(store, issue, RULE, RUNG, says(output), "/rules"), pick) + self.assertEqual(picked(store, issue, {}, RULE, RUNG, says(output), "/rules"), pick) self.assertEqual(store.read()[0].labels, (label,)) # type: ignore[index] - self.assertEqual(recorded(store.read()[0]), pick) # type: ignore[index] + self.assertEqual(recorded(store.read()[0], {}), pick) # type: ignore[index] def test_reads_a_recorded_pick_back_without_asking_claude(self) -> None: self.store.add_label(self.key, "repo:log") @@ -113,7 +116,7 @@ class RepoPick(unittest.TestCase): for name in ("../../.ssh", "a/b", ".hidden", "-flag", "https://host/x.git", "host:repo"): with self.subTest(name=name): self.assertIsInstance(self.pick(says({"pick": "repo", "repo": name})), Failure) - self.assertIsNone(recorded(EpicIssue(self.key, "s", "", (REPO_PREFIX + name,), None, "To Do", False, "ABC-12"))) + self.assertIsNone(recorded(EpicIssue(self.key, "s", "", (REPO_PREFIX + name,), None, "To Do", False, "ABC-12"), {})) def test_a_reply_that_is_no_pick_says_what_it_got_in_its_first_200_characters(self) -> None: output = {"pick": "repo", "repo": "two words" * 40} @@ -129,16 +132,32 @@ class RepoPick(unittest.TestCase): def test_a_label_the_tracker_refuses_comes_back_as_it_is(self) -> None: issue = self.issue() self.store.fails = "Jira answered 503" - self.assertEqual(picked(self.store, issue, RULE, RUNG, says({"pick": "claude"}), "/rules"), Failure("Jira answered 503")) + self.assertEqual(picked(self.store, issue, {}, RULE, RUNG, says({"pick": "claude"}), "/rules"), Failure("Jira answered 503")) def test_the_label_of_a_pick_reads_back_as_that_pick(self) -> None: for pick in (Repo("payments-api"), ClaudeWork(), HumanTask()): with self.subTest(pick=pick): - self.assertEqual(recorded(EpicIssue(self.key, "s", "", (label_of(pick),), None, "To Do", False, "ABC-12")), pick) + self.assertEqual(recorded(EpicIssue(self.key, "s", "", (label_of(pick),), None, "To Do", False, "ABC-12"), {}), pick) + + def test_a_label_the_teams_table_maps_records_its_repo_without_asking_claude(self) -> None: + self.store.add_label(self.key, "twu-4") + claude = says({"pick": "claude"}) + self.assertEqual((picked(self.store, self.issue(), TEAM, RULE, RUNG, claude, "/rules"), claude.calls), (Repo("tenant-web-ui-4"), [])) + self.assertIsNone(recorded(self.issue(), {}), "the label means nothing without the table") + + def test_the_teams_label_and_do_epics_own_for_one_repo_record_one_pick(self) -> None: + self.store.add_label(self.key, "twu-4") + self.store.add_label(self.key, "repo:tenant-web-ui-4") + self.assertEqual(recorded(self.issue(), TEAM), Repo("tenant-web-ui-4")) + + def test_two_of_the_teams_labels_for_different_repos_fail_and_name_both(self) -> None: + self.store.add_label(self.key, "twu-4") + self.store.add_label(self.key, "core-4") + self.assertEqual(recorded(self.issue(), TEAM), Failure(f"{self.key} is labelled with 2 picks: core-4, twu-4; remove all but the right one")) def test_a_label_with_the_prefix_alone_is_no_pick(self) -> None: self.store.add_label(self.key, "repo:") - self.assertIsNone(recorded(self.issue())) + self.assertIsNone(recorded(self.issue(), {})) if __name__ == "__main__": diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index cd853477..f3d8f2cc 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -1,3 +1,4 @@ +import dataclasses import pathlib import subprocess import sys @@ -48,13 +49,30 @@ class TheCapLine(unittest.TestCase): 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)]) + 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")]) + 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_epic_shaped_as_a_teams_is_worked_through_its_own_sub_tasks_and_labels(self) -> None: + team = {"twu-4": "tenant-web-ui-4", "core-4": "core-4"} + issues = [ + issue("ABC-19", "twu-4"), + issue("ABC-20", blockers=("ABC-19",)), + issue("ABC-23", "core-4", parent="ABC-20"), + issue("ABC-24", "twu-4", parent="ABC-20", done=True), + issue("ABC-21"), + issue("ABC-25", "core-4", parent="ABC-21"), + ] + self.assertEqual(chunks(issues, team), ([Chunk("ABC-19", "tenant-web-ui-4"), Chunk("ABC-25", "core-4")], [Waits("ABC-23", "ABC-19 blocks it")])) + self.assertEqual(chunks(issues[:1], {}), ([], [Waits("ABC-19", "no label names its repo")])) + + def test_an_item_whose_only_sub_task_do_epic_filed_is_not_split_until_marked(self) -> None: + task = dataclasses.replace(issue("ABC-23", "repo:api", parent="ABC-20"), by_loop=True) + self.assertEqual(chunks([issue("ABC-20"), task], {}), ([Chunk("ABC-23", "api")], [Waits("ABC-20", "no label names its repo")])) + def test_an_issue_waits_for_its_pick_its_human_and_its_blockers(self) -> None: found = chunks([ issue("ABC-20"), @@ -62,7 +80,7 @@ class WhichIssuesAreChunks(unittest.TestCase): 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"), @@ -71,19 +89,19 @@ class WhichIssuesAreChunks(unittest.TestCase): ])) def test_a_human_task_that_blocks_an_open_issue_is_a_chunk_to_await_and_one_that_blocks_none_waits(self) -> None: - found = chunks([issue("ABC-20", "do-epic-human"), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human")]) + found = chunks([issue("ABC-20", "do-epic-human"), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human")], {}) self.assertEqual(found, ([Chunk("ABC-20", None, human=True)], [Waits("ABC-21", "ABC-20 blocks it"), Waits("ABC-22", "it is a human's task")])) def test_a_human_task_is_awaited_while_it_blocks_a_sub_task_through_its_split_parent(self) -> None: - found = chunks([issue("ABC-19", "do-epic-human"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")]) + found = chunks([issue("ABC-19", "do-epic-human"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")], {}) self.assertEqual(found, ([Chunk("ABC-19", None, human=True)], [Waits("ABC-23", "ABC-19 blocks it")])) def test_a_human_task_that_is_blocked_itself_or_blocks_only_done_issues_waits(self) -> None: - found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "do-epic-human", blockers=("ABC-19",)), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human"), issue("ABC-23", "repo:api", done=True, blockers=("ABC-22",))]) + found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "do-epic-human", blockers=("ABC-19",)), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human"), issue("ABC-23", "repo:api", done=True, blockers=("ABC-22",))], {}) self.assertEqual(found, ([Chunk("ABC-19", "api")], [Waits("ABC-20", "it is a human's task"), Waits("ABC-21", "ABC-20 blocks it"), Waits("ABC-22", "it is a human's task")])) def test_what_blocks_a_split_item_blocks_its_sub_tasks(self) -> None: - found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")]) + found = chunks([issue("ABC-19", "repo:api"), issue("ABC-20", "split-by-repo", blockers=("ABC-19",)), issue("ABC-23", "repo:api", parent="ABC-20")], {}) self.assertEqual(found, ([Chunk("ABC-19", "api")], [Waits("ABC-23", "ABC-19 blocks it")])) @@ -142,7 +160,7 @@ class StartingAnEpicsChunks(unittest.TestCase): """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"}) + 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, False, own, run) diff --git a/bin/do_epic/test_split.py b/bin/do_epic/test_split.py index 32b4d8a4..1e908448 100644 --- a/bin/do_epic/test_split.py +++ b/bin/do_epic/test_split.py @@ -1,3 +1,4 @@ +import dataclasses import json import pathlib import sys @@ -8,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.test_repo_pick import Claude, says from do_epic.backend.protocol import EpicIssue from failure import Failure -from do_epic.split import finished, Split, split, SPLIT_LABEL, SPLIT_SCHEMA +from do_epic.split import finished, is_split, Split, split, SPLIT_LABEL, SPLIT_SCHEMA from claude_code.reply import Limited from do_epic.backend.fake import MemoryEpic from model_routing.ladder import Rung @@ -50,7 +51,7 @@ class Split_(unittest.TestCase): return [issue for issue in self.issues() if issue.parent == self.key] def run_split(self, claude: Claude, by_person: bool = False): # type: ignore[no-untyped-def] - return split(self.store, self.issue(), by_person, RULE, "Swedish", ("/repos/api", "/repos/web"), RUNG, claude, "/rules") + return split(self.store, self.issue(), {}, by_person, RULE, "Swedish", ("/repos/api", "/repos/web"), RUNG, claude, "/rules") def test_files_a_sub_task_per_repo_labelled_for_it_and_marks_the_parent(self) -> None: done = self.run_split(says(TWO)) @@ -60,6 +61,16 @@ class Split_(unittest.TestCase): self.assertEqual(self.issue().labels, ("api", SPLIT_LABEL)) self.assertEqual(self.store.comments, {}) + def test_an_item_a_person_filed_a_sub_task_under_is_left_alone_without_asking_claude(self) -> None: + self.store.issues.append(EpicIssue("ABC-90", "twu-4: Count them.", "", ("twu-4",), None, "To Do", False, self.key)) + claude = says(TWO) + self.assertEqual((self.run_split(claude), claude.calls, len(self.tasks())), (Split((), ()), [], 1)) + + def test_a_sub_task_with_the_teams_label_counts_as_its_repos_when_a_failed_run_is_taken_up(self) -> None: + self.store.issues.append(EpicIssue("ABC-90", "Serve it.", "", ("backend",), None, "To Do", False, self.key, by_loop=True)) + done = split(self.store, self.issue(), {"backend": "api"}, False, RULE, "Swedish", (), RUNG, says(TWO), "/rules") + self.assertEqual((done, [task.labels for task in self.tasks()]), (Split(("api", "web"), (self.tasks()[1].key,)), [("backend",), ("repo:web",)])) + def test_comments_on_a_persons_issue_for_the_team_once_its_sub_tasks_are_filed(self) -> None: self.run_split(says(TWO), by_person=True) self.assertEqual(self.store.comments, {self.key: ["Delat per repo: api och web."]}) @@ -143,7 +154,7 @@ class Split_(unittest.TestCase): assert isinstance(key, str) bare = next(issue for issue in self.issues() if issue.key == key) claude = says(TWO) - split(self.store, bare, False, RULE, "Swedish", (), RUNG, claude, "/rules") + split(self.store, bare, {}, False, RULE, "Swedish", (), RUNG, claude, "/rules") prompt = claude.calls[0][2] self.assertIn("checked out at: none. Read them", prompt) self.assertTrue(prompt.endswith("\nLabels: none\n\n(no description)\n")) @@ -153,7 +164,7 @@ class Split_(unittest.TestCase): key = self.store.file("ABC-12", "Two labels.", "Why.", ("api", "urgent")) assert isinstance(key, str) claude = says(TWO) - split(self.store, next(issue for issue in self.issues() if issue.key == key), False, RULE, "Swedish", (), RUNG, claude, "/rules") + split(self.store, next(issue for issue in self.issues() if issue.key == key), {}, False, RULE, "Swedish", (), RUNG, claude, "/rules") self.assertIn("\nLabels: api, urgent\n", claude.calls[0][2]) def test_asks_a_persons_issue_for_a_comment(self) -> None: @@ -196,6 +207,16 @@ class Finished(unittest.TestCase): self.assertEqual([finished(self.issues((own, ()), ()), "ABC-1") for own in (True, False)], [True, False]) self.assertEqual(finished(self.issues((True, ()), ()), "ABC-9"), False) + def test_an_item_with_a_persons_sub_tasks_is_split_without_the_mark_and_done_once_they_are(self) -> None: + self.assertEqual([finished(self.issues((False, ()), tasks), "ABC-1") for tasks in ((True, True), (True, False))], [True, False]) + self.assertTrue(is_split(*self.issues((False, ()), (False,))[:1], self.issues((False, ()), (False,)))) + + def test_an_item_whose_only_sub_tasks_do_epic_filed_is_not_split_until_marked(self) -> None: + parent, task = self.issues((False, ()), (True,)) + ours = [parent, dataclasses.replace(task, by_loop=True)] + self.assertEqual((is_split(parent, ours), finished(ours, "ABC-1")), (False, False)) + self.assertTrue(is_split(dataclasses.replace(parent, labels=(SPLIT_LABEL,)), ours)) + def test_an_item_marked_split_whose_sub_tasks_are_not_filed_yet_is_done_by_its_own_status(self) -> None: self.assertEqual(finished(self.issues((False, (SPLIT_LABEL,)), ()), "ABC-1"), False) diff --git a/bin/do_epic/test_status.py b/bin/do_epic/test_status.py index 4ede4c06..f811e78e 100644 --- a/bin/do_epic/test_status.py +++ b/bin/do_epic/test_status.py @@ -24,7 +24,7 @@ class TheStatusLines(unittest.TestCase): os.utime(parked.file_of(self.folder, key), (SINCE, SINCE)) def lines(self, issues: list, *windows: tuple[str, str, bool, str]) -> list[str] | Failure: - return status.lines("ABC-12", self.home, issues, Tmux(*windows)) + return status.lines("ABC-12", self.home, issues, {}, Tmux(*windows)) def test_a_chunk_that_asks_says_where_to_answer_and_one_that_works_runs(self) -> None: found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20 ?", False, ""), (EPIC, "ABC-21", False, "")) diff --git a/docs/decisions.md b/docs/decisions.md index d45998bb..883a6c5c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -145,10 +145,10 @@ Valid while `~/.claude` is a checkout of this repo. 2026-11-18, lilleman's answers to claude's questions while planning release 0.12.0. Serves goal 1, so development scales past one repo, and goal 1.6, since the epic stays in the client's Jira. Valid while Jira is the only backend; another backend goes behind the same interface. - **What it is.** `do-epic ` is a sibling of loop-claude, built on the same cycle, judge, interrupt, tmux and routing packages, not a copy (goal 1.3). It runs one tmux session per epic. -- **Machine settings.** `~/.claude-projects/do-epic/` holds `config.toml` (the Jira site, env-file, the folder repos are cloned into, the default language, and the model for a no-repo item) and `repo-rule.md`. `repo-rule.md` is a prose instruction that says how to tell an item's repo. It is the same for every epic on the machine. On the first machine, an item's label that equals a repo's name names that repo. +- **Machine settings.** `~/.claude-projects/do-epic/` holds `config.toml` (the Jira site, env-file, the folder repos are cloned into, the default language, and the model for a no-repo item) and `repo-rule.md`. `repo-rule.md` is a prose instruction that says how to tell an item's repo. It is the same for every epic on the machine. On the first machine, an item's label that equals a repo's name names that repo. A `[label-repos]` table in `config.toml` maps a team's own label to a repo, so do-epic reads that label as a pick without a claude call. - **The epic's description is its record.** It holds `## Goals`, `## Audience`, `## Scoring` (formula and bar), `## Decisions` and a language line. do-epic writes all of it, but it changes Goals or Audience only after the human approves in an interrupt. - **Items live only in the epic.** A repo's own plan never mirrors them. Where `repo-rule.md` leaves an item's repo unclear, do-epic asks. An item without a repo is either Claude's work, done without a PR, or a human task; where the item doesn't say which, do-epic asks. -- **One item, several repos.** do-epic splits such an item when it plans it, into one Jira sub-task per repo, each labelled for its repo. The parent tracks the whole change. A person's issue is split too, with a comment for the team. +- **One item, several repos.** do-epic splits such an item when it plans it, into one Jira sub-task per repo, each labelled for its repo. The parent tracks the whole change. A person's issue is split too, with a comment for the team. An item a person filed a sub-task under counts as split already: do-epic works it through the team's own sub-tasks and files none beside them. - **Ranking.** Score, then Blocked by, in one weight chain: the epic's achieve goals, then code health, then the repo's goals. Where the epic and a repo disagree, the epic wins. do-epic re-ranks Jira's backlog to match, and people's issues keep their rank. - **Releases.** An epic item has no release. It ships into its repo's unreleased work: where the repo publishes something others consume, a bullet under `CHANGELOG.md` → `## Unreleased`, or nothing where the repo's plan is in Jira. The issue is no item of the repo's plan, so the chunk's worker writes the bullet in its branch and runs `chunk-pr merge` without `--finish`. - **Repos.** A repo's name is its main checkout's folder name, and a project config names that checkout. A missing checkout is cloned from the host of the epic's other repos; where unsure, do-epic asks. Unsure means the other repos don't all sit under one host and owner (the same host spelt as https and as ssh counts as two), an origin can't be read or isn't an https, ssh or scp-style address, the folder to clone into holds something else, or the clone fails. A repo no config names is cloned into the clone folder, and the human is asked to write its config. Each chunk uses its repo's model, routing, and language for commits and PRs. Jira text is in the epic's language, or else the machine's default. From b26256ce44237547644426f38f3a859ba2193481 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 15:37:03 +0100 Subject: [PATCH 02/22] Sort the imports the label table added --- bin/do_epic/config.py | 6 +++--- bin/do_epic/findings.py | 2 +- bin/do_epic/finish.py | 2 +- bin/do_epic/human_tasks.py | 2 +- bin/do_epic/scheduler.py | 4 ++-- bin/do_epic/split.py | 2 +- bin/do_epic/status.py | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index ecbbdc17..7edf0310 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -25,12 +25,12 @@ import re import types from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINISH, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE -from do_epic.backend.protocol import LABEL -from do_epic.repo_pick import of_label, REPO_NAME, LabelRepos, REVIEW_LABEL -from do_epic.split import SPLIT_LABEL from failure import Failure +from do_epic.backend.protocol import LABEL +from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL from text_files.markdown_text import listed from model_routing.ladder_file import read_ladder, SHIPPED +from do_epic.split import SPLIT_LABEL REPO_RULE = "repo-rule.md" # Three readers, seated as the human who writes this config, picked these spellings from four candidates each, 3-0: `jira-url` over `site`, `clone-folder` over `repos-folder` (which reads as the folder of repos that already exist) and `repoless-model` over `no-repo-model`. `env-file` and `language` keep the names a project's config gives them. diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py index b2264940..33fa8470 100644 --- a/bin/do_epic/findings.py +++ b/bin/do_epic/findings.py @@ -6,7 +6,7 @@ import fcntl import pathlib import typing -from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX, LabelRepos, REVIEW_LABEL +from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, LabelRepos, of_label, REPO_PREFIX, REVIEW_LABEL from do_epic.epic_record import EpicRecord from do_epic.backend.protocol import EpicStore from failure import Failure diff --git a/bin/do_epic/finish.py b/bin/do_epic/finish.py index f6a42d57..029977b3 100644 --- a/bin/do_epic/finish.py +++ b/bin/do_epic/finish.py @@ -15,9 +15,9 @@ from do_epic.backend.protocol import EpicIssue, EpicStore from failure import Failure from do_epic import findings from do_epic.split import finished +from do_epic.repo_pick import LabelRepos, recorded, Repo, REPO_PREFIX, REVIEW_LABEL from text_files.markdown_text import listed from text_files.piped_text import piped -from do_epic.repo_pick import recorded, Repo, REPO_PREFIX, LabelRepos, REVIEW_LABEL # Not `--close`, which reads as closing the run or one issue: three readers, seated as the human, as a chunk's worker and as one of the client's team, picked this one from four, 2-1 over it. CLOSE = "--close-epic" diff --git a/bin/do_epic/human_tasks.py b/bin/do_epic/human_tasks.py index 5ef39162..13efb0c6 100644 --- a/bin/do_epic/human_tasks.py +++ b/bin/do_epic/human_tasks.py @@ -7,7 +7,7 @@ from project_config.settings import by_name, ProjectConfig from loop_effects.effects import Effects, say from do_epic.backend.protocol import EpicIssue, EpicStore from failure import Failure -from do_epic.repo_pick import recorded, Repo, LabelRepos +from do_epic.repo_pick import LabelRepos, recorded, Repo from do_epic import scheduler from agent_cycle.direct_message import tell from agent_cycle import tmux diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index dae39991..c1569718 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -9,11 +9,11 @@ from do_epic.epic_record import CAP from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_chunks, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure -from do_epic.repo_pick import HumanTask, Pick, recorded, Repo, LabelRepos +from do_epic.repo_pick import HumanTask, LabelRepos, Pick, recorded, Repo +from do_epic.split import is_split from project_config.settings import PARALLEL_CHUNKS from do_epic.parked import parked_chunks from chunk_pr.approval import PARKS -from do_epic.split import is_split from agent_cycle import tmux # Under the home folder, a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. diff --git a/bin/do_epic/split.py b/bin/do_epic/split.py index 01c58026..b4f26c64 100644 --- a/bin/do_epic/split.py +++ b/bin/do_epic/split.py @@ -7,7 +7,7 @@ import json from claude_code.reply import Claude, claude_reply, Limited from do_epic.backend.protocol import EpicIssue, EpicStore from failure import Failure -from do_epic.repo_pick import label_of, of_label, Repo, REPO_NAME, LabelRepos +from do_epic.repo_pick import label_of, LabelRepos, of_label, Repo, REPO_NAME from model_routing.ladder import Rung from claude_code.entries import structured_output diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py index 846d2f9e..65e3ea96 100644 --- a/bin/do_epic/status.py +++ b/bin/do_epic/status.py @@ -2,11 +2,11 @@ import datetime import pathlib -from do_epic.repo_pick import LabelRepos from do_epic.scheduler import chunks, HUMAN_WAIT, STATE from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, Parked, parked_chunks, SLOT +from do_epic.repo_pick import LabelRepos from agent_cycle import tmux From b09d30b48e994993feced55e0cb63ffe7c76322c Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 15:48:02 +0100 Subject: [PATCH 03/22] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From b2630b814844353bf2374e062d0c8632d2396208 Mon Sep 17 00:00:00 2001 From: Lilleman Date: Thu, 19 Nov 2026 15:52:49 +0100 Subject: [PATCH 04/22] Let do-epic --file take --blocked-by and --parent, so a change a repo ships as two pull requests gets an issue for each --- README.md | 2 +- bin/do_epic/backend/contract.py | 22 +++++++++++++++ bin/do_epic/backend/fake.py | 8 ++++-- bin/do_epic/backend/jira.py | 23 +++++++++++++--- bin/do_epic/backend/protocol.py | 9 ++++-- bin/do_epic/backend/test_jira.py | 14 ++++++++++ bin/do_epic/findings.py | 47 ++++++++++++++++++++++---------- bin/do_epic/main.py | 4 +-- bin/do_epic/test_findings.py | 19 ++++++++++++- bin/do_epic/test_scheduler.py | 4 ++- 10 files changed, 123 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 250d1d18..eeaee08b 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. -- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. +- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, which takes `--blocked-by` to make the issue wait for another of the epic's and `--parent` to file it as a sub-task, so a change a repo ships as two pull requests gets an issue for each, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. - `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index 9786e2f0..4fc4eb44 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -91,6 +91,28 @@ class EpicStoreContract: self.assertEqual(store.file(task, "Count more.", "", ()), Failure(f"{task} is neither the epic {store.epic_key} nor one of its child issues, so nothing can be filed under it")) self.assertEqual(len(self.issues(store)), 2) + def test_files_an_issue_blocked_by_a_child_issue_or_a_sub_task_of_the_epic(self) -> None: + store = self.new_store() + child = self.filed(store, store.epic_key, "Pin the behaviour.") + task = self.filed(store, child, "Pin it in the api.") + second = store.file(store.epic_key, "Change the behaviour.", "", (), child) + third = store.file(child, "Change it in the api.", "", (), task) + assert isinstance(second, str) and isinstance(third, str), (second, third) + read = {issue.key: issue for issue in self.issues(store)} + self.assertEqual((read[second].blockers, read[third].blockers, read[third].parent), ((child,), (task,), child)) + + def test_refuses_to_file_blocked_by_an_issue_outside_the_epic(self) -> None: + store = self.new_store() + for blocker in ("ZZZ-1", "not a key"): + with self.subTest(blocker=blocker): + self.assertIsInstance(store.file(store.epic_key, "Count more.", "", (), blocker), Failure) + self.assertEqual(self.issues(store), []) + + def test_refuses_to_file_blocked_by_the_epic_itself(self) -> None: + store = self.new_store() + self.assertIsInstance(store.file(store.epic_key, "Count more.", "", (), store.epic_key), Failure) + self.assertEqual(self.issues(store), []) + def test_refuses_to_file_under_an_issue_outside_the_epic(self) -> None: store = self.new_store() for parent in ("ZZZ-1", "not a key"): diff --git a/bin/do_epic/backend/fake.py b/bin/do_epic/backend/fake.py index 4d2a3e01..3d05918d 100644 --- a/bin/do_epic/backend/fake.py +++ b/bin/do_epic/backend/fake.py @@ -1,7 +1,7 @@ """An epic held in memory, for do-epic's tests, held to contract.py like every backend.""" import dataclasses -from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label +from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -19,15 +19,17 @@ class MemoryEpic: return Failure(self.fails) return [issue for child in self.issues if child.parent == self.epic_key for issue in (child, *(task for task in self.issues if task.parent == child.key))] - def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure: + def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...], blocked_by: str | None = None) -> str | Failure: if self.fails: return Failure(self.fails) if refused := unfit(summary, labels): return refused if parent != self.epic_key and parent not in {issue.key for issue in self.issues if issue.parent == self.epic_key}: return no_parent(self.epic_key, parent) + if blocked_by is not None and blocked_by not in {issue.key for issue in self.issues}: + return no_blocker(self.epic_key, blocked_by) key = f"{self.epic_key.rpartition('-')[0]}-{len(self.issues) + 100}" - self.issues.append(EpicIssue(key, summary, detail.strip(), tuple(sorted(labels)), None, "To Do", False, parent, by_loop=True)) + self.issues.append(EpicIssue(key, summary, detail.strip(), tuple(sorted(labels)), None, "To Do", False, parent, blockers=(blocked_by,) if blocked_by else (), by_loop=True)) return key def add_label(self, key: str, label: str) -> None | Failure: diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 79ad2548..6891e3df 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -7,9 +7,9 @@ from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION -from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label +from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure -from plan_store.jira_epic import FILED_BY, ISSUE_TYPE, PROPERTY, scores +from plan_store.jira_epic import BLOCKS, FILED_BY, ISSUE_TYPE, PROPERTY, scores FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. @@ -57,11 +57,11 @@ class JiraEpic: details = {each.issue.key: text.strip() for each, text in zip(described, texts)} return [dataclasses.replace(each.issue, detail=details.get(each.issue.key, "")) for each in found] - def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure: + def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...], blocked_by: str | None = None) -> str | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - if refused := unfit(summary, labels) or self.not_a_parent(parent, authorization): + if refused := unfit(summary, labels) or self.not_a_parent(parent, authorization) or (blocked_by and self.not_a_blocker(blocked_by, authorization)): return refused fields: dict[str, typing.Any] = {"project": {"key": project_of(parent)}, "parent": {"key": parent}, "summary": summary, "labels": list(labels)} # Marks the issue as the loop's, as plan_store marks the items it files. @@ -80,6 +80,11 @@ class JiraEpic: key = created.get("key") if isinstance(created, dict) else None if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): return Failure(f"Jira answered the new issue without an issue key; {PERHAPS_FILED.format(under=parent)}") + if blocked_by: + # Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it. + linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocked_by}, "outwardIssue": {"key": key}}) + if isinstance(linked, Failure): + return Failure(f"filed {key} under {parent}, but cannot link it as blocked by {blocked_by}: {linked.reason}; link it in Jira") return key def add_label(self, key: str, label: str) -> None | Failure: @@ -184,6 +189,16 @@ class JiraEpic: above = self.parent_of(parent, authorization, "to file under it") return above if isinstance(above, Failure) else None if above == self.epic_key else no_parent(self.epic_key, parent) + def not_a_blocker(self, blocker: str, authorization: str) -> Failure | None: + """Why nothing can be filed blocked by blocker; None where it is a child issue of the epic or a sub-task of one.""" + above = self.parent_of(blocker, authorization, "to file blocked by it") + if isinstance(above, Failure): + return above + if above == self.epic_key: + return None + grand = None if above is None else self.parent_of(above, authorization, "to file blocked by it") + return grand if isinstance(grand, Failure) else None if grand == self.epic_key else no_blocker(self.epic_key, blocker) + def parent_of(self, key: str, authorization: str, why: str) -> str | None | Failure: """The key of key's parent issue; None where key isn't an issue key or has no parent. A failed read says "cannot read ".""" placed = self.placed(key, authorization, why) diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index 516b2300..af51d7d1 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -51,8 +51,8 @@ class EpicStore(typing.Protocol): def read(self) -> list[EpicIssue] | Failure: """Each child issue, open or done, in the tracker's rank order, each followed by its sub-tasks in theirs.""" - def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure: - """Files an open issue under parent, marked as filed by the loop, and answers its key: a child issue where parent is the epic, a sub-task where parent is one of its child issues. detail is markdown, and may be empty.""" + def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...], blocked_by: str | None = None) -> str | Failure: + """Files an open issue under parent, marked as filed by the loop, and answers its key: a child issue where parent is the epic, a sub-task where parent is one of its child issues. detail is markdown, and may be empty. Where blocked_by names an issue, a child issue of the epic or a sub-task of one, the new issue is blocked by it; any other issue is refused before anything is filed. Where the issue is filed and cannot be linked, the Failure names its key.""" def add_label(self, key: str, label: str) -> None | Failure: """Adds label to the epic's child issue named key, leaving its other labels as they are; adding one it already has leaves the labels as they are. A sub-task, or an issue outside the epic, is refused.""" @@ -93,6 +93,11 @@ def no_parent(epic_key: str, parent: str) -> Failure: return Failure(f"{parent} is neither the epic {epic_key} nor one of its child issues, so nothing can be filed under it") +def no_blocker(epic_key: str, blocker: str) -> Failure: + """What every backend says when asked to file an issue blocked by blocker, which is neither a child issue of the epic nor a sub-task of one.""" + return Failure(f"{blocker} is neither a child issue of the epic {epic_key} nor a sub-task of one, so nothing can be filed blocked by it") + + def no_child(epic_key: str, key: str, done_to_it: str) -> Failure: """What every backend says when asked to change key, which is not one of the epic's child issues; done_to_it is the past participle of what was asked, such as "labelled".""" return Failure(f"{key} is not one of the child issues of the epic {epic_key}, so it cannot be {done_to_it}") diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 89c56635..6f2384f9 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -21,6 +21,7 @@ EPIC_URL = f"{SITE}/rest/api/3/issue/ABC-12?fields=summary" ISSUE_TYPES = f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes" SEARCH = f"{SITE}/rest/api/3/search/jql" ISSUES = f"{SITE}/rest/api/3/issue" +LINKS = f"{SITE}/rest/api/3/issueLink" RANK = f"{SITE}/rest/agile/1.0/issue/rank" TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}} DONE = {"name": "Done", "statusCategory": {"key": "done"}} @@ -91,6 +92,11 @@ class FakeJira: return self.created(body) if method == "PUT" and url == RANK: return self.ranked(body) + if method == "POST" and url == LINKS: + assert isinstance(body, dict) and body["type"] == {"name": "Blocks"}, body + links = next(issue for issue in self.issues if issue["key"] == body["outwardIssue"]["key"])["fields"]["issuelinks"] # type: ignore[index] + links.append({"id": str(len(links) + 1), "type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": body["inwardIssue"]}) # type: ignore[index] + return None if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/comment"), None)): assert isinstance(body, dict) self.comments.setdefault(str(held["key"]), []).append(body["body"]) @@ -304,6 +310,14 @@ class Jira(Case): self.jira.answers[("POST", ISSUES)] = answer self.assertEqual(self.new_store().file("ABC-12", "Count the runs.", "", ()), Failure(f"{reason}; unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again")) + def test_a_link_jira_refuses_leaves_the_issue_filed_and_names_its_key(self) -> None: + store = self.new_store() + first = store.file("ABC-12", "Pin the behaviour.", "", ()) + assert isinstance(first, str) + self.jira.answers[("POST", LINKS)] = Failure("Jira answered 403") + self.assertEqual(store.file("ABC-12", "Change the behaviour.", "", (), first), Failure(f"filed ABC-101 under ABC-12, but cannot link it as blocked by {first}: Jira answered 403; link it in Jira")) + self.assertEqual([issue["key"] for issue in self.jira.issues], [first, "ABC-101"]) + def test_a_detail_the_codec_refuses_leaves_the_epic_as_it_was(self) -> None: store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it")) self.assertEqual(store.file("ABC-12", "Count the runs.", "Why.", ()), Failure("cannot convert the detail to a Jira description: adf-codec refused it")) diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py index 54a11837..764bf33d 100644 --- a/bin/do_epic/findings.py +++ b/bin/do_epic/findings.py @@ -2,6 +2,7 @@ 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 @@ -16,16 +17,19 @@ from text_files.piped_text import piped # Three readers, seated as the human and as a chunk's worker, picked each spelling from four: ` --file` over `--file `, `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}` 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 {FILE} [{LABEL}