From 4e0b625191cb78b4d95715f50f254928bc020979 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:04:21 +0100 Subject: [PATCH 01/34] Re-score item 411 to L 4, S 6 after reading the code --- todo.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 7b8e0368..3ff6671b 100644 --- a/todo.md +++ b/todo.md @@ -18,7 +18,7 @@ | 415 | 0.12.0 | 413 | | **Finish an epic: run release-review passes on each repo it changed, work what they file, have the human confirm each goal, post a summary comment, and close the epic in Jira last.** | 3 | 2 | 3 | 6 | 5 | 1 by 5 | 1.2 | | 418 | 0.12.0 | 415 | | **Describe do-epic in `README.md`'s tools and setup, with its machine settings and `repo-rule.md`.** | 1 | 2 | 1 | 2 | 2 | 1 by 5 | 2.1 | | 420 | 0.12.0 | | | **End a worker that printed its final result and lingers, by killing the background shells it left, after a few minutes, and print each kill with its evidence on loop-claude's terminal.** | 2 | 2 | 2 | 4 | 3 | 1.5 by 6 | 2.0 | -| 411 | 0.12.0 | | | **Park a chunk whose PR waits on a long gate, keeping its worktree, PR and session in a state file that survives a reboot, and resume its session when the gate passes or a reviewer comments.** | 3 | 2 | 3 | 6 | 5 | 1 by 5 | 1.2 | +| 411 | 0.12.0 | | | **Park a chunk whose PR waits on a long gate, keeping its worktree, PR and session in a state file that survives a reboot, and resume its session when the gate passes or a reviewer comments.** | 4 | 2 | 3 | 7 | 6 | 1 by 5 | 0.8 | | 412 | 0.12.0 | 411 | | **Print each chunk of an epic, running, parked with its gate and since when, or stopped, each human task and each open interrupt with `do-epic --status`, and name a parked chunk's gate in its tmux window's name.** | 2 | 1 | 1 | 2 | 3 | 1 by 5 | 1.9 | | 414 | 0.12.0 | | | **DM the human through the notifier when a human-task issue blocks the epic's next item, and poll until it closes.** | 2 | 2 | 2 | 4 | 3 | 1 by 5 | 1.9 | | 417 | 0.12.0 | | | **Run do-epic end to end against a sandbox epic on a real Jira site with a command of its own, outside `run-tests`.** | 2 | 1 | 1 | 2 | 3 | 1 by 5 | 1.9 | @@ -155,6 +155,10 @@ Touches: - `bin/forge/pulls.py`: `checks_passed` (small) - `bin/do_epic/gates.py` - `bin/do_epic/parked.py` +- `bin/do_epic/main.py`: `HELP` (small), `run`, `windows_opened`, `chunk_run` +- `bin/do_epic/scheduler.py`: `start_chunks`, `room_in` (small) +- `bin/do_epic/chunk_prompt.py` +- `README.md`: `` ### Packages under `bin/` `` (small) ### 412. Print each chunk of an epic, running, parked with its gate and since when, or stopped, each human task and each open interrupt with `do-epic --status`, and name a parked chunk's gate in its tmux window's name. From 36dbddfa0b70d1f4298c7f5072ca8a8c69b1f663 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:04:27 +0100 Subject: [PATCH 02/34] Re-score item 413 to L 4: several components and a new filing command --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 7b8e0368..50ca2fac 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +14,7 @@ |---|---|---|---|---|---|---|---|---|---|---|---| | 441 | 0.12.0 | | | **Move an epic's issue to done in Jira when its chunk finishes, so no finished chunk starts again and what it blocks starts.** | 2 | 2 | 2 | 4 | 3 | 1 by 6 | 2.3 | | 416 | 0.12.0 | | | **Finish an epic's repo item with a bullet under its repo's `CHANGELOG.md` → `## Unreleased`, or with none where the repo's plan is in Jira.** | 1 | 1 | 1 | 1 | 2 | 1 by 5 | 2.1 | -| 413 | 0.12.0 | | | **File a finding about an epic goal in the epic and one about a repo goal by that repo's rules, ask the human where unsure which, and give the judge the epic's records beside the repo's.** | 3 | 2 | 3 | 6 | 4 | 1 by 5 | 1.6 | +| 413 | 0.12.0 | | | **File a finding about an epic goal in the epic and one about a repo goal by that repo's rules, ask the human where unsure which, and give the judge the epic's records beside the repo's.** | 4 | 2 | 3 | 7 | 4 | 1 by 5 | 1.6 | | 415 | 0.12.0 | 413 | | **Finish an epic: run release-review passes on each repo it changed, work what they file, have the human confirm each goal, post a summary comment, and close the epic in Jira last.** | 3 | 2 | 3 | 6 | 5 | 1 by 5 | 1.2 | | 418 | 0.12.0 | 415 | | **Describe do-epic in `README.md`'s tools and setup, with its machine settings and `repo-rule.md`.** | 1 | 2 | 1 | 2 | 2 | 1 by 5 | 2.1 | | 420 | 0.12.0 | | | **End a worker that printed its final result and lingers, by killing the background shells it left, after a few minutes, and print each kill with its evidence on loop-claude's terminal.** | 2 | 2 | 2 | 4 | 3 | 1.5 by 6 | 2.0 | From 7058e8c13b48dc29d970d83ab69297149208a06a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:08:36 +0100 Subject: [PATCH 03/34] Read a pull request's checks and waiting review threads once, and fail chunk-pr merge at once where do-epic parks --- bin/chunk_pr/approval.py | 31 ++++++++------ bin/chunk_pr/main.py | 19 ++++----- bin/chunk_pr/test_chunk_pr.py | 10 +++++ bin/forge/pulls.py | 76 +++++++++++++++++++++++++---------- bin/forge/test_forge.py | 30 +++++++++++++- 5 files changed, 123 insertions(+), 43 deletions(-) diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index a33b08e5..d420a7f8 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -10,6 +10,8 @@ from forge.commands import Forge, Run # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 WAIT_SECONDS = 90 * 60 +# The environment variable do-epic sets to 1 for its chunks' workers. With it, merge doesn't wait for an approval: do-epic parks the chunk and polls the forge itself, so the chunk holds no running slot meanwhile (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). +PARKS = "CHUNK_PR_PARKS" def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure: @@ -59,16 +61,21 @@ def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time def unanswered(number: str, run: Run) -> Failure | None: - """A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits.""" - read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) - try: - pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"] - if isinstance(pull, Failure): - return pull - author = pull["author"]["login"] - waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) - except (ValueError, KeyError, TypeError): - return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}") - if not waiting: - return None + """A Failure naming the files where a reviewer's comment waits for an answer on pull request number, as `waiting_threads` finds them, or saying why they cannot be read. None where no thread waits.""" + waiting = waiting_threads(number, run) + if isinstance(waiting, Failure) or not waiting: + return waiting or None return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again") + + +def waiting_threads(number: str, run: Run) -> list[str] | Failure: + """The files where a reviewer's comment waits for an answer on pull request number, read once: those of each review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again.""" + read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) + if isinstance(read, Failure): + return read + try: + pull = json.loads(read)["data"]["repository"]["pullRequest"] + author = pull["author"]["login"] + return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) + except (ValueError, KeyError, TypeError): + return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}") diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 0e91ea6a..09529c70 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -45,7 +45,8 @@ merge merges the pull request in its turn: the chunks of one project on this Where the project's config sets `wait-for-approval = true` (`project-config --help`), it merges only once GitHub reports the pull request approved as its branch protection requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes - a new turn once approved. + a new turn once approved. In a chunk do-epic runs, which sets CHUNK_PR_PARKS=1, it + fails at once instead of waiting: do-epic parks the chunk until the approval comes. It stops, without merging, and says what to do before running it again: - on a merge conflict in step 1, naming the conflicted files, with the merge in progress; - where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a @@ -85,7 +86,7 @@ import sys import time import typing -from chunk_pr.approval import approval, approved, awaited, unanswered +from chunk_pr.approval import approval, approved, awaited, PARKS, unanswered from forge.pulls import checks_passed, merged_pull, open_pull, required_checks from failure import Failure from forge.commands import Forge, forge_of, gitea, Run, runner @@ -119,7 +120,7 @@ def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home()))) + done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())), os.environ.get(PARKS) == "1") if isinstance(done, Failure): print(f"chunk-pr: {done.reason}", file=sys.stderr) return 1 @@ -127,8 +128,8 @@ def main(argv: list[str]) -> int: return 0 -def step(argv: list[str], run: Run, config: Config) -> str | Failure: - """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything.""" +def step(argv: list[str], run: Run, config: Config, parks: bool = False) -> str | Failure: + """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything. parks is whether a merge fails at once where it would wait for an approval (`merged`).""" match argv: case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"): return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run) @@ -138,7 +139,7 @@ def step(argv: list[str], run: Run, config: Config) -> str | Failure: return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None) case ["merge", *given]: finishes = finishes_of(given) - return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes) + return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes, parks=parks) case ["clean"]: return cleaned(run) return Failure(USAGE) @@ -304,8 +305,8 @@ def finishes_of(given: list[str]) -> list[list[str]] | None: return finishes -def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure: - """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved.""" +def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = (), parks: bool = False) -> str | Failure: + """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, telling the worker that do-epic parks the chunk.""" found = pull(run) if isinstance(found, Failure): return found @@ -337,7 +338,7 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = tim if not isinstance(taken, AwaitsApproval): return taken if isinstance(taken, Failure) else taken + absent # Out of the queue, so the project's other chunks merge while this one waits. - waited = approved(number, run, sleep) + waited = Failure(f"pull request {number} passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments") if parks else approved(number, run, sleep) if isinstance(waited, Failure): return waited diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index a8ceafa1..615a5bc9 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -377,6 +377,16 @@ class Merge(unittest.TestCase): self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(slept, [60]) + def test_a_merge_that_parks_returns_at_once_while_the_branch_protection_still_wants_a_review(self): + checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") + failed = merged(checkout, checkout.config, self.fail, parks=True) + self.assertEqual(failed.reason, "pull request 12 passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments") + self.assertEqual(checkout.ran.count(GH_DECISION), 1) + + def test_a_merge_that_parks_merges_an_approved_pull_request(self): + checkout = self.requiring_approval() + self.assertEqual(merged(checkout, checkout.config, self.fail, parks=True), "Merged pull request #12 (merge).") + def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self): checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") slept: list[float] = [] diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 5644a66f..2f2d1c8d 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -1,5 +1,7 @@ """Finding a pull request from origin's own branch, and waiting for the checks on its head commit.""" +import dataclasses import fnmatch +import json import time import typing @@ -10,6 +12,8 @@ from forge.commands import Forge, gitea, Run POLL_SECONDS = 10 # How long checks_passed waits on Gitea for the checks before it gives up; CI took about 3 minutes in 2026-11. gh's watch waits as long as the checks run. WAIT_SECONDS = 30 * 60 +# What gh says of a pull request whose head has no check. +NO_CHECKS = "no checks reported" def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure: @@ -57,37 +61,67 @@ def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure: return Failure(f"tea api answered branch {base} in a shape that can't be read: {str(branch)[:200]}") -def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None: - """None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. +@dataclasses.dataclass(frozen=True) +class CheckFailed(Failure): + """A check on a pull request's head failed, which a new push answers. Any other Failure of a read of the checks says the forge could not be read.""" - On Gitea it also waits for a passed check to match each of required: a check CI has yet to queue is no status at all. + +@dataclasses.dataclass(frozen=True) +class Pending: + """The checks on a pull request's head have not all passed yet, and none failed.""" + # The checks, or glob patterns, that the protection requires and no passed check matches yet. Empty where a check that reported is still running. + missing: list[str] + + +def checks_now(forge: Forge, number: str, head: str, required: set[str], run: Run, settled: bool = True) -> Pending | Failure | None: + """The checks on pull request number, whose head commit is head, read once: None where every one passed, Pending while one still runs, a CheckFailed where one failed, and any other Failure where the forge cannot be read. + + On Gitea a passed check must also match each of required: a check CI has yet to queue is no status at all. A head without any check counts as passed once settled, and as pending before, since CI may not have queued its checks yet. gh reports no check as pending before it starts, so there such a head always counts as passed. """ + if forge == "gh": + listed = run(["gh", "pr", "checks", number, "--json", "bucket"]) + if isinstance(listed, Failure): + return None if NO_CHECKS in listed.reason else listed + try: + buckets = {check["bucket"] for check in json.loads(listed)} + except (ValueError, KeyError, TypeError): + return Failure(f"gh pr checks printed no checks: {listed.strip()[:200]}") + if buckets & {"fail", "cancel"}: + return CheckFailed(f"a check on pull request {number} failed") + return Pending([]) if "pending" in buckets else None + status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") + if isinstance(status, Failure): + return status + try: + count, state = status["total_count"], status["state"] + passed = [check["context"] for check in status.get("statuses") or [] if check["status"] == "success"] + except (KeyError, TypeError, AttributeError): + return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") + if state not in ("pending", "success"): + return CheckFailed(f"a check on pull request {number} ended in {state}") + # Gitea matches a required context as a glob, and reads a commit with no status as pending, with total_count 0. + missing = sorted(pattern for pattern in required if not fnmatch.filter(passed, pattern)) + return None if (count == 0 and settled or state == "success") and not missing else Pending(missing) + + +def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None: + """None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. checks_now says what counts as passed on Gitea.""" if forge == "gh": for waited in range(0, settle + 1, POLL_SECONDS): watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"]) if not isinstance(watched, Failure): return None - if "no checks reported" not in watched.reason: + if NO_CHECKS not in watched.reason: return watched if waited < settle: sleep(POLL_SECONDS) return None - for _ in range(WAIT_SECONDS // POLL_SECONDS + 1): - status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status") - if isinstance(status, Failure): - return status - try: - count, state = status["total_count"], status["state"] - passed = [check["context"] for check in status.get("statuses") or [] if check["status"] == "success"] - except (KeyError, TypeError, AttributeError): - return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}") - if state not in ("pending", "success"): - return Failure(f"a check on pull request {number} ended in {state}") - # Gitea matches a required context as a glob, and reads a commit with no status as pending, with total_count 0. - missing = sorted(pattern for pattern in required if not fnmatch.filter(passed, pattern)) - if (count == 0 and _ * POLL_SECONDS >= settle or state == "success") and not missing: - return None - if _ < WAIT_SECONDS // POLL_SECONDS: + polls = WAIT_SECONDS // POLL_SECONDS + for poll in range(polls + 1): + now = checks_now(forge, number, head, required, run, settled=poll * POLL_SECONDS >= settle) + if not isinstance(now, Pending): + return now + if poll < polls: sleep(POLL_SECONDS) - waited_on = f"{', '.join(missing)}, which the protection requires, never passed" if missing else "a check is still pending" + waited_on = f"{', '.join(now.missing)}, which the protection requires, never passed" if now.missing else "a check is still pending" return Failure(f"gave up on pull request {number} after {WAIT_SECONDS // 60} minutes: {waited_on}") diff --git a/bin/forge/test_forge.py b/bin/forge/test_forge.py index fcc8ca70..54ab6417 100644 --- a/bin/forge/test_forge.py +++ b/bin/forge/test_forge.py @@ -6,8 +6,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from forge.pulls import checks_passed, open_pull, POLL_SECONDS, required_checks, WAIT_SECONDS +from forge.pulls import CheckFailed, checks_now, checks_passed, open_pull, Pending, POLL_SECONDS, required_checks, WAIT_SECONDS from forge.commands import forge_of, gitea, url_beside +from failure import Failure class ForgeOf(unittest.TestCase): @@ -69,6 +70,33 @@ class RequiredChecks(unittest.TestCase): self.assertEqual(required_checks("gh", "main", self.fail), set()) +class ChecksNow(unittest.TestCase): + def test_reads_on_gh_once_and_says_a_check_is_pending(self): + read = [] + self.assertEqual(checks_now("gh", "7", "abc", set(), lambda command: read.append(command) or '[{"bucket": "pass"}, {"bucket": "pending"}]'), Pending([])) + self.assertEqual(read, [["gh", "pr", "checks", "7", "--json", "bucket"]]) + + def test_takes_on_gh_passed_and_skipped_checks_and_no_checks_as_passed(self): + self.assertIsNone(checks_now("gh", "7", "abc", set(), lambda command: '[{"bucket": "pass"}, {"bucket": "skipping"}]')) + self.assertIsNone(checks_now("gh", "7", "abc", set(), lambda command: Failure("gh pr checks: no checks reported on the 'x' branch"))) + + def test_fails_on_gh_where_a_check_failed_or_was_cancelled_or_gh_fails(self): + for bucket in ("fail", "cancel"): + self.assertEqual(checks_now("gh", "7", "abc", set(), lambda command: f'[{{"bucket": "pending"}}, {{"bucket": "{bucket}"}}]'), CheckFailed("a check on pull request 7 failed")) + self.assertEqual(checks_now("gh", "7", "abc", set(), lambda command: Failure("no network")), Failure("no network")) + self.assertEqual(checks_now("tea", "1", "abc", set(), tea(['{"state": "failure", "total_count": 1}'])), CheckFailed("a check on pull request 1 ended in failure")) + self.assertEqual(checks_now("gh", "7", "abc", set(), lambda command: "[1]").reason, "gh pr checks printed no checks: [1]") + + def test_reads_on_tea_once_and_names_each_required_check_that_has_not_passed(self): + self.assertEqual(checks_now("tea", "1", "abc", {"lint"}, tea(['{"state": "pending", "total_count": 0, "statuses": []}'])), Pending(["lint"])) + self.assertEqual(checks_now("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 1}'])), Pending([])) + self.assertIsNone(checks_now("tea", "1", "abc", set(), tea(['{"state": "success", "total_count": 1}']))) + + def test_takes_a_commit_with_no_status_on_tea_as_pending_until_settled(self): + self.assertEqual(checks_now("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 0}']), settled=False), Pending([])) + self.assertIsNone(checks_now("tea", "1", "abc", set(), tea(['{"state": "pending", "total_count": 0}']))) + + class ChecksPassed(unittest.TestCase): def test_waits_on_tea_while_a_check_is_pending(self): slept = [] From 004c76679e08362332b8a0c85217a43ea9149b09 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:10:12 +0100 Subject: [PATCH 04/34] Add do-epic's gate read and parked-chunk state files --- bin/do_epic/gates.py | 98 ++++++++++++++++++++++++++++++++++++++ bin/do_epic/parked.py | 72 ++++++++++++++++++++++++++++ bin/do_epic/test_gates.py | 89 ++++++++++++++++++++++++++++++++++ bin/do_epic/test_parked.py | 55 +++++++++++++++++++++ 4 files changed, 314 insertions(+) create mode 100644 bin/do_epic/gates.py create mode 100644 bin/do_epic/parked.py create mode 100644 bin/do_epic/test_gates.py create mode 100644 bin/do_epic/test_parked.py diff --git a/bin/do_epic/gates.py b/bin/do_epic/gates.py new file mode 100644 index 00000000..f0ad0d2e --- /dev/null +++ b/bin/do_epic/gates.py @@ -0,0 +1,98 @@ +"""What the pull request of a do-epic chunk waits on, read once from its forge (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). + +A gate is something only time or a person passes: checks that still run, or an approval a reviewer has yet to give. While a chunk's pull request waits on one, its worker has nothing to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on.""" +import dataclasses +import json +import typing + +from chunk_pr.approval import waiting_threads +from failure import Failure +from forge.commands import forge_of, Run +from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks + +# What a pull request waits on, as the words after "awaits". +CHECKS = "its checks" +APPROVAL = "an approval" + + +@dataclasses.dataclass(frozen=True) +class Gate: + """The gate a chunk's open pull request waits on.""" + # The chunk's worktree, where the pull request's branch is checked out. + worktree: str + # The pull request's number. + pull: str + # CHECKS or APPROVAL. + on: str + + +@dataclasses.dataclass(frozen=True) +class Open: + """A chunk that waits on no gate, so its worker goes on.""" + # Why, as a sentence without its full stop, for the worker of a chunk that was parked. + news: str + + +def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | Open | Failure: + """What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder. A Failure where git or the forge cannot be read, which says nothing about the gate. + + A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). + """ + worktree = worktree_of(branch, at(checkout)) + if not isinstance(worktree, str): + return worktree or Open(f"no worktree of {checkout} has the branch {branch} checked out") + run = at(worktree) + read = [run(["git", *args]) for args in (["remote", "get-url", "origin"], ["rev-parse", "HEAD"], ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])] + failed = next((answer for answer in read if isinstance(answer, Failure)), None) + if failed is not None: + return failed + origin, head, base = (str(answer).strip() for answer in read) + forge = forge_of(origin) + pull = open_pull(forge, branch, head, run) + if not isinstance(pull, str): + return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}") + decision = review_decision(pull, run) if forge == "gh" else "" + if not isinstance(decision, str): + return decision or Open(f"pull request #{pull} is a draft") + required = required_checks(forge, base.removeprefix("origin/"), run) + checks = required if isinstance(required, Failure) else checks_now(forge, pull, head, required, run) + if isinstance(checks, CheckFailed): + return Open(f"{checks.reason}; fix it and push") + if isinstance(checks, Failure): + return checks + if isinstance(checks, Pending): + return Gate(worktree, pull, CHECKS) + if decision == "CHANGES_REQUESTED": + return Open(f"a reviewer requested changes on pull request #{pull}") + waiting = waiting_threads(pull, run) if forge == "gh" else [] + if isinstance(waiting, Failure): + return waiting + if waiting: + return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}") + if decision == "REVIEW_REQUIRED": + return Gate(worktree, pull, APPROVAL) + return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == "APPROVED" else "")) + + +def worktree_of(branch: str, run: Run) -> str | None | Failure: + """The worktree, of the checkout run works in, that has branch checked out; None where none has.""" + listed = run(["git", "worktree", "list", "--porcelain"]) + if isinstance(listed, Failure): + return listed + for block in listed.split("\n\n"): + lines = block.splitlines() + if f"branch refs/heads/{branch}" in lines and lines[0].startswith("worktree "): + return lines[0].removeprefix("worktree ") + return None + + +def review_decision(pull: str, run: Run) -> str | None | Failure: + """GitHub's review decision on the pull request, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. None where it is a draft.""" + viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision"]) + if isinstance(viewed, Failure): + return viewed + try: + parsed = json.loads(viewed) + return None if parsed["isDraft"] else str(parsed["reviewDecision"] or "") + except (ValueError, KeyError, TypeError): + return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") diff --git a/bin/do_epic/parked.py b/bin/do_epic/parked.py new file mode 100644 index 00000000..d8bd3131 --- /dev/null +++ b/bin/do_epic/parked.py @@ -0,0 +1,72 @@ +"""The parked chunks of an epic: each keeps its worktree, pull request and session while that pull request waits on a long gate, in a file that survives a reboot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). + +A chunk is parked from the moment its file is written until the file is removed, whatever its window does: `scheduler` starts a window again for a parked chunk that has none, and that window goes on polling.""" +import dataclasses +import json +import os +import pathlib + +from failure import Failure + +# Under the epic's folder, the folder that holds one file per parked chunk, named for its issue. +FOLDER = "parked" + + +@dataclasses.dataclass(frozen=True) +class Parked: + """A parked chunk.""" + # The key of the issue it works. + issue: str + worktree: str + # Its pull request's number. + pull: str + # The ID of its worker's claude session, which `claude --resume` takes. + session: str + # What its pull request waits on, as the words after "awaits" (`gates.CHECKS`, `gates.APPROVAL`). + on: str + + @property + def waits(self) -> str: + """Why the chunk doesn't run, for the human.""" + return f"it is parked: its pull request #{self.pull} awaits {self.on}" + + +def file_of(folder: pathlib.Path, issue: str) -> pathlib.Path: + return folder / FOLDER / f"{issue}.json" + + +def park(folder: pathlib.Path, chunk: Parked) -> Failure | None: + """Records chunk as parked under the epic's folder, in place of what was recorded for its issue. The file is whole or absent, whenever the machine stops.""" + file = file_of(folder, chunk.issue) + partial = file.with_suffix(".partial") + try: + file.parent.mkdir(parents=True, exist_ok=True) + partial.write_text(json.dumps(dataclasses.asdict(chunk), indent="\t") + "\n", encoding="utf-8") + os.replace(partial, file) + except OSError as failure: + return Failure(f"cannot record the parked chunk in {file}: {failure.strerror}") + return None + + +def unpark(folder: pathlib.Path, issue: str) -> Failure | None: + """Records that the issue's chunk is parked no longer.""" + try: + file_of(folder, issue).unlink(missing_ok=True) + except OSError as failure: + return Failure(f"cannot remove {file_of(folder, issue)}: {failure.strerror}") + return None + + +def parked_chunks(folder: pathlib.Path) -> dict[str, Parked] | Failure: + """The epic's parked chunks, by issue. A Failure where a file cannot be read as one, since a chunk taken as not parked would start a second time.""" + found: dict[str, Parked] = {} + for file in sorted((folder / FOLDER).glob("*.json")): + try: + fields = json.loads(file.read_text(encoding="utf-8")) + chunk = Parked(**fields) + except (OSError, ValueError, TypeError) as failure: + return Failure(f"cannot read the parked chunk in {file}: {failure}; fix or remove the file") + if chunk.issue != file.stem or not all(isinstance(value, str) for value in fields.values()): + return Failure(f"cannot read the parked chunk in {file}: its fields are not those of {file.stem}'s chunk; fix or remove the file") + found[chunk.issue] = chunk + return found diff --git a/bin/do_epic/test_gates.py b/bin/do_epic/test_gates.py new file mode 100644 index 00000000..6e5e03a6 --- /dev/null +++ b/bin/do_epic/test_gates.py @@ -0,0 +1,89 @@ +import json +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from do_epic.gates import APPROVAL, CHECKS, gate, Gate, Open +from failure import Failure + +WORKTREES = "worktree /code/billing\nHEAD aaa\nbranch refs/heads/main\n\nworktree /code/billing-ABC-21\nHEAD abc\nbranch refs/heads/ABC-21\n" +HEAD = "abc" * 4 + + +def thread(resolved: bool, last: str, path: str = "a.py") -> dict: + return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}} + + +class Forge: + """Stands in for git and the forge's CLI in the checkout and the chunk's worktree; `ran` holds each folder a command ran in.""" + + def __init__(self, origin: str = "git@github.com:o/billing.git", pulls: str = f"7\t{HEAD}\tfalse\n", draft: bool = False, decision: str = "REVIEW_REQUIRED", buckets: tuple[str, ...] = ("pass",), threads: tuple[dict, ...] = (), status: str = '{"state": "success", "total_count": 1}', worktrees: str = WORKTREES, fails: str = "") -> None: + self.ran: list[str] = [] + self.fails = fails + self.answers = { + "git worktree": worktrees, + "git remote": origin + "\n", + "git rev-parse": HEAD + "\n", + "git symbolic-ref": "origin/main\n", + "gh pr list": pulls, + "gh pr view": json.dumps({"isDraft": draft, "reviewDecision": decision}), + "gh pr checks": json.dumps([{"bucket": bucket} for bucket in buckets]), + "gh api graphql": json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": list(threads)}}}}}), + "tea api repos/{owner}/{repo}/pulls?state=open&limit=50": json.dumps([{"number": 7, "merged": False, "head": {"label": "ABC-21", "sha": HEAD, "repo": {"full_name": "o/billing"}}, "base": {"repo": {"full_name": "o/billing"}}}]), + "tea api repos/{owner}/{repo}/branches/main": '{"name": "main"}', + "tea api repos/{owner}/{repo}/commits/" + HEAD + "/status": status, + } + + def at(self, folder: str): + def run(command: list[str]) -> str | Failure: + self.ran.append(folder) + key = " ".join(command) if command[0] == "tea" else " ".join(command[:3] if command[0] == "gh" else command[:2]) + return Failure(f"{key} failed") if self.fails and key.startswith(self.fails) else self.answers[key] + return run + + def gate(self) -> Gate | Open | Failure: + return gate("ABC-21", "/code/billing", self.at) + + +class GateOfAChunk(unittest.TestCase): + def test_a_pull_request_whose_checks_passed_awaits_the_approval_its_protection_requires(self): + forge = Forge() + self.assertEqual(forge.gate(), Gate("/code/billing-ABC-21", "7", APPROVAL)) + self.assertEqual(set(forge.ran[1:]), {"/code/billing-ABC-21"}) + + def test_a_pull_request_awaits_its_checks_while_one_runs_whatever_its_reviews_say(self): + for decision in ("REVIEW_REQUIRED", "APPROVED", "CHANGES_REQUESTED", ""): + with self.subTest(decision=decision): + self.assertEqual(Forge(decision=decision, buckets=("pass", "pending")).gate(), Gate("/code/billing-ABC-21", "7", CHECKS)) + + def test_a_gitea_pull_request_awaits_only_its_checks(self): + gitea = "https://gitea.larvit.se/o/billing.git" + self.assertEqual(Forge(gitea, status='{"state": "pending", "total_count": 1}').gate(), Gate("/code/billing-ABC-21", "7", CHECKS)) + self.assertEqual(Forge(gitea).gate(), Open("pull request #7 passed its checks")) + + def test_the_worker_goes_on_where_nothing_but_the_worker_moves_the_pull_request(self): + cases = { + "pull request #7 passed its checks and is approved": Forge(decision="APPROVED"), + "pull request #7 passed its checks": Forge(decision=""), + "pull request #7 is a draft": Forge(draft=True, buckets=("pending",)), + "a check on pull request 7 failed; fix it and push": Forge(buckets=("fail",)), + "a reviewer requested changes on pull request #7": Forge(decision="CHANGES_REQUESTED"), + "a reviewer's comment on pull request #7 waits for an answer, in a.py, b.py": Forge(threads=(thread(False, "reviewer", "b.py"), thread(False, "reviewer"), thread(True, "reviewer", "c.py"), thread(False, "worker", "d.py"))), + "no pull request from origin's ABC-21 is open at abcabcabcabc": Forge(pulls=""), + "no worktree of /code/billing has the branch ABC-21 checked out": Forge(worktrees="worktree /code/billing\nHEAD aaa\nbranch refs/heads/main\n"), + } + for news, forge in cases.items(): + with self.subTest(news=news): + self.assertEqual(forge.gate(), Open(news)) + + def test_a_read_that_fails_is_a_failure_and_says_nothing_of_the_gate(self): + for command in ("git worktree", "git remote", "gh pr list", "gh pr view", "gh pr checks", "gh api graphql"): + with self.subTest(command=command): + self.assertEqual(Forge(fails=command).gate(), Failure(f"{command} failed")) + self.assertEqual(Forge("https://gitea.larvit.se/o/billing.git", fails="tea api repos/{owner}/{repo}/branches").gate(), Failure("tea api repos/{owner}/{repo}/branches/main failed")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/do_epic/test_parked.py b/bin/do_epic/test_parked.py new file mode 100644 index 00000000..8ea7e87e --- /dev/null +++ b/bin/do_epic/test_parked.py @@ -0,0 +1,55 @@ +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from do_epic.parked import file_of, park, Parked, parked_chunks, unpark +from failure import Failure + +CHUNK = Parked("ABC-21", "/code/billing-ABC-21", "7", "0c0f", "an approval") + + +class ParkedChunks(unittest.TestCase): + def setUp(self): + self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) + + def test_an_epic_without_a_parked_chunk_has_none(self): + self.assertEqual(parked_chunks(self.folder), {}) + + def test_a_parked_chunk_is_read_back_by_its_issue_until_it_is_unparked(self): + self.assertIsNone(park(self.folder, CHUNK)) + self.assertEqual(parked_chunks(self.folder), {"ABC-21": CHUNK}) + self.assertIsNone(unpark(self.folder, "ABC-21")) + self.assertEqual(parked_chunks(self.folder), {}) + + def test_parking_again_replaces_what_the_chunk_waits_on_and_leaves_no_partial_file(self): + park(self.folder, CHUNK) + park(self.folder, Parked("ABC-21", "/code/billing-ABC-21", "7", "0c0f", "its checks")) + self.assertEqual(parked_chunks(self.folder)["ABC-21"].on, "its checks") + self.assertEqual([file.name for file in (self.folder / "parked").iterdir()], ["ABC-21.json"]) + + def test_unparking_a_chunk_that_is_not_parked_does_nothing(self): + self.assertIsNone(unpark(self.folder, "ABC-21")) + + def test_says_why_the_human_sees_no_chunk_run(self): + self.assertEqual(CHUNK.waits, "it is parked: its pull request #7 awaits an approval") + + def test_fails_naming_the_file_where_it_holds_no_parked_chunk_or_another_issues(self): + park(self.folder, CHUNK) + file = file_of(self.folder, "ABC-21") + for text in ("{", '{"issue": "ABC-21"}', file.read_text().replace("ABC-21", "ABC-22"), file.read_text().replace('"7"', "7")): + with self.subTest(text=text): + file.write_text(text) + failed = parked_chunks(self.folder) + self.assertIsInstance(failed, Failure) + self.assertIn(f"cannot read the parked chunk in {file}: ", failed.reason) + + def test_fails_where_the_folder_cannot_be_written(self): + (self.folder / "parked").write_text("a file") + self.assertIn(f"cannot record the parked chunk in {file_of(self.folder, 'ABC-21')}: ", park(self.folder, CHUNK).reason) + + +if __name__ == "__main__": + unittest.main() From 1df19f4ac858f34eea172b8a4d42c5f1a803f067 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:11:31 +0100 Subject: [PATCH 05/34] Keep a parked chunk out of the epic's and its repo's running slots --- bin/agent_cycle/tmux.py | 28 +++++++++- bin/do_epic/scheduler.py | 50 ++++++++++++++--- bin/do_epic/test_main.py | 2 +- bin/do_epic/test_scheduler.py | 80 ++++++++++++++++++++++++++- bin/loop_claude/loop/chunk_windows.py | 4 +- 5 files changed, 148 insertions(+), 16 deletions(-) diff --git a/bin/agent_cycle/tmux.py b/bin/agent_cycle/tmux.py index e3b50631..4c632ef0 100644 --- a/bin/agent_cycle/tmux.py +++ b/bin/agent_cycle/tmux.py @@ -14,6 +14,8 @@ NEEDED = (3, 2) # What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang. WAITS = " ?" BELL = "\a" +# What follows a window's name while its chunk is parked, before what its pull request waits on, as in `ABC-34 awaits an approval`. A parked chunk takes no running slot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). +PARKED = " awaits " # What a session's name opens with: LOOP for a project's chunks under loop-claude, EPIC for an epic's chunks under do-epic. LOOP = "loop" EPIC = "epic" @@ -41,12 +43,14 @@ class Window: @dataclasses.dataclass(frozen=True) class Listed: """A window of the project's session, as tmux lists it.""" - # Without WAITS. + # Without WAITS, and without PARKED and what follows it. name: str # tmux's ID of the window, such as `@3`. id: str # Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable. dead: bool + # Whether its chunk is parked: its name held PARKED. + parked: bool = False @dataclasses.dataclass(frozen=True) @@ -76,14 +80,20 @@ def listed(session: str, run: Tmux) -> list[Listed]: """The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs.""" done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else [] - return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3] + return [as_listed(row[0], row[2], row[1]) for row in rows if len(row) == 3] + + +def as_listed(shown: str, id: str, pane_dead: str) -> Listed: + """The window tmux shows under the name shown, with the ID id and `#{pane_dead}` as pane_dead.""" + name, parked, _ = shown.removesuffix(WAITS).partition(PARKED) + return Listed(name, id, pane_dead == "1", bool(parked)) def everywhere(run: Tmux) -> list[Placed]: """The windows of every session; none where no tmux server runs.""" done = run(["list-windows", "-a", "-F", f"#{{session_name}}\t#{{window_name}}\t#{{pane_dead}}\t#{{window_id}}\t#{{{ROOT}}}"]) rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else [] - return [Placed(row[0], Listed(row[1].removesuffix(WAITS), row[3], row[2] == "1"), row[4]) for row in rows if len(row) == 5] + return [Placed(row[0], as_listed(row[1], row[3], row[2]), row[4]) for row in rows if len(row) == 5] def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, owned: bool, run: Tmux) -> Failure | None: @@ -131,6 +141,18 @@ def mark(window: Window, waits: bool, run: Tmux) -> None: run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")]) +def park(window: Window, on: str, run: Tmux) -> None: + """Shows window's chunk as parked while its pull request awaits on, such as `an approval`: the name says so, and the window names no folder its chunk works in, so no checkout counts it as a running chunk.""" + run(["rename-window", "-t", window.pane, window.name + PARKED + on]) + run(["set-option", "-w", "-u", "-t", window.pane, ROOT]) + + +def unpark(window: Window, root: str, run: Tmux) -> None: + """Shows window's chunk as running again, in the folder root.""" + run(["rename-window", "-t", window.pane, window.name]) + run(["set-option", "-w", "-t", window.pane, ROOT, root]) + + def show(session: str, inside: bool) -> list[str]: """The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches.""" return ["switch-client" if inside else "attach-session", "-t", f"={session}"] diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 04250a47..c3e2ef3a 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -1,11 +1,13 @@ """Which of an epic's issues run as chunks now, each in its own window of the epic's tmux session (docs/decisions.md → `do-epic: drives one Jira epic …`). -Three limits hold a chunk back: the epic's cap of chunks at once, its repo's `parallel-chunks`, counted across every epic, and a loop-claude that runs chunks in its repo. do-epic checks a repo and starts a chunk in it while holding the lock loop-claude holds when it starts one (`chunk_windows.starting`), so the two never start chunks in one checkout together.""" +Three limits hold a chunk back: the epic's cap of chunks at once, its repo's `parallel-chunks`, counted across every epic, and a loop-claude that runs chunks in its repo. A parked chunk (`parked`) counts toward none of them: its window only polls the forge, and `resume` takes it a slot under the same limits once its worker has something to do. do-epic checks a repo and starts a chunk in it while holding the lock loop-claude holds when it starts one (`chunk_windows.starting`), so the two never start chunks in one checkout together.""" import dataclasses import pathlib import typing +from chunk_pr.approval import PARKS from do_epic.epic_record import CAP +from do_epic.parked import parked_chunks from loop_claude.loop.chunk_windows import epic_chunks, HANDED, LOCK, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure @@ -107,24 +109,33 @@ def refusal(repo: str, room: RepoRoom) -> str | None: def start_chunks(epic: Epic, issues: list[EpicIssue], own: str | None, run: tmux.Tmux) -> Started | Failure: - """Starts a do-epic in a new window for each of the epic's chunks that may start now. own is the issue of the chunk that asks, which has finished: it counts as running nowhere, and no stopped chunk starts again. Where own is None, the human's `do-epic ` asks, and each stopped chunk starts again. A Failure says why a window could not start; those before it run.""" + """Starts a do-epic in a new window for each of the epic's chunks that may start now. own is the issue of the chunk that asks, which has finished 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) started: list[str] = [] + parked = parked_chunks(epic.folder) + if isinstance(parked, Failure): + return parked try: with starting(epic.folder): windows = tmux.listed(session, run) - running = {window.name for window in windows if not window.dead} - {own} - stopped = {window.name for window in windows if window.dead} - running + live = {window.name for window in windows if not window.dead} - {own} + running = {window.name for window in windows if not window.dead and not window.parked} - {own} + stopped = {window.name for window in windows if window.dead} - live + # The windows this call started that take a running slot. + taken = 0 for chunk in found: if chunk.issue in running or chunk.issue == own: continue - if own and chunk.issue in stopped: + if chunk.issue in parked and chunk.issue in live: + waits.append(Waits(chunk.issue, parked[chunk.issue].waits)) + elif own and (chunk.issue in stopped or chunk.issue in parked): waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again")) - elif len(running) + len(started) >= epic.cap: + elif chunk.issue not in parked and len(running) + taken >= epic.cap: waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}")) else: - now = start_chunk(epic, chunk, own, windows, run) + now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run) + taken += chunk.issue not in parked if isinstance(now, Failure): return now if isinstance(now, str): @@ -138,9 +149,10 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], own: str | None, run: tmux def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure: - """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none. It holds the repo's lock from the check to the start. Raises OSError where that lock cannot be taken.""" + """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none. It holds the repo's lock from the check to the start. Raises OSError where that lock cannot be taken. A chunk without a repo starts in the epic's folder, as a parked chunk does, which takes no room in its repo.""" session = tmux.session_name(tmux.EPIC, epic.key) - handed = {name: value for name, value in epic.env.items() if name.startswith(HANDED)} + # PARKS reaches the chunk's worker, so its `chunk-pr merge` doesn't wait for an approval the parked chunk waits for. + handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"} command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key] if chunk.repo is None: return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), handed, command, windows, False, run) @@ -160,3 +172,23 @@ def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pa loop_session = tmux.session_name(tmux.LOOP, project_key(checkout, home)) loops = any(not window.dead for window in tmux.listed(loop_session, run)) and tmux.owner(loop_session, run) == checkout return RepoRoom(limit, len(theirs), loops) + + +def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None: + """Takes a running slot for the parked chunk in window, which changes repo and whose worker has something to do again: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks.""" + try: + with starting(epic.folder): + running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked] + if len(running) >= epic.cap: + return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}" + located = epic.locate(repo) + if isinstance(located, Failure): + return located.reason + checkout, limit = located + with starting(project_lock(str(checkout), epic.home)): + if reason := refusal(repo, room_in(str(checkout), limit, (window.session, None), epic.home, run)): + return reason + tmux.unpark(window, str(checkout), run) + return None + except OSError as failure: + return f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}" diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index de1b1e9a..78913c1f 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -89,7 +89,7 @@ class TheCommand(DoEpicTest): self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out) self.assertIn("ABC-20 waits: no label names its repo\n", out) started = [args for args in fake.tmux_calls if args[0] == "new-session"] - self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) + self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) # The session is no checkout's, so nothing marks it as one's. self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"]) diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index 3cbd3b61..b4ade50b 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -6,7 +6,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from do_epic.scheduler import Chunk, CHUNK_FLAG, chunks, Epic, refusal, RepoRoom, start_chunks, Started, Waits +from do_epic.scheduler import Chunk, CHUNK_FLAG, chunks, Epic, refusal, RepoRoom, resume, start_chunks, Started, Waits +from do_epic.parked import file_of, park, Parked from do_epic import chunk_prompt from do_epic.backend.protocol import EpicIssue from failure import Failure @@ -102,6 +103,12 @@ class Tmux: session = args[args.index("-s") + 1] if args[0] == "new-session" else args[args.index("-t") + 1].removeprefix("=").removesuffix(":") self.windows.append((session, args[args.index("-n") + 1], False, args[args.index("-c") + 1])) out = f"@{len(self.windows) - 1}\n" + elif args[0] == "rename-window": + at = int(args[2].removeprefix("%")) + self.windows[at] = (self.windows[at][0], args[3], *self.windows[at][2:]) + elif args[0] == "set-option" and tmux.ROOT in args: + at = int(args[args.index("-t") + 1].removeprefix("%").removeprefix("@")) + self.windows[at] = (*self.windows[at][:3], "" if "-u" in args else args[-1]) elif args[0] == "kill-window": self.windows[int(args[2].removeprefix("@"))] = ("", "", True, "") return subprocess.CompletedProcess(args, 0, out, "") @@ -137,6 +144,77 @@ class StartingAnEpicsChunks(unittest.TestCase): self.assertIn("LOOP_CLAUDE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")]) self.assertNotIn("OTHER=2", run.calls[[args[0] for args in run.calls].index("new-session")]) + def parked(self, issue_key: str, on: str = "an approval") -> None: + self.assertIsNone(park(self.home / ".local/state/do-epic/ABC-12", Parked(issue_key, f"/code/api-{issue_key}", "7", "0c0f", on))) + + def test_a_parked_chunk_waits_in_its_window_and_takes_no_slot_of_the_epic_or_its_repo(self) -> None: + self.parked("ABC-20") + run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")) + found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api", blockers=("ABC-20",))], run) + self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "it is parked: its pull request #7 awaits an approval"), Waits("ABC-22", "ABC-20 blocks it")])) + + def test_a_parked_chunk_without_a_window_starts_again_whatever_the_limits_in_the_epics_folder(self) -> None: + self.parked("ABC-20") + for windows in ((), (("epic-ABC-12", "ABC-20 awaits an approval", True, ""),)): + with self.subTest(windows=windows): + run = Tmux(*windows, ("epic-ABC-12", "ABC-21", False, str(self.home / "code/api"))) + found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], run) + self.assertEqual(found, Started(["ABC-20"], [])) + self.assertEqual(run.windows[-1], ("epic-ABC-12", "ABC-20", False, str(self.home / ".local/state/do-epic/ABC-12"))) + self.assertEqual([name for _, name, dead, _ in run.windows if dead], [""] * len(windows)) + + def test_a_parked_chunk_that_starts_again_leaves_the_epics_cap_to_the_others(self) -> None: + self.parked("ABC-20") + found = self.start(self.epic(1, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], Tmux()) + self.assertEqual(found, Started(["ABC-20", "ABC-21"], [])) + + def test_a_chunk_that_hands_on_starts_no_parked_chunk_whose_window_stopped(self) -> None: + self.parked("ABC-20") + found = self.start(self.epic(2, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], Tmux(), own="ABC-21") + self.assertEqual(found, Started([], [Waits("ABC-20", "its window stopped; run `do-epic ABC-12` to start it again")])) + + def test_a_chunk_that_parks_frees_its_slot_for_the_next(self) -> None: + self.parked("ABC-20") + run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")) + found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], run, own="ABC-20") + self.assertEqual(found, Started(["ABC-21"], [])) + + def test_stops_on_a_parked_chunk_it_cannot_read_and_starts_none(self) -> None: + self.parked("ABC-20") + file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20").write_text("{") + run = Tmux() + found = start_chunks(self.epic(2, api=2), [issue("ABC-21", "repo:api")], None, run) + assert isinstance(found, Failure) + self.assertIn("cannot read the parked chunk in ", found.reason) + self.assertEqual(run.started(), []) + + def test_hands_each_chunk_the_variable_that_makes_its_merge_park(self) -> None: + run = Tmux() + self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], run) + self.assertIn("CHUNK_PR_PARKS=1", run.calls[[args[0] for args in run.calls].index("new-session")]) + + def resumed(self, epic: Epic, run: Tmux) -> str | None: + """resume for the parked chunk in the first window, which changes the repo api.""" + return resume(epic, "api", tmux.Window("epic-ABC-12", "ABC-20", "%0"), run) + + def test_a_parked_chunk_resumes_into_a_free_slot_and_counts_in_its_repo_again(self) -> None: + run = Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, ""), ("epic-ABC-12", "ABC-21 awaits its checks", False, "")) + self.assertIsNone(self.resumed(self.epic(1, api=1), run)) + self.assertEqual(run.windows[0], ("epic-ABC-12", "ABC-20", False, str(self.home / "code/api"))) + + def test_a_parked_chunk_stays_parked_while_the_epic_or_its_repo_is_full(self) -> None: + parked = ("epic-ABC-12", "ABC-20 awaits an approval", False, "") + cases = { + "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1": (self.epic(1, api=2), Tmux(parked, ("epic-ABC-12", "ABC-21", False, str(self.home / "code/web")))), + "api runs as many chunks as its `parallel-chunks` allows: 1": (self.epic(2, api=1), Tmux(parked, ("epic-XYZ-1", "XYZ-5", False, str(self.home / "code/api")))), + "loop-claude runs chunks in api": (self.epic(2, api=1), Tmux(parked, ("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})), + "no project config names api": (self.epic(2), Tmux(parked)), + } + for reason, (epic, run) in cases.items(): + with self.subTest(reason=reason): + self.assertEqual(self.resumed(epic, run), reason) + self.assertEqual(run.windows[0], parked) + def test_a_running_chunk_counts_and_is_not_started_twice(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20 ?", False, str(self.home / "code/api"))) found = self.start(self.epic(2, api=2), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run) diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index f6ceea41..ba3e82ad 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -66,8 +66,8 @@ def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: def epic_chunks(root: str, run: tmux.Tmux) -> list[tmux.Placed]: - """The windows of do-epic's sessions whose chunks run in the checkout root.""" - return [placed for placed in tmux.everywhere(run) if placed.session.startswith(f"{tmux.EPIC}-") and placed.root == root and not placed.window.dead] + """The windows of do-epic's sessions whose chunks run in the checkout root. A parked chunk doesn't run.""" + return [placed for placed in tmux.everywhere(run) if placed.session.startswith(f"{tmux.EPIC}-") and placed.root == root and not placed.window.dead and not placed.window.parked] def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]: From d0ecdd6359983814c0282905b6f768f6e7e55c5e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:13:43 +0100 Subject: [PATCH 06/34] File a finding and record a decision in a do-epic epic, and give the judge the epic's records beside the repo's --- README.md | 4 +- bin/agent_cycle/judge.py | 4 +- bin/agent_cycle/run.py | 1 + bin/agent_cycle/worker_prompts.py | 2 + bin/do_epic/chunk_prompt.py | 13 +++- bin/do_epic/epic_record.py | 13 ++++ bin/do_epic/findings.py | 59 +++++++++++++++ bin/do_epic/main.py | 42 +++++++++-- bin/do_epic/test_findings.py | 111 ++++++++++++++++++++++++++++ bin/do_epic/test_main.py | 15 +++- bin/do_epic/test_scheduler.py | 2 +- bin/judge_replay/main.py | 4 +- bin/loop_claude/cycle/prompts.py | 15 +++- bin/loop_claude/project/records.py | 25 ++++--- bin/loop_claude/test_loop_claude.py | 35 ++++++--- bin/text_files/piped_text.py | 6 ++ bin/todo_item/main.py | 7 +- docs/reading-cost.md | 22 ++++++ skills/larv-review/SKILL.md | 1 + 19 files changed, 334 insertions(+), 47 deletions(-) create mode 100644 bin/do_epic/findings.py create mode 100644 bin/do_epic/test_findings.py create mode 100644 bin/text_files/piped_text.py diff --git a/README.md b/README.md index 1da63f00..7515b10d 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. - `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`. `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. Beside it, `chunk_prompt.py` words what a chunk's worker reads. `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, and posts comments. +- `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`. `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. Beside it, `chunk_prompt.py` words what a chunk's worker reads. `findings.py` is what that worker writes into the epic: `do-epic --file` files a finding as an issue of the epic, and `--record-decision` appends a decision to its description. `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, and posts comments. - `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and waits for its checks (`pulls.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 `loop_claude`'s premises, records and `ANSWER_DESTINATIONS`. @@ -237,7 +237,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `loop_claude`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. - `test_env.py` serves the tests. -- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. +- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. ## Test diff --git a/bin/agent_cycle/judge.py b/bin/agent_cycle/judge.py index 993ebf85..3591a649 100644 --- a/bin/agent_cycle/judge.py +++ b/bin/agent_cycle/judge.py @@ -141,6 +141,8 @@ class Brief(typing.NamedTuple): task: str premises: str records: str + # What the records are, in their order, as WorkerPrompts.records_named has it. + records_named: str # Where the worker may record an answer the human typed, as the entry point names it. answer_destinations: str entries: list[Entry] @@ -290,7 +292,7 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]: """The prompt, and what the judge's quotes are checked against.""" head = ( f"From the goals file, {brief.premises}\n\n" - f"The records: the project's working rules and decisions, then the human's rules for every project:\n{brief.records or 'none'}\n\n" + f"The records: {brief.records_named}:\n{brief.records or 'none'}\n\n" f"{TASK_HEADING}{brief.task}\n\n" f"{transcript_heading(brief.driver)}" ) diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 98bf2bf8..a836cb47 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -156,6 +156,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto task=cycle.task, premises=cycle.premises, records=cycle.records, + records_named=cycle.prompts.records_named, answer_destinations=cycle.prompts.answer_destinations, entries=entries, escalated_at=cycle.route.escalated_at, diff --git a/bin/agent_cycle/worker_prompts.py b/bin/agent_cycle/worker_prompts.py index 25f9c931..9c070afb 100644 --- a/bin/agent_cycle/worker_prompts.py +++ b/bin/agent_cycle/worker_prompts.py @@ -45,6 +45,8 @@ class WorkerPrompts: quote_sources: str # Where the worker may record an answer the human typed. answer_destinations: str + # What the records the judge reads are, in the order it reads them. + records_named: str def answered(self, question: str, answer: str, route: Route, project: ProjectRung | None, stepped: bool) -> str: """stepped is whether the answer's ruling stepped the worker up.""" diff --git a/bin/do_epic/chunk_prompt.py b/bin/do_epic/chunk_prompt.py index 3de4876d..f2128c06 100644 --- a/bin/do_epic/chunk_prompt.py +++ b/bin/do_epic/chunk_prompt.py @@ -1,5 +1,8 @@ """What a do-epic cycle's worker is told: its task, from the issue, and its first prompt. The resumed prompt and the rung sentences are the ones loop-claude's cycles use, naming do-epic.""" from do_epic.backend.protocol import EpicIssue +from do_epic import findings +from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES +from text_files.markdown_text import listed from model_routing.ladder import ProjectRung from loop_claude.cycle import prompts from model_routing.route import Route @@ -11,7 +14,7 @@ DRIVER = "do-epic" def task(issue: EpicIssue, epic: str, checkout: str | None) -> str: """The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None.""" where = f"in the checkout {checkout}, on the branch {issue.key}" if checkout else "which changes no repo: work in the folder you start in" - return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "") + return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {findings.instructions(epic)} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "") CODE_HEALTH = '~/.claude/CLAUDE.md → "Shared goal"' @@ -25,4 +28,10 @@ def fresh(task: str, premises: str, route: Route, project: ProjectRung | None, f # The worker names no plan items: the chunk's one item is its issue. -WORKER = prompts.worker_prompts(DRIVER, fresh, "") +# The epic's records come first, as its goals do; a chunk without a repo has only those and the human's rules. +NAMES = prompts.RecordNames( + quote_sources=listed(("the epic's description", "the repo's goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or"), + answer_destinations="the epic's description under ## Decisions, the repo's goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the repo's plan or a comment", + records_named="the epic's scoring and decisions, then the repo's working rules and decisions, then the human's rules for every project", +) +WORKER = prompts.worker_prompts(DRIVER, fresh, "", NAMES) diff --git a/bin/do_epic/epic_record.py b/bin/do_epic/epic_record.py index fb302034..2e8b5490 100644 --- a/bin/do_epic/epic_record.py +++ b/bin/do_epic/epic_record.py @@ -110,6 +110,19 @@ class EpicRecord: """Writes body as the ## name section. approved says the human approved the change in an interrupt, which Goals and Audience need.""" return self.written(lambda text: with_section(text, name, body), frozenset({name}) if approved else frozenset()) + def append_decision(self, title: str, entry: str) -> Held | Failure: + """Adds entry under a ### title heading at the end of ## Decisions, leaving the decisions before it as they are.""" + if not title.strip() or "\n" in title: + return Failure("the title must be one line of text") + if not entry.strip(): + return Failure("pipe the decision's text in") + + def appended(text: str) -> str | Failure: + before = read_section(text, "Decisions") + return before if isinstance(before, Failure) else with_section(text, "Decisions", f"{before}\n\n### {title.strip()}\n\n{entry.strip()}".strip()) + + return self.written(appended, frozenset()) + def write_language(self, language: str) -> Held | Failure: return self.written(lambda text: with_language(text, language), frozenset()) diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py new file mode 100644 index 00000000..d15cc7db --- /dev/null +++ b/bin/do_epic/findings.py @@ -0,0 +1,59 @@ +"""What a chunk's worker writes into its epic: a finding, filed as an issue, and a decision, appended to the description. + +A finding about one of the epic's goals is filed in the epic, and one about a repo's goals by that repo's rules (docs/decisions.md → `do-epic: drives one Jira epic …` → "Findings"). A decision that governs the epic goes under the description's ## Decisions, where the judge of each later chunk reads it.""" +import typing + +from do_epic.backend.protocol import EpicStore +from do_epic.epic_record import EpicRecord +from failure import Failure +from text_files.piped_text import piped + +# Three readers, seated as the human and as a chunk's worker, ranked four spellings of each flag: ` --file` came first, second and second, ahead of `--file `, `add` and `--finding`; `--record-decision` won 2-1 over `--decision`, since `--decide` reads as do-epic deciding. +FILE = "--file" +LABEL = "--label" +RECORD_DECISION = "--record-decision" +USAGE = f"""do-epic {FILE} [{LABEL}