From f9615cb3b0d69b7b42328bfbc6d77c5a9813ee74 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 00:29:24 +0200 Subject: [PATCH 01/22] Run a preflight before each fresh worker and put its facts in the worker's prompt --- .gitignore | 3 + CHANGELOG.md | 1 + README.md | 3 +- bin/chunk-preflight | 9 + bin/chunk_preflight/__init__.py | 0 bin/chunk_preflight/facts.py | 26 +++ bin/chunk_preflight/main.py | 179 ++++++++++++++++++ bin/chunk_preflight/test_chunk_preflight.py | 162 ++++++++++++++++ bin/git_repo.py | 7 + bin/judge_replay/test_judge_replay.py | 2 +- bin/larv_review/git.py | 12 +- bin/loop_claude/cycle/prompts.py | 16 +- bin/loop_claude/cycle/run.py | 18 +- bin/loop_claude/effects.py | 6 + bin/loop_claude/loop/main.py | 7 +- bin/loop_claude/routing.py | 12 +- bin/loop_claude/test_black_box.py | 1 + bin/loop_claude/test_loop_claude.py | 66 +++++-- bin/rank_todo.py | 23 +-- bin/stability_replay/test_stability_replay.py | 2 +- bin/todo_table.py | 31 +++ todo.md | 22 +-- 22 files changed, 532 insertions(+), 76 deletions(-) create mode 100755 bin/chunk-preflight create mode 100644 bin/chunk_preflight/__init__.py create mode 100644 bin/chunk_preflight/facts.py create mode 100644 bin/chunk_preflight/main.py create mode 100644 bin/chunk_preflight/test_chunk_preflight.py diff --git a/.gitignore b/.gitignore index cbc50bba..e39d52e3 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,9 @@ !agents/ !agents/*.md !bin/ +!bin/chunk-preflight +!bin/chunk_preflight/ +!bin/chunk_preflight/*.py !bin/claude_code/ !bin/claude_code/*.py !bin/comprehension_history.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 94aae989..cbcdcfbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names. - `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`. - `loop-claude` archives each judge reply it rejects in the chunk's `.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1. +- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before each chunk's first worker, `loop-claude` runs it and quotes what it printed in the worker's prompt. It names the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. ## 0.1.0 diff --git a/README.md b/README.md index 15da6745..a39f9a87 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. +- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before each chunk's first worker, and `chunk-preflight --help` lists the facts. - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places; `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. @@ -109,7 +110,7 @@ pytest_add_cli_args=-k Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show ` to see a mutant's change. The config keys are mutmut 3's. -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge. `judge_replay` and `stability_replay` share `rung_replay/`: the rung search, and the argument, candidate rungs and exits. It reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `stability_replay` share `rung_replay/`: the rung search, and the argument, candidate rungs and exits. It reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself. ## Tracking a new file diff --git a/bin/chunk-preflight b/bin/chunk-preflight new file mode 100755 index 00000000..4a0ec9bb --- /dev/null +++ b/bin/chunk-preflight @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from chunk_preflight import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/chunk_preflight/__init__.py b/bin/chunk_preflight/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py new file mode 100644 index 00000000..7d730af9 --- /dev/null +++ b/bin/chunk_preflight/facts.py @@ -0,0 +1,26 @@ +import re + +from markdown_text import sections +from todo_table import Item + + +def unreleased_entries(changelog: str) -> int | None: + """How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section.""" + found = sections(changelog).get("Unreleased") + return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) + + +def bundle_candidates(found: list[Item], first: Item) -> list[Item]: + """The items of first's release, in the table's order, that a chunk taking first may take too: no question, and none blocked by an item outside first and these.""" + candidates = {item.id for item in found if item.release == first.release and item.id != first.id and item.exempt != "question"} + held = {item.id for item in found} + while blocked := {item.id for item in found if item.id in candidates and (held & set(item.blocked_by)) - candidates - {first.id}}: + candidates -= blocked + return [item for item in found if item.id in candidates] + + +def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]: + """Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file.""" + spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text)) + held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans) + return [(span, count) for span, count in held if count] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py new file mode 100644 index 00000000..fcd47f15 --- /dev/null +++ b/bin/chunk_preflight/main.py @@ -0,0 +1,179 @@ +"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker reads them rather than finding them. + +usage: chunk-preflight + +Run it inside a project checkout. loop-claude runs it at the checkout root before each fresh worker, +and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that +remote, and reads origin's default branch, or else the local main or master, as larv-review does. +It then prints: + +- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md + holds under ## Unreleased, or else how many commits followed the tag; +- the next release in the default branch's todo.md, and that release's first item that does not + wait, as loop-claude routes on, with its L and E + I; +- the item's worktree: a sibling of the checkout named -item-, on the branch + item-. It continues a worktree already on that branch; else it adds one on the local branch, + else on a new branch tracking origin's, else on a new branch off the default branch; +- the open pull requests, as gh lists them on a github.com origin, and else as tea does; +- the items of that release that a chunk taking the item may take too: none is a question, and no + item outside them and the item blocks one; +- each file or folder git tracks that the item's tagline or detail names in backticks, with a + file's lines or a folder's files, and the item's tagline and detail; +- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run `, `reading-cost` and + `larv-review places` print in the worktree, each with its exit code. reading-cost appends to the + worktree's docs/reading-cost.md, for the chunk to commit. + +A fact it cannot find it says it cannot, and why, and goes on. With no item, it makes no worktree +and runs none of those four tools. + +Exit 1, saying why, on any argument, or when git cannot start or finds no checkout. +""" +import pathlib +import subprocess +import sys + +from chunk_preflight.facts import bundle_candidates, named_paths, unreleased_entries +from failure import Failure +from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top +from markdown_text import quoted +from todo_table import Item, item_details, items, next_item + +BIN = pathlib.Path(__file__).resolve().parents[1] +# A tool or forge CLI still running after this many seconds is stopped, so a hung one cannot hold the loop. +TIMEOUT = 300 + + +def main(argv: list[str]) -> int: + if argv in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if argv: + print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr) + return 1 + root = top() + if isinstance(root, Failure): + print(root.reason, file=sys.stderr) + return 1 + print("\n".join(preflight(pathlib.Path(root)))) + return 0 + + +def preflight(root: pathlib.Path) -> list[str]: + branch = default_branch(stale_ok=True) + if isinstance(branch, Failure): + return [f"- No default branch: {branch.reason}"] + default, note = branch + found = [f"- {note}"] if note else [] + found.append(f"- {last_release(default)}") + todo = file_at(default, "todo.md") + planned = todo if isinstance(todo, Failure) else items(todo) + if isinstance(planned, Failure): + return [*found, f"- No plan item: {default}'s todo.md: {planned.reason}", *pull_requests(root)] + first = next_item(planned or []) + if first is None: + why = f"every item of {default}'s next release waits" if planned else f"{default} holds no todo.md items table" + return [*found, f"- No plan item: {why}, so no worktree was made.", *pull_requests(root)] + assert isinstance(todo, str) and planned + found.append(f"- Next release: {release_name(first)}. Its first item that does not wait: item {first.id}, L {first.likelihood or 'unscored'}, E + I {first.escape_and_impact or 'unscored'}.") + worktree = item_worktree(root, f"item-{first.id}", default) + found.append(f"- Worktree: {worktree.reason}" if isinstance(worktree, Failure) else f"- Worktree: {worktree[0]}, {worktree[1]}") + found += pull_requests(root) + found += bundled(planned, first) + details = item_details(todo) + detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" + text = f"{first.tagline}\n\n{detail}".strip() + found += named(text, worktree[0] if isinstance(worktree, tuple) else root) + found.append(f"\nItem {first.id}'s tagline and detail:\n\n{quoted(text)}") + if isinstance(worktree, tuple): + for args in (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", str(first.id)), ("reading-cost",), ("larv-review", "places")): + found.append(f"\n{printed(args, [sys.executable, str(BIN / args[0]), *args[1:]], worktree[0])}") + return found + + +def last_release(default: str) -> str: + tag = newest_release_tag(default) + if isinstance(tag, Failure): + return f"Last version cut: cannot be read: {tag.reason}" + changelog = file_at(default, "CHANGELOG.md") + entries = unreleased_entries(changelog) if isinstance(changelog, str) else None + if entries is not None: + return f"Last version cut: {tag or 'none'}. Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." + commits = git("rev-list", "--count", f"{tag}..{default}" if tag else default) + since = f"since {tag}" if tag else f"on {default}" + return f"Last version cut: {tag or 'none'}. Unreleased: {commits.reason if isinstance(commits, Failure) else counted(int(commits), 'commit', 'commits')} {since}, and no ## Unreleased in CHANGELOG.md." + + +def item_worktree(root: pathlib.Path, branch: str, default: str) -> tuple[pathlib.Path, str] | Failure: + """The worktree on branch, and how it came to be; a Failure where git cannot make it, or its path holds something else.""" + held = git("worktree", "list", "--porcelain") + if isinstance(held, Failure): + return held + for block in held.split("\n\n"): + fields = dict(line.partition(" ")[::2] for line in block.splitlines()) + if fields.get("branch") == f"refs/heads/{branch}": + return pathlib.Path(fields["worktree"]), f"on the branch {branch}, which it already held." + path = root.parent / f"{root.name}-{branch}" + if path.exists(): + return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}") + if commit_exists(f"refs/heads/{branch}"): + added, how = git("worktree", "add", "--quiet", str(path), branch), f"on the branch {branch}, which existed already." + elif commit_exists(f"refs/remotes/origin/{branch}"): + added, how = git("worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"), f"on the new branch {branch}, made off origin/{branch}." + else: + # --no-track: tracking the default branch would point a bare `git push` at it. + added, how = git("worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default), f"on the new branch {branch}, made off {default}." + return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else (path, how) + + +def pull_requests(root: pathlib.Path) -> list[str]: + url = git("remote", "get-url", "origin") + if isinstance(url, Failure): + return ["- Open pull requests: none, as the checkout has no origin remote."] + command = ["gh", "pr", "list"] if "github.com" in url else ["tea", "pulls", "list", "--fields", "index,title,head,state", "--output", "tsv"] + return [f"- Open pull requests: {printed(tuple(command), command, root)}"] + + +def bundled(planned: list[Item], first: Item) -> list[str]: + candidates = bundle_candidates(planned, first) + if not candidates: + return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."] + listed = [f" - item {item.id}, L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates] + return [f"- The items of release {release_name(first)} that item {first.id}'s chunk may take too, where `~/.claude/CLAUDE.md` → \"Working loop\" lets them share it:", *listed] + + +def named(text: str, base: pathlib.Path) -> list[str]: + tracked = git("-C", str(base), "ls-files") + if isinstance(tracked, Failure): + return [f"- The files the item names: cannot be listed: {tracked.reason}"] + paths = named_paths(text, tracked.splitlines()) + if not paths: + return ["- The item names no file or folder git tracks."] + return ["- The files and folders the item names:", *(f" - `{span}`: {size(base / span, count)}" for span, count in paths)] + + +def size(path: pathlib.Path, files: int) -> str: + if not path.is_file(): + return counted(files, "file", "files") + try: + return counted(len(path.read_text(encoding="utf-8").splitlines()), "line", "lines") + except (OSError, UnicodeDecodeError) as failure: + return f"cannot be read: {failure}" + + +def printed(shown: tuple[str, ...], command: list[str], cwd: pathlib.Path) -> str: + """What command printed, run in cwd, and its exit code, under its name as shown.""" + name = f"`{' '.join(shown)}`" + try: + done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) + except (OSError, subprocess.TimeoutExpired) as failure: + return f"{name} could not finish: {failure}" + output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip()) + return f"{name} exited {done.returncode}, printing:\n\n{quoted(output)}" if output else f"{name} exited {done.returncode}, printing nothing." + + +def release_name(item: Item) -> str: + return ".".join(map(str, item.release)) + + +def counted(count: int, one: str, many: str) -> str: + return f"{count} {one if count == 1 else many}" diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py new file mode 100644 index 00000000..1f3831cb --- /dev/null +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -0,0 +1,162 @@ +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from chunk_preflight import facts +from test_env import isolated_env +from todo_table import items + +BIN = pathlib.Path(__file__).resolve().parents[1] +README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n" +# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release. +TODO = """# todo + +## Scoring + +`Score = 100 * V / (2**S + 8)` + +`Bar = 0.1` + +`Next ID = 10` + +## Items + +| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 | +| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 | +| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 | +| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 | +| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 | + +## Details + +### 3. Do the next thing. + +Change `src/app.py`'s `run` and the files under `src`, not `gone.py`. +""" +CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" +# Prints its arguments, then two open pull requests, as `tea pulls list --output tsv` does. +FAKE_TEA = "#!/bin/sh\necho \"tea $*\"\nprintf 'index\\ttitle\\thead\\tstate\\n12\\tWIP: the next thing\\titem-3\\topen\\n'\n" + + +class Repo: + """An origin with a tagged release, a clone of it at /proj, and a fake tea on PATH.""" + + def __init__(self, test, todo=TODO): + temp = tempfile.TemporaryDirectory() + test.addCleanup(temp.cleanup) + self.temp = pathlib.Path(os.path.realpath(temp.name)) + self.origin = self.temp / "origin.git" + self.root = self.temp / "proj" + fake = self.temp / "fake-bin" + fake.mkdir() + (fake / "tea").write_text(FAKE_TEA) + (fake / "tea").chmod(0o755) + (fake / "git").symlink_to(shutil.which("git")) + self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")} + self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin)) + self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root)) + self.write("README.md", README) + self.write("src/app.py", "def run():\n\treturn 1\n\n") + self.commit("start") + self.git(self.root, "tag", "v0.1.0") + self.write("CHANGELOG.md", CHANGELOG) + if todo: + self.write("todo.md", todo) + self.commit("plan") + self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0") + + def git(self, cwd, *args): + return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout + + def write(self, path, text): + (self.root / path).parent.mkdir(parents=True, exist_ok=True) + (self.root / path).write_text(text) + + def commit(self, title): + self.git(self.root, "add", "-A") + self.git(self.root, "commit", "--quiet", "-m", title) + + def preflight(self): + return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env=self.env, text=True, timeout=120) + + +class ChunkPreflightTool(unittest.TestCase): + def test_makes_the_items_worktree_off_the_fetched_default_branch_and_states_the_chunks_facts(self): + repo = Repo(self) + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + worktree = repo.temp / "proj-item-3" + self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-3") + self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main")) + for fact in ( + "Last version cut: v0.1.0. Unreleased: 2 entries under CHANGELOG.md → ## Unreleased.", + "Next release: 0.2.0. Its first item that does not wait: item 3, L 4, E + I 5.", + f"Worktree: {worktree}, on the new branch item-3, made off origin/main.", + "- item 7, L 1, E + I 2, S 1: **Do the thing after.**", + "- `src/app.py`: 3 lines", + "- `src`: 1 file", + "Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", + "tea pulls list --fields index,title,head,state --output tsv", + "12\tWIP: the next thing\titem-3\topen", + "`rank_todo.py --check todo.md` exited 0", + "`larv-review needs-scoring-run 3` exited 0", + "`reading-cost` exited 0", + "`larv-review places` exited 0", + ): + self.assertIn(fact, done.stdout) + self.assertNotIn("item 5,", done.stdout) + self.assertNotIn("item 8,", done.stdout) + self.assertNotIn("item 9,", done.stdout) + self.assertNotIn("`gone.py`:", done.stdout) + self.assertIn(f"to {worktree}/docs/reading-cost.md", done.stdout) + + def test_continues_the_items_worktree_and_else_its_pushed_branch(self): + repo = Repo(self) + repo.preflight() + worktree = repo.temp / "proj-item-3" + self.assertIn(f"Worktree: {worktree}, on the branch item-3, which it already held.", repo.preflight().stdout) + (worktree / "work.txt").write_text("work\n") + repo.git(worktree, "add", "work.txt") + repo.git(worktree, "commit", "--quiet", "-m", "work") + repo.git(worktree, "push", "--quiet", "origin", "item-3") + repo.git(repo.root, "worktree", "remove", "--force", str(worktree)) + repo.git(repo.root, "branch", "--quiet", "-D", "item-3") + self.assertIn(f"Worktree: {worktree}, on the new branch item-3, made off origin/item-3.", repo.preflight().stdout) + self.assertTrue((worktree / "work.txt").exists()) + + def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self): + repo = Repo(self, todo="") + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("Last version cut: v0.1.0.", done.stdout) + self.assertIn("No plan item: origin/main holds no todo.md items table, so no worktree was made.", done.stdout) + self.assertFalse((repo.temp / "proj-item-3").exists()) + + def test_exits_1_outside_a_checkout(self): + with tempfile.TemporaryDirectory() as temp: + done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True) + self.assertEqual(done.returncode, 1) + self.assertIn("git rev-parse --show-toplevel", done.stderr) + + +class Facts(unittest.TestCase): + def test_counts_the_top_level_entries_under_unreleased(self): + self.assertEqual(facts.unreleased_entries(CHANGELOG), 2) + self.assertEqual(facts.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0) + self.assertIsNone(facts.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n")) + + def test_bundles_an_item_blocked_only_by_items_the_chunk_may_take(self): + found = items(TODO.replace("| 9 | 0.3.0 | |", "| 9 | 0.2.0 | 7 |")) + self.assertEqual([item.id for item in facts.bundle_candidates(found, found[1])], [7, 9]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/git_repo.py b/bin/git_repo.py index 7f36bd03..a84eaf22 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -47,6 +47,13 @@ def origin_head() -> str | Failure: return Failure("origin names no default branch; set it with `git remote set-head origin --auto`") +def newest_release_tag(branch: str) -> str | None | Failure: + """The newest `v*` tag merged into branch, None when it has none.""" + # Sorts v1.0.0-rc.1 below v1.0.0. + tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", branch, "--sort=-v:refname") + return tags if isinstance(tags, Failure) else next(iter(tags.split()), None) + + def commit_exists(commit: str) -> bool: return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index faf513b1..24dd0cce 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -114,7 +114,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, preflight=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index f0ca946b..b9c8f839 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,5 +1,5 @@ from failure import Failure -from git_repo import file_at, full_history, git +from git_repo import file_at, full_history, git, newest_release_tag from comprehension_history import HISTORY, HistoryChange @@ -24,10 +24,8 @@ def history_changes(default: str) -> list[HistoryChange] | Failure: def landed_since_release(default: str) -> bool | Failure: """Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none.""" - # Sorts v1.0.0-rc.1 below v1.0.0. - tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname") - if isinstance(tags, Failure): - return tags - newest = tags.split()[:1] - count = git("rev-list", "--count", f"{newest[0]}..{default}" if newest else default) + newest = newest_release_tag(default) + if isinstance(newest, Failure): + return newest + count = git("rev-list", "--count", f"{newest}..{default}" if newest else default) return count if isinstance(count, Failure) else int(count) > 0 diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 001c968a..97bbcc75 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -13,14 +13,24 @@ ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could REVIEWS: tuple[tuple[str, ReviewKind], ...] = (("each reviewer", "reviewer"), ("each comprehension seat", "seat"), ("the security pass's subagent", "security")) -def fresh(task: str, premises: str, route: Route, anchor: Rung | None) -> str: +def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str: + """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text, or empty.""" escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip() routed = f"{routed_by(route, anchor)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") - return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" + found = f"{facts}\n\n" if facts else "" + return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{found}The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" def routed_by(route: Route, anchor: Rung | None) -> str: - return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}" + return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)} After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." + + +def preflight_facts(printed: str) -> str: + return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}" + + +def preflight_failed(reason: str) -> str: + return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself: {reason}" def review_launches(route: Route, anchor: Rung | None) -> str: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index b2a8b13a..0ef0d778 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -84,8 +84,9 @@ def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop: print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) if stop := keep_answer(cycle, answered): return stop + facts = preflight(cycle) if answered is None and not session_open(cycle.session) else "" # worker_start runs inside the lambda: a failed attempt may have opened the session. - if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered), worker_environment(cycle), cycle.effects), cycle.effects): + if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, facts), worker_environment(cycle), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") @@ -96,12 +97,23 @@ def worker_environment(cycle: Cycle) -> dict[str, str]: return worker_rungs.environment(cycle.anchor, cycle.route) -def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]: +def preflight(cycle: Cycle) -> str: + """The facts chunk-preflight printed for a fresh worker, or why it could not run them; run once per chunk start, outside the worker's retries.""" + try: + done = cycle.effects.preflight(cycle.root) + except OSError as failure: + return prompts.preflight_failed(str(failure)) + if done.returncode: + return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") + return prompts.preflight_facts(done.stdout.strip()) + + +def worker_start(cycle: Cycle, answered: QuotedAnswer | None, facts: str) -> list[str]: if answered is not None: return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer), resume=True) if session_open(cycle.session): return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True) - return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor), resume=False) + return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, facts), resume=False) def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index e3c3ee76..7a20fe50 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -1,10 +1,13 @@ import dataclasses import os +import pathlib import subprocess import sys import time import typing +PREFLIGHT = pathlib.Path(__file__).resolve().parents[1] / "chunk-preflight" + class Streaming(typing.Protocol): """A started claude whose stream-json lines arrive as it works.""" @@ -24,6 +27,8 @@ class Effects: local_time: typing.Callable[[float], str] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] + # Runs chunk-preflight in the given directory. + preflight: typing.Callable[[str], subprocess.CompletedProcess[str]] python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]] sleep: typing.Callable[[float], None] stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming] @@ -51,6 +56,7 @@ def system_effects() -> Effects: local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), + preflight=lambda cwd: subprocess.run([sys.executable, str(PREFLIGHT)], capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True), python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), sleep=time.sleep, stream_claude=StreamingClaude, diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 3b08b5d8..13e4c54b 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -5,7 +5,9 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md -items, or else the task, and never widen them. A judge then reads the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, +items, or else the task, and never widen them. Before that first worker, loop-claude runs +bin/chunk-preflight at the checkout root, which finds the chunk's mechanical facts and makes its +worktree; the prompt quotes what it printed, or why it could not run. A judge then reads the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a @@ -52,7 +54,8 @@ for a low L; without such an item, or with its L, E or I unscored, the chunk run cheapest rung. The item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there, never below the worker's rung. The worker's first prompt names the rung and the item, and asks the -worker to name each item the chunk takes, with its L and E + I. The prompt names the rung of each +worker to name each item the chunk takes, with its L and E + I, and to count the item's size again +once it has read the code: a re-score whose L picks a higher rung is an escalation trigger. The prompt names the rung of each review that runs on a rung other than the worker's: the reviewers' rung for the reviewers, and the cheapest rung for each comprehension seat and the security pass. It also names the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run. diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 02e04c10..92ba42ac 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -3,7 +3,7 @@ import dataclasses from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung from failure import Failure -from todo_table import Item, items, waiting +from todo_table import Item, items, next_item from model_routing.route import Route UNFINISHED_PER_STEP = 2 @@ -14,13 +14,11 @@ JUDGE_REPLAYED = ("claude-opus-5-5",) def routed_item(todo: str) -> Item | Failure | None: - """The next release's first row that does not wait, as todo_table.waiting says, in the table's order; None when there is none, or it lacks L, E or I.""" + """The item todo_table.next_item names; None when there is none, or it lacks L, E or I.""" found = items(todo) - if isinstance(found, Failure) or not found: - return found if isinstance(found, Failure) else None - next_release = min(item.release for item in found) - waits = waiting(found) - takes = next((item for item in found if item.release == next_release and item.id not in waits), None) + if isinstance(found, Failure): + return found + takes = next_item(found or []) return takes if takes and takes.likelihood and takes.escape_and_impact else None diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 66a86f3e..27648b7e 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -353,6 +353,7 @@ class Cycles(unittest.TestCase): self.assertEqual(argument(workers[2], "--session-id"), session) self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe.")) + self.assertIn("`~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- No default branch: no origin remote, and no main or master branch to take as the default branch\n\nThe chunk's", argument(workers[0], "-p")) self.assertNotIn(TASK, argument(workers[1], "-p")) self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p")) self.assertIn("as the work remaining:\n\n> started\n\n", argument(workers[1], "-p")) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 5418fff3..b70255cb 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -48,9 +48,9 @@ def human(content): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), preflight=(), python=(), streams=(), on_terminal=True): self.calls = [] - self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} + self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "preflight": list(preflight), "python": list(python), "stream_claude": list(streams)} self.terminal = on_terminal self.worker_environments = [] self.terminal_environments = [] @@ -65,6 +65,7 @@ class FakeEffects: local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW, on_terminal=lambda: self.terminal, + preflight=self.preflight, python=lambda args: self.answer("python", args), sleep=lambda seconds: self.calls.append(("sleep", seconds)), stream_claude=self.stream, @@ -74,6 +75,13 @@ class FakeEffects: self.terminal_environments.append(env) return self.answer("claude_on_terminal", args) + def preflight(self, cwd): + """Answers from the script while it lasts, and else with one fact, since most cycles start a fresh worker.""" + if self.scripts["preflight"]: + return self.answer("preflight", cwd) + self.calls.append(("preflight", cwd)) + return ran("- A preflight fact.") + def stream(self, args, cwd, env): self.worker_environments.append(env) return self.answer("stream_claude", args) @@ -196,6 +204,24 @@ class Cycles(unittest.TestCase): self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"]) self.assertIsNone(session.transcript_file(self.session)) + def test_a_fresh_worker_reads_what_the_preflight_printed_at_the_checkout_root_and_a_resumed_one_runs_none(self): + worker = Worker(self.paths.claude_code_transcripts.parent) + fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working")) + self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Finished("working")) + self.assertEqual(fake.made("preflight"), [str(self.home)]) + fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude")) + self.assertIn("loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- A preflight fact.", fresh) + self.assertNotIn("chunk-preflight", resumed) + + def test_a_fresh_worker_finds_the_facts_itself_where_the_preflight_fails(self): + for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (OSError(2, "No such file or directory"), "[Errno 2] No such file or directory")): + with self.subTest(why=why): + fake = FakeEffects(preflight=[failed], streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working")) + args = fake.made("stream_claude")[0] + self.assertIn(f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself: {why}", args[args.index("-p") + 1]) + def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviewers_in_its_environment(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) @@ -798,30 +824,34 @@ class WorkerArgs(unittest.TestCase): SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung." def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): - routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None) - self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.\n\nThe chunk's", routed) - unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None) + routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, "") + self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3. After your first read", routed) + unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, "") self.assertIn("before creating a new one.\n\nThe chunk's", unrouted) self.assertNotIn("loop-claude runs you on", unrouted) + def test_puts_the_preflights_facts_before_the_scope_and_asks_the_worker_to_count_the_items_size_again(self): + fresh = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, prompts.preflight_facts("- A fact.")) + self.assertIn("whether or not it is item 3. After your first read of the code, count item 3's size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1.\n\nloop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- A fact.\n\nThe chunk's", fresh) + def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): opus = Rung("claude-opus-5-5", "medium") - below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus) + below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, "") self.assertIn(f"whether or not it is item 3. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 ` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", below) - self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus)) + self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): opus = Rung("claude-opus-5-5", "medium") - level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus) + level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, "") self.assertIn("whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", level) - below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus) + below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, "") self.assertIn(f"whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below) self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 6), opus)) def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): opus = Rung("claude-opus-5-5", "medium") taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8." - self.assertIn(f"whether or not it is item 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus)) + self.assertIn(f"whether or not it is item 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus)) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 4), opus)) self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus)) @@ -834,7 +864,7 @@ class WorkerArgs(unittest.TestCase): def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): opus = Rung("claude-opus-5-5", "medium") - above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus) + above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, "") stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus) self.assertIn(f"{prompts.ANSWERS_RECORDED}. loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", stepped_up) self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus)) @@ -843,7 +873,7 @@ class WorkerArgs(unittest.TestCase): def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): opus = Rung("claude-opus-5-5", "medium") - fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus) + fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "") self.assertIn("whether or not it is item 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh) self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)) self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus)) @@ -851,12 +881,12 @@ class WorkerArgs(unittest.TestCase): self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus)) - self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus)) + self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, "")) def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): opus = Rung("claude-opus-5-5", "medium") offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`." - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus)) + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)) self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus)) @@ -865,19 +895,19 @@ class WorkerArgs(unittest.TestCase): both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`." self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both)) self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both)) - self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus).split("\n\nThe chunk's")[0].endswith(both)) + self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, "").split("\n\nThe chunk's")[0].endswith(both)) self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort xhigh`, and a comprehension seat with `model opus, effort high`.")) self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort max`, and a comprehension seat with `model opus, effort high`.")) self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.")) self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None)) - self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None)) - self.assertIn(f"{both}\n\nThe chunk's", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus)) + self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, "")) + self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) fable = Rung("claude-fable-5-1", "max") self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable)) def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) - fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None), resume=False) + fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, ""), resume=False) self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 06180604..0b28179d 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -77,9 +77,9 @@ import re import sys import typing -from todo_table import BLOCKED_BY, cells, HEADER_START, Item, items_table, MOVES, OLD_SHAPE, parse_row, risk, Shape, SHAPE, shape_of, Table, table_rows +from todo_table import BLOCKED_BY, cells, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, risk, Shape, SHAPE, shape_of, Table, table_rows from failure import Failure -from markdown_text import FENCE, listed, sections +from markdown_text import listed, sections from file_writes import replace_file LARGEST_FORMULA = 200 @@ -578,21 +578,10 @@ def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...] def rank_details(text: str, items: list[Item]) -> str | Failure: - section = re.search(r"^## Details\n(.*?)(?=^## |\Z)", text, re.M | re.S) - if section is None: - return text - body = section.group(1) - # A fenced line such as "## Goals" or "### 2. x" would read as a heading and split a detail. - if FENCE.search(body): - return Failure("## Details holds a fenced code block; indent quoted markdown by four spaces instead") - parts = re.split(r"^### (\d+)\. [^\n]*\n", body, flags=re.M) - if parts[0].strip(): - return Failure("## Details holds text before its first ### . heading") - details: dict[int, str] = {} - for id_, detail in zip(parts[1::2], parts[2::2]): - if int(id_) in details: - return Failure(f"## Details holds item {id_} twice") - details[int(id_)] = detail.strip("\n") + section = DETAILS.search(text) + details = item_details(text) + if section is None or isinstance(details, Failure): + return details if isinstance(details, Failure) else text if unknown := sorted(set(details) - {item.id for item in items}): return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not") headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details] diff --git a/bin/stability_replay/test_stability_replay.py b/bin/stability_replay/test_stability_replay.py index d1012e4a..c26416c7 100644 --- a/bin/stability_replay/test_stability_replay.py +++ b/bin/stability_replay/test_stability_replay.py @@ -213,7 +213,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, preflight=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/todo_table.py b/bin/todo_table.py index ecbabeb3..37df9035 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -3,6 +3,7 @@ import re import typing from failure import Failure +from markdown_text import FENCE # Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level. TOP_SCORE = 10 @@ -16,6 +17,8 @@ BLOCKED_BY = "Blocked by" MOVES = "Moves" # How the items table's header opens, which tells it from any other table in todo.md. HEADER_START = "| ID | Release |" +# todo.md's ## Details section, its body the first group. +DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) # Each goal an item names, in its order, with how far the item moves it; None in OLD_SHAPE, whose Goals cell names no move. Moves = tuple[tuple[str, int | None], ...] @@ -161,6 +164,34 @@ def waiting(found: list[Item]) -> set[int]: return {item.id for item in found if item.exempt == "question" or held.intersection(item.blocked_by)} +def next_item(found: list[Item]) -> Item | None: + """The earliest release's first row that does not wait, as waiting says, in the table's order: the item the next chunk takes first.""" + if not found: + return None + release = min(item.release for item in found) + waits = waiting(found) + return next((item for item in found if item.release == release and item.id not in waits), None) + + +def item_details(todo: str) -> dict[int, str] | Failure: + """Each item's detail under ## Details, by ID; empty where todo.md has no such section.""" + section = DETAILS.search(todo) + if section is None: + return {} + # A fenced line such as "## Goals" or "### 2. x" would read as a heading and split a detail. + if FENCE.search(section.group(1)): + return Failure("## Details holds a fenced code block; indent quoted markdown by four spaces instead") + parts = re.split(r"^### (\d+)\. [^\n]*\n", section.group(1), flags=re.M) + if parts[0].strip(): + return Failure("## Details holds text before its first ### . heading") + details: dict[int, str] = {} + for id_, detail in zip(parts[1::2], parts[2::2]): + if int(id_) in details: + return Failure(f"## Details holds item {id_} twice") + details[int(id_)] = detail.strip("\n") + return details + + def table_rows(lines: list[str], header: str) -> Table | Failure: if lines.count(header) != 1: return Failure(f"todo.md needs the table header {header} once") diff --git a/todo.md b/todo.md index fb7415ae..275a4ffb 100644 --- a/todo.md +++ b/todo.md @@ -6,13 +6,12 @@ `Bar = 0.1` -`Next ID = 175` +`Next ID = 176` ## Items | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 161 | 0.2.0 | | | **Have loop-claude run a preflight script before each fresh worker and put its findings in the worker's prompt, so the worker no longer spends tool calls finding the chunk's mechanical facts.** | 4 | 2 | 3 | 7 | 6 | 1.1 by 4, 1.4 by 6, 1.5 by 6 | 2.9 | | 84 | 0.2.0 | | | **Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.** | 2 | 2 | 2 | 4 | 4 | 1.4 by 5 | 2.3 | | 168 | 0.2.0 | | | **Have the human answer an interrupt on loop-claude's terminal and resume the worker headless with the answer, opening the interactive session only when they ask for it.** | 4 | 2 | 3 | 7 | 5 | 1.5 by 8 | 1.8 | | 73 | 0.2.0 | | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4 | 1.1 | @@ -39,6 +38,7 @@ | 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 | | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | +| 175 | 0.3.0 | | | **Compare the time and fresh tokens before the first edit in the first five chunks loop-claude starts with `chunk-preflight` against item 140's, and file an item where they did not fall.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -82,20 +82,6 @@ ## Details -### 161. Have loop-claude run a preflight script before each fresh worker and put its findings in the worker's prompt, so the worker no longer spends tool calls finding the chunk's mechanical facts. - -In item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. About half of those found facts a program computes the same way in every chunk: - -- the open PR and worktree for the chunk, the last tag and how many changes are unreleased; -- the next release, the first plan item that does not wait, its L, its E + I and its detail, after `rank_todo.py --check`; -- the items that may bundle with it under `CLAUDE.md` → "Working loop", "Work one chunk at a time, and make it as large as one purpose allows"; -- what `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print; -- a worktree off a freshly fetched `origin/main`. - -The preflight also lists the files and components the item's detail names, for the worker to judge the item's size from. - -Compute these in one tool and give loop-claude's prompt its output as facts, so the worker reads them rather than finding them. The reading the chunk needs, such as the decision an item changes, stays the worker's. After its first read of the code, the worker counts the item's size again: the lines, files and components it will change. Where that count would change the item's L, a subagent on the project's rung re-scores the item. A re-score whose L picks a rung above the worker's is escalation trigger 1. Measure the next few chunks' time and fresh tokens before the first edit against item 140's figures. The comprehension seats found the prompt assembly in `bin/loop_claude/cycle/prompts.py` hard: put the preflight's facts in a function of their own there. - ### 84. Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes. Raised by the principles audit of PR #228: the `review: the comprehension check records …` entry in `docs/decisions.md` is valid only while that holds, and `docs/comprehension-history.md` keeps every vote, yet nothing reads the agreement rate. Scoring runs on near-identical code are rare now, so compare with those already in the history, such as PR #224's and PR #225's, or make a second run for the check. @@ -219,6 +205,10 @@ lilleman asked, on 2026-10-16, for a standing audit each release, so the loop ke The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it. +### 175. Compare the time and fresh tokens before the first edit in the first five chunks loop-claude starts with `chunk-preflight` against item 140's, and file an item where they did not fall. + +Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure the same figures from loop-claude's archive for the first five chunks that started with the preflight. Where their median did not fall, file an item naming the facts the workers still found by hand. + ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2). -- 2.52.0 From ee340db912d6da719abf02b2d915c3c4e1a5130d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 00:29:24 +0200 Subject: [PATCH 02/22] Append the reading cost of the last finished chunk --- docs/reading-cost.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index f241e04e..07e8c441 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -586,3 +586,20 @@ Read most (opens and searches): - `docs/decisions.md` 2 - `AGENTS.md` 1 - `CHANGELOG.md` 1 + +## Reading cost, chunk 94d844dc700e, finished 2026-10-16T22:15:37Z + +117108 new input tokens before the first commit. + +Read most (opens and searches): + +- `todo.md` 6 +- `bin/loop_claude/test_black_box.py` 5 +- `bin/loop_claude/test_loop_claude.py` 5 +- `docs/decisions.md` 4 +- `CHANGELOG.md` 3 +- `bin/routing_figures/measure.py` 2 +- `bin/transcript_archive/outcomes.py` 2 +- `AGENTS.md` 1 +- `README.md` 1 +- `bin/loop_claude/cycle/judge.py` 1 -- 2.52.0 From 8b3a5a32a3ab3380291ba4c293ff7cdfc3fcde74 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 00:30:27 +0200 Subject: [PATCH 03/22] List only the open pull requests from the item's branch, by number and URL, so no stranger's title reaches the worker's prompt --- bin/chunk_preflight/main.py | 42 ++++++++++++++------- bin/chunk_preflight/test_chunk_preflight.py | 7 ++-- 2 files changed, 32 insertions(+), 17 deletions(-) diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index fcd47f15..d35b5cad 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -14,7 +14,9 @@ It then prints: - the item's worktree: a sibling of the checkout named -item-, on the branch item-. It continues a worktree already on that branch; else it adds one on the local branch, else on a new branch tracking origin's, else on a new branch off the default branch; -- the open pull requests, as gh lists them on a github.com origin, and else as tea does; +- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists + them on a github.com origin, and else as tea does. No title reaches the output: on a public forge, + anyone may open a pull request, and its title would reach the worker's prompt; - the items of that release that a chunk taking the item may take too: none is a question, and no item outside them and the item blocks one; - each file or folder git tracks that the item's tagline or detail names in backticks, with a @@ -68,16 +70,17 @@ def preflight(root: pathlib.Path) -> list[str]: todo = file_at(default, "todo.md") planned = todo if isinstance(todo, Failure) else items(todo) if isinstance(planned, Failure): - return [*found, f"- No plan item: {default}'s todo.md: {planned.reason}", *pull_requests(root)] + return [*found, f"- No plan item: {default}'s todo.md: {planned.reason}"] first = next_item(planned or []) if first is None: why = f"every item of {default}'s next release waits" if planned else f"{default} holds no todo.md items table" - return [*found, f"- No plan item: {why}, so no worktree was made.", *pull_requests(root)] + return [*found, f"- No plan item: {why}, so no worktree was made."] assert isinstance(todo, str) and planned found.append(f"- Next release: {release_name(first)}. Its first item that does not wait: item {first.id}, L {first.likelihood or 'unscored'}, E + I {first.escape_and_impact or 'unscored'}.") - worktree = item_worktree(root, f"item-{first.id}", default) + branch = f"item-{first.id}" + worktree = item_worktree(root, branch, default) found.append(f"- Worktree: {worktree.reason}" if isinstance(worktree, Failure) else f"- Worktree: {worktree[0]}, {worktree[1]}") - found += pull_requests(root) + found.append(f"- Open pull requests from {branch}: {pull_requests(root, branch)}") found += bundled(planned, first) details = item_details(todo) detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" @@ -125,12 +128,19 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> tuple[pathli return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else (path, how) -def pull_requests(root: pathlib.Path) -> list[str]: +def pull_requests(root: pathlib.Path, branch: str) -> str: + """Each open pull request from branch, by its number and URL, or why none can be listed.""" url = git("remote", "get-url", "origin") if isinstance(url, Failure): - return ["- Open pull requests: none, as the checkout has no origin remote."] - command = ["gh", "pr", "list"] if "github.com" in url else ["tea", "pulls", "list", "--fields", "index,title,head,state", "--output", "tsv"] - return [f"- Open pull requests: {printed(tuple(command), command, root)}"] + return "none, as the checkout has no origin remote." + github = "github.com" in url + command = ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] if github else ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"] + done = ran(command, root) + if isinstance(done, Failure) or done.returncode: + return f"cannot be listed: `{' '.join(command[:3])}` {done.reason if isinstance(done, Failure) else f'exited {done.returncode}: {done.stderr.strip()}'}" + rows = [line.split("\t") for line in done.stdout.splitlines()] + opened = [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2] if github else [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch] + return ", ".join(opened) if opened else "none." def bundled(planned: list[Item], first: Item) -> list[str]: @@ -160,13 +170,19 @@ def size(path: pathlib.Path, files: int) -> str: return f"cannot be read: {failure}" +def ran(command: list[str], cwd: pathlib.Path) -> subprocess.CompletedProcess[str] | Failure: + try: + return subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) + except (OSError, subprocess.TimeoutExpired) as failure: + return Failure(f"could not finish: {failure}") + + def printed(shown: tuple[str, ...], command: list[str], cwd: pathlib.Path) -> str: """What command printed, run in cwd, and its exit code, under its name as shown.""" name = f"`{' '.join(shown)}`" - try: - done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) - except (OSError, subprocess.TimeoutExpired) as failure: - return f"{name} could not finish: {failure}" + done = ran(command, cwd) + if isinstance(done, Failure): + return f"{name} {done.reason}" output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip()) return f"{name} exited {done.returncode}, printing:\n\n{quoted(output)}" if output else f"{name} exited {done.returncode}, printing nothing." diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 1f3831cb..94828f69 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -42,8 +42,8 @@ TODO = """# todo Change `src/app.py`'s `run` and the files under `src`, not `gone.py`. """ CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" -# Prints its arguments, then two open pull requests, as `tea pulls list --output tsv` does. -FAKE_TEA = "#!/bin/sh\necho \"tea $*\"\nprintf 'index\\ttitle\\thead\\tstate\\n12\\tWIP: the next thing\\titem-3\\topen\\n'\n" +# Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1. +FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-3\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n" class Repo: @@ -104,8 +104,7 @@ class ChunkPreflightTool(unittest.TestCase): "- `src/app.py`: 3 lines", "- `src`: 1 file", "Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", - "tea pulls list --fields index,title,head,state --output tsv", - "12\tWIP: the next thing\titem-3\topen", + "- Open pull requests from item-3: #12 https://forge/pulls/12\n", "`rank_todo.py --check todo.md` exited 0", "`larv-review needs-scoring-run 3` exited 0", "`reading-cost` exited 0", -- 2.52.0 From ecbb7a7cda8d7344c497756d79f816d728eefed9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 01:03:15 +0200 Subject: [PATCH 04/22] =?UTF-8?q?Answer=20architecture=20round=201:=202=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1;=20route=20and=20preflight=20o?= =?UTF-8?q?n=20the=20one=20checkout=20todo.md=20the=20preflight=20fast-for?= =?UTF-8?q?wards,=20split=20the=20preflight=20into=20gathering=20and=20a?= =?UTF-8?q?=20pure=20render,=20move=20bundle=5Fcandidates=20onto=20todo=5F?= =?UTF-8?q?table.waiting,=20run=20the=20preflight=20through=20the=20python?= =?UTF-8?q?=20effect=20with=20a=20timeout,=20give=20the=20re-score=20sente?= =?UTF-8?q?nce=20its=20own=20function,=20and=20point=20loop-claude's=20hel?= =?UTF-8?q?p=20at=20the=20modules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- README.md | 2 +- bin/chunk_preflight/facts.py | 116 ++++++++-- bin/chunk_preflight/gathered.py | 158 ++++++++++++++ bin/chunk_preflight/main.py | 198 +++++++----------- bin/chunk_preflight/test_chunk_preflight.py | 178 ++++++++++++---- bin/judge_replay/test_judge_replay.py | 2 +- bin/loop_claude/cycle/prompts.py | 18 +- bin/loop_claude/cycle/run.py | 20 +- bin/loop_claude/effects.py | 21 +- bin/loop_claude/loop/main.py | 39 +++- bin/loop_claude/loop/reload.py | 2 +- bin/loop_claude/test_black_box.py | 28 ++- bin/loop_claude/test_loop_claude.py | 115 ++++++---- bin/stability_replay/test_stability_replay.py | 2 +- bin/test_rank_todo.py | 7 + bin/todo_table.py | 17 +- 17 files changed, 657 insertions(+), 268 deletions(-) create mode 100644 bin/chunk_preflight/gathered.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cbcdcfbf..fd56429a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ - `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names. - `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`. - `loop-claude` archives each judge reply it rejects in the chunk's `.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1. -- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before each chunk's first worker, `loop-claude` runs it and quotes what it printed in the worker's prompt. It names the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. +- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight first fast-forwards the checkout to origin's default branch where the checkout is on that branch and holds no uncommitted change, so the chunk is routed on the plan origin holds. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. ## 0.1.0 diff --git a/README.md b/README.md index a39f9a87..bad1a399 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. -- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before each chunk's first worker, and `chunk-preflight --help` lists the facts. +- `chunk-preflight` fast-forwards the checkout, finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts. - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places; `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 7d730af9..78bb02dd 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,7 +1,30 @@ -import re +"""The lines the preflight prints, stated from what it gathered.""" +from todo_table import bundle_candidates, Item +from failure import Failure +from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Plan, pulls_command, Ran, Release +from markdown_text import quoted, sections -from markdown_text import sections -from todo_table import Item + +def render(found: Gathered) -> list[str]: + """One `- ` line per fact, then the item's tagline and detail, and what each tool printed.""" + note = [f"- {found.note}"] if found.note else [] + checkout = f"- The checkout was not fast-forwarded: {found.kept_as_is}" if found.kept_as_is else f"- The checkout was fast-forwarded to {found.default}." + head = [*note, checkout, f"- {last_release(found.default, found.release)}"] + if isinstance(found.item, str): + return [*head, f"- No plan item: {found.item}, so no worktree was made."] + return [*head, *item_lines(found.item)] + + +def last_release(default: str, release: Release) -> str: + if isinstance(release.tag, Failure): + return f"Last version cut: cannot be read: {release.tag.reason}" + cut = f"Last version cut: {release.tag or 'none'}." + entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None + if entries is not None: + return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." + commits = release.commits.reason if isinstance(release.commits, Failure) else counted(release.commits, "commit", "commits") + since = f"since {release.tag}" if release.tag else f"on {default}" + return f"{cut} Unreleased: {commits} {since}, and no ## Unreleased in CHANGELOG.md." def unreleased_entries(changelog: str) -> int | None: @@ -10,17 +33,80 @@ def unreleased_entries(changelog: str) -> int | None: return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) -def bundle_candidates(found: list[Item], first: Item) -> list[Item]: - """The items of first's release, in the table's order, that a chunk taking first may take too: no question, and none blocked by an item outside first and these.""" - candidates = {item.id for item in found if item.release == first.release and item.id != first.id and item.exempt != "question"} - held = {item.id for item in found} - while blocked := {item.id for item in found if item.id in candidates and (held & set(item.blocked_by)) - candidates - {first.id}}: - candidates -= blocked - return [item for item in found if item.id in candidates] +def item_lines(item: ItemFacts) -> list[str]: + first = item.plan.first + worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}" + return [ + f"- Next release, in the checkout's todo.md: {release_name(first)}. Its first item that does not wait: item {first.id}, {levels(first)}.", + f"- Worktree: {worktree}", + f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}", + *bundled(item.plan), + *named_lines(item.named), + f"\nItem {first.id}'s tagline and detail:\n\n{quoted(item.plan.text)}", + *(f"\n{printed(shown, done)}" for shown, done in item.tools), + ] -def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]: - """Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file.""" - spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text)) - held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans) - return [(span, count) for span, count in held if count] +def pulls_text(pulls: tuple[Forge, Ran | Failure] | None, branch: str) -> str: + """Each open pull request from branch, by its number and URL, or why none can be listed. No title: on a public forge anyone may open one, and its title would reach the worker's prompt.""" + if pulls is None: + return "none, as the checkout has no origin remote." + forge, done = pulls + shown = " ".join(pulls_command(forge, branch)[:3]) + if isinstance(done, Failure): + return f"cannot be listed: `{shown}` {done.reason}" + if done.code: + return f"cannot be listed: `{shown}` exited {done.code}: {done.stderr.strip()}" + return ", ".join(open_pulls(done.stdout, forge, branch)) or "none." + + +def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]: + """Each open pull request from branch in the rows pulls_command printed, as `# `: gh's rows are branch's, number and URL; tea's are every one's, index, head and URL, under a header row.""" + rows = [line.split("\t") for line in stdout.splitlines()] + if forge == "gh": + return [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2] + return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch] + + +def bundled(plan: Plan) -> list[str]: + first, candidates = plan.first, bundle_candidates(plan.items, plan.first) + if not candidates: + return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."] + listed = [f" - item {item.id}, {levels(item)}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates] + return [f'- The items of release {release_name(first)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed] + + +def named_lines(named: list[NamedPath] | Failure) -> list[str]: + if isinstance(named, Failure): + return [f"- The files the item names: cannot be listed: {named.reason}"] + if not named: + return ["- The item names no file or folder git tracks."] + return ["- The files and folders the item names:", *(f" - `{path.span}`: {size(path)}" for path in named)] + + +def size(path: NamedPath) -> str: + if path.lines is None: + return counted(path.files, "file", "files") + if isinstance(path.lines, Failure): + return f"cannot be read: {path.lines.reason}" + return counted(path.lines, "line", "lines") + + +def printed(shown: str, done: Ran | Failure) -> str: + """What a tool printed and its exit code, under its command line.""" + if isinstance(done, Failure): + return f"`{shown}` {done.reason}" + output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip()) + return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing nothing." + + +def levels(item: Item) -> str: + return f"L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}" + + +def release_name(item: Item) -> str: + return ".".join(map(str, item.release)) + + +def counted(count: int, one: str, many: str) -> str: + return f"{count} {one if count == 1 else many}" diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py new file mode 100644 index 00000000..248f2a26 --- /dev/null +++ b/bin/chunk_preflight/gathered.py @@ -0,0 +1,158 @@ +"""What the preflight gathers, and the pure choices its steps act on; facts.render states it.""" +import dataclasses +import pathlib +import re +import typing + +from failure import Failure +from todo_table import Item, item_details, items, next_item + +# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. +Forge = typing.Literal["gh", "tea"] + + +@dataclasses.dataclass(frozen=True) +class Ran: + """A command that ran to its end: its exit code and what it printed.""" + code: int + stdout: str + stderr: str + + +@dataclasses.dataclass(frozen=True) +class Release: + """What the last release fact rests on, each read from the default branch.""" + tag: str | None | Failure + changelog: str | Failure + # How many commits follow the tag, or make up the branch where it has none. + commits: int | Failure + + +@dataclasses.dataclass(frozen=True) +class Plan: + """The checkout's todo.md items, and first, the item the next chunk takes first.""" + items: list[Item] + first: Item + # first's tagline and detail. + text: str + + @property + def branch(self) -> str: + """The branch first's worktree is on.""" + return f"item-{self.first.id}" + + +@dataclasses.dataclass(frozen=True) +class Worktree: + path: pathlib.Path + # How it came to be, as the worker reads it. + how: str + + +@dataclasses.dataclass(frozen=True) +class NamedPath: + """A tracked file or folder the item names, with how many tracked files it holds.""" + span: str + files: int + # A file's lines, or why they cannot be read; None for a folder. + lines: int | Failure | None + + +@dataclasses.dataclass(frozen=True) +class ItemFacts: + """What the preflight found or made for the plan's first item.""" + plan: Plan + worktree: Worktree | Failure + # The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote. + pulls: tuple[Forge, Ran | Failure] | None + named: list[NamedPath] | Failure + # Each tool run in the worktree, by its command line, and how it ran; none without a worktree. + tools: list[tuple[str, Ran | Failure]] + + +@dataclasses.dataclass(frozen=True) +class Gathered: + """Everything the preflight read and ran, for facts.render to state.""" + # The default branch's ref, such as origin/main. + default: str + # Why origin reads as last fetched; None after a fetch. + note: str | None + # Why the checkout was not fast-forwarded to default; None once it was. + kept_as_is: str | None + release: Release + # The plan's first item and what was found or made for it; else why there is none. + item: ItemFacts | str + + +def planned(todo: str | Failure) -> Plan | str: + """The checkout's plan and its first item, as todo_table.next_item picks it; else why there is none.""" + if isinstance(todo, Failure): + return f"the checkout's todo.md cannot be read: {todo.reason}" + found = items(todo) + if isinstance(found, Failure): + return f"the checkout's todo.md cannot be read: {found.reason}" + listed = found or [] + first = next_item(listed) + if first is None: + return "every item of the checkout's next release waits" if listed else "the checkout holds no todo.md items table" + details = item_details(todo) + detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" + return Plan(listed, first, f"{first.tagline}\n\n{detail}".strip()) + + +def held_back(default: str, head: str | Failure, status: str | Failure, behind: str | Failure) -> str | None: + """Why the checkout is not fast-forwarded to default, from its branch, its tracked changes and how many commits it is behind; None where nothing holds it back. + + A dirty checkout is never fast-forwarded, as `~/.claude/CLAUDE.md` → "Working with the codebase" asks: its changes are for the human to see, never to carry along. + """ + branch = default.removeprefix("origin/") + if branch == default: + return "it has no origin remote" + if isinstance(head, Failure): + return "it is on no branch" + if head.strip() != branch: + return f"it is on {head.strip()}, not {branch}" + if isinstance(status, Failure): + return f"its status cannot be read: {status.reason}" + if status.strip(): + return "it holds uncommitted changes" + if isinstance(behind, Failure): + return f"how far it is behind {default} cannot be read: {behind.reason}" + return f"it is not behind {default}" if int(behind) == 0 else None + + +def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: + """The worktree on branch, in what `git worktree list --porcelain` printed; None where none is.""" + for block in porcelain.split("\n\n"): + fields = dict(line.partition(" ")[::2] for line in block.splitlines()) + if fields.get("branch") == f"refs/heads/{branch}": + return pathlib.Path(fields["worktree"]) + return None + + +def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]: + """The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default.""" + if local: + return ["worktree", "add", "--quiet", str(path), branch], f"on the branch {branch}, which existed already." + if pushed: + return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"on the new branch {branch}, made off origin/{branch}." + # --no-track: tracking the default branch would point a bare `git push` at it. + return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"on the new branch {branch}, made off {default}." + + +def forge_of(origin_url: str) -> Forge: + return "gh" if "github.com" in origin_url else "tea" + + +def pulls_command(forge: Forge, branch: str) -> list[str]: + """The command that lists open pull requests, by number, head and URL. gh lists only branch's; tea lists every one, for facts.open_pulls to pick branch's.""" + if forge == "gh": + return ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] + return ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"] + + +def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]: + """Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file.""" + spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text)) + held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans) + return [(span, count) for span, count in held if count] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index d35b5cad..ca834673 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -2,15 +2,17 @@ usage: chunk-preflight -Run it inside a project checkout. loop-claude runs it at the checkout root before each fresh worker, -and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that -remote, and reads origin's default branch, or else the local main or master, as larv-review does. -It then prints: +Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's +first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It +fetches origin, when the checkout has that remote, and takes origin's default branch, or else the +local main or master, as larv-review does. It fast-forwards the checkout to that branch where the +checkout is on it, behind it and holds no uncommitted change; else it says why not. It then reads +the checkout's own todo.md, the file loop-claude routes on, and prints: - the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how many commits followed the tag; -- the next release in the default branch's todo.md, and that release's first item that does not - wait, as loop-claude routes on, with its L and E + I; +- the next release in todo.md, and that release's first item that does not wait, the item + loop-claude routes on, with its L and E + I; - the item's worktree: a sibling of the checkout named -item-, on the branch item-. It continues a worktree already on that branch; else it adds one on the local branch, else on a new branch tracking origin's, else on a new branch off the default branch; @@ -25,8 +27,9 @@ It then prints: `larv-review places` print in the worktree, each with its exit code. reading-cost appends to the worktree's docs/reading-cost.md, for the chunk to commit. -A fact it cannot find it says it cannot, and why, and goes on. With no item, it makes no worktree -and runs none of those four tools. +A fact it cannot find it says it cannot, and why, and goes on. A tool or forge CLI still running +after TIMEOUT seconds is stopped. With no item, it makes no worktree and runs none of those four +tools. Exit 1, saying why, on any argument, or when git cannot start or finds no checkout. """ @@ -34,15 +37,16 @@ import pathlib import subprocess import sys -from chunk_preflight.facts import bundle_candidates, named_paths, unreleased_entries -from failure import Failure from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top -from markdown_text import quoted -from todo_table import Item, item_details, items, next_item +from failure import Failure +from chunk_preflight.gathered import Forge, forge_of, Gathered, held_back, ItemFacts, named_paths, NamedPath, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on +from chunk_preflight.facts import render BIN = pathlib.Path(__file__).resolve().parents[1] -# A tool or forge CLI still running after this many seconds is stopped, so a hung one cannot hold the loop. -TIMEOUT = 300 +# Each tool run in the item's worktree, {item} standing for the item's ID. +TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places")) +# Seconds before a tool or forge CLI is stopped, so a hung one leaves the facts the others find. +TIMEOUT = 60 def main(argv: list[str]) -> int: @@ -61,135 +65,95 @@ def main(argv: list[str]) -> int: def preflight(root: pathlib.Path) -> list[str]: - branch = default_branch(stale_ok=True) - if isinstance(branch, Failure): - return [f"- No default branch: {branch.reason}"] - default, note = branch - found = [f"- {note}"] if note else [] - found.append(f"- {last_release(default)}") - todo = file_at(default, "todo.md") - planned = todo if isinstance(todo, Failure) else items(todo) - if isinstance(planned, Failure): - return [*found, f"- No plan item: {default}'s todo.md: {planned.reason}"] - first = next_item(planned or []) - if first is None: - why = f"every item of {default}'s next release waits" if planned else f"{default} holds no todo.md items table" - return [*found, f"- No plan item: {why}, so no worktree was made."] - assert isinstance(todo, str) and planned - found.append(f"- Next release: {release_name(first)}. Its first item that does not wait: item {first.id}, L {first.likelihood or 'unscored'}, E + I {first.escape_and_impact or 'unscored'}.") - branch = f"item-{first.id}" - worktree = item_worktree(root, branch, default) - found.append(f"- Worktree: {worktree.reason}" if isinstance(worktree, Failure) else f"- Worktree: {worktree[0]}, {worktree[1]}") - found.append(f"- Open pull requests from {branch}: {pull_requests(root, branch)}") - found += bundled(planned, first) - details = item_details(todo) - detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" - text = f"{first.tagline}\n\n{detail}".strip() - found += named(text, worktree[0] if isinstance(worktree, tuple) else root) - found.append(f"\nItem {first.id}'s tagline and detail:\n\n{quoted(text)}") - if isinstance(worktree, tuple): - for args in (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", str(first.id)), ("reading-cost",), ("larv-review", "places")): - found.append(f"\n{printed(args, [sys.executable, str(BIN / args[0]), *args[1:]], worktree[0])}") - return found + """Gathers the facts step by step, each step taking what the ones before it found, and renders them.""" + default = default_branch(stale_ok=True) + if isinstance(default, Failure): + return [f"- No default branch: {default.reason}"] + ref, note = default + # First, so the plan read next is the fast-forwarded checkout's. + kept_as_is = fast_forward(ref) + plan = planned(text_of(root / "todo.md")) + item = plan if isinstance(plan, str) else item_facts(root, ref, plan) + return render(Gathered(ref, note, kept_as_is, release(ref), item)) -def last_release(default: str) -> str: +def fast_forward(default: str) -> str | None: + """Fast-forwards the checkout to default unless held_back says why not; None once it has.""" + held = held_back(default, git("symbolic-ref", "--quiet", "--short", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("rev-list", "--count", f"HEAD..{default}")) + if held is not None: + return held + merged = git("merge", "--ff-only", "--quiet", default) + return merged.reason if isinstance(merged, Failure) else None + + +def release(default: str) -> Release: tag = newest_release_tag(default) - if isinstance(tag, Failure): - return f"Last version cut: cannot be read: {tag.reason}" - changelog = file_at(default, "CHANGELOG.md") - entries = unreleased_entries(changelog) if isinstance(changelog, str) else None - if entries is not None: - return f"Last version cut: {tag or 'none'}. Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." - commits = git("rev-list", "--count", f"{tag}..{default}" if tag else default) - since = f"since {tag}" if tag else f"on {default}" - return f"Last version cut: {tag or 'none'}. Unreleased: {commits.reason if isinstance(commits, Failure) else counted(int(commits), 'commit', 'commits')} {since}, and no ## Unreleased in CHANGELOG.md." + commits = git("rev-list", "--count", f"{tag}..{default}" if isinstance(tag, str) else default) + return Release(tag, file_at(default, "CHANGELOG.md"), commits if isinstance(commits, Failure) else int(commits)) -def item_worktree(root: pathlib.Path, branch: str, default: str) -> tuple[pathlib.Path, str] | Failure: - """The worktree on branch, and how it came to be; a Failure where git cannot make it, or its path holds something else.""" +def item_facts(root: pathlib.Path, default: str, plan: Plan) -> ItemFacts: + worktree = item_worktree(root, plan.branch, default) + made = worktree.path if isinstance(worktree, Worktree) else None + return ItemFacts(plan, worktree, pull_listing(root, plan.branch), named_files(plan.text, made or root), tools_run(plan.first.id, made) if made else []) + + +def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure: + """The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else.""" held = git("worktree", "list", "--porcelain") if isinstance(held, Failure): return held - for block in held.split("\n\n"): - fields = dict(line.partition(" ")[::2] for line in block.splitlines()) - if fields.get("branch") == f"refs/heads/{branch}": - return pathlib.Path(fields["worktree"]), f"on the branch {branch}, which it already held." + if (path := worktree_on(held, branch)) is not None: + return Worktree(path, f"on the branch {branch}, which it already held.") path = root.parent / f"{root.name}-{branch}" if path.exists(): return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}") - if commit_exists(f"refs/heads/{branch}"): - added, how = git("worktree", "add", "--quiet", str(path), branch), f"on the branch {branch}, which existed already." - elif commit_exists(f"refs/remotes/origin/{branch}"): - added, how = git("worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"), f"on the new branch {branch}, made off origin/{branch}." - else: - # --no-track: tracking the default branch would point a bare `git push` at it. - added, how = git("worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default), f"on the new branch {branch}, made off {default}." - return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else (path, how) + args, how = worktree_add(branch, path, default, commit_exists(f"refs/heads/{branch}"), commit_exists(f"refs/remotes/origin/{branch}")) + added = git(*args) + return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how) -def pull_requests(root: pathlib.Path, branch: str) -> str: - """Each open pull request from branch, by its number and URL, or why none can be listed.""" +def pull_listing(root: pathlib.Path, branch: str) -> tuple[Forge, Ran | Failure] | None: url = git("remote", "get-url", "origin") if isinstance(url, Failure): - return "none, as the checkout has no origin remote." - github = "github.com" in url - command = ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] if github else ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"] - done = ran(command, root) - if isinstance(done, Failure) or done.returncode: - return f"cannot be listed: `{' '.join(command[:3])}` {done.reason if isinstance(done, Failure) else f'exited {done.returncode}: {done.stderr.strip()}'}" - rows = [line.split("\t") for line in done.stdout.splitlines()] - opened = [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2] if github else [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch] - return ", ".join(opened) if opened else "none." + return None + forge = forge_of(url) + return forge, ran(pulls_command(forge, branch), root) -def bundled(planned: list[Item], first: Item) -> list[str]: - candidates = bundle_candidates(planned, first) - if not candidates: - return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."] - listed = [f" - item {item.id}, L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates] - return [f"- The items of release {release_name(first)} that item {first.id}'s chunk may take too, where `~/.claude/CLAUDE.md` → \"Working loop\" lets them share it:", *listed] - - -def named(text: str, base: pathlib.Path) -> list[str]: +def named_files(text: str, base: pathlib.Path) -> list[NamedPath] | Failure: tracked = git("-C", str(base), "ls-files") if isinstance(tracked, Failure): - return [f"- The files the item names: cannot be listed: {tracked.reason}"] - paths = named_paths(text, tracked.splitlines()) - if not paths: - return ["- The item names no file or folder git tracks."] - return ["- The files and folders the item names:", *(f" - `{span}`: {size(base / span, count)}" for span, count in paths)] + return tracked + return [NamedPath(span, files, line_count(base / span)) for span, files in named_paths(text, tracked.splitlines())] -def size(path: pathlib.Path, files: int) -> str: +def line_count(path: pathlib.Path) -> int | Failure | None: + """A file's lines, or why they cannot be read; None for a folder.""" if not path.is_file(): - return counted(files, "file", "files") + return None + text = text_of(path) + return text if isinstance(text, Failure) else len(text.splitlines()) + + +def tools_run(item_id: int, worktree: pathlib.Path) -> list[tuple[str, Ran | Failure]]: + commands = [[part.format(item=item_id) for part in tool] for tool in TOOLS] + return [(" ".join(command), ran([sys.executable, str(BIN / command[0]), *command[1:]], worktree)) for command in commands] + + +def text_of(path: pathlib.Path) -> str | Failure: + """A file's text; empty where there is no such file.""" try: - return counted(len(path.read_text(encoding="utf-8").splitlines()), "line", "lines") + return path.read_text(encoding="utf-8") + except FileNotFoundError: + return "" except (OSError, UnicodeDecodeError) as failure: - return f"cannot be read: {failure}" + return Failure(str(failure)) -def ran(command: list[str], cwd: pathlib.Path) -> subprocess.CompletedProcess[str] | Failure: +def ran(command: list[str], cwd: pathlib.Path) -> Ran | Failure: try: - return subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) + done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) except (OSError, subprocess.TimeoutExpired) as failure: return Failure(f"could not finish: {failure}") - - -def printed(shown: tuple[str, ...], command: list[str], cwd: pathlib.Path) -> str: - """What command printed, run in cwd, and its exit code, under its name as shown.""" - name = f"`{' '.join(shown)}`" - done = ran(command, cwd) - if isinstance(done, Failure): - return f"{name} {done.reason}" - output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip()) - return f"{name} exited {done.returncode}, printing:\n\n{quoted(output)}" if output else f"{name} exited {done.returncode}, printing nothing." - - -def release_name(item: Item) -> str: - return ".".join(map(str, item.release)) - - -def counted(count: int, one: str, many: str) -> str: - return f"{count} {one if count == 1 else many}" + return Ran(done.returncode, done.stdout, done.stderr) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 94828f69..d0e1a755 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -8,9 +8,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from chunk_preflight import facts +from failure import Failure +from chunk_preflight.gathered import forge_of, Gathered, held_back, ItemFacts, NamedPath, planned, Ran, Release, Worktree, worktree_add from test_env import isolated_env -from todo_table import items +from chunk_preflight.facts import open_pulls, render, unreleased_entries BIN = pathlib.Path(__file__).resolve().parents[1] README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n" @@ -41,9 +42,11 @@ TODO = """# todo Change `src/app.py`'s `run` and the files under `src`, not `gone.py`. """ +# The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files. +SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.") CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" # Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1. -FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-3\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n" +FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n" class Repo: @@ -63,59 +66,65 @@ class Repo: self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")} self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin)) self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root)) - self.write("README.md", README) - self.write("src/app.py", "def run():\n\treturn 1\n\n") - self.commit("start") + self.write(self.root, "README.md", README) + self.write(self.root, "src/app.py", "def run():\n\treturn 1\n\n") + self.commit(self.root, "start") self.git(self.root, "tag", "v0.1.0") - self.write("CHANGELOG.md", CHANGELOG) + self.write(self.root, "CHANGELOG.md", CHANGELOG) if todo: - self.write("todo.md", todo) - self.commit("plan") + self.write(self.root, "todo.md", todo) + self.commit(self.root, "plan") self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0") def git(self, cwd, *args): return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout - def write(self, path, text): - (self.root / path).parent.mkdir(parents=True, exist_ok=True) - (self.root / path).write_text(text) + def write(self, root, path, text): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text(text) - def commit(self, title): - self.git(self.root, "add", "-A") - self.git(self.root, "commit", "--quiet", "-m", title) + def commit(self, root, title): + self.git(root, "add", "-A") + self.git(root, "commit", "--quiet", "-m", title) + + def push_from_elsewhere(self, path, text): + """Pushes a change to path from another clone, leaving the checkout behind origin.""" + other = self.temp / "other" + self.git(self.temp, "clone", "--quiet", str(self.origin), str(other)) + self.write(other, path, text) + self.commit(other, "elsewhere") + self.git(other, "push", "--quiet", "origin", "main") def preflight(self): return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env=self.env, text=True, timeout=120) class ChunkPreflightTool(unittest.TestCase): - def test_makes_the_items_worktree_off_the_fetched_default_branch_and_states_the_chunks_facts(self): + def test_fast_forwards_the_checkout_reads_its_plan_and_makes_the_items_worktree_off_the_fetched_default_branch(self): repo = Repo(self) + repo.push_from_elsewhere("todo.md", SHIPPED) done = repo.preflight() self.assertEqual(done.returncode, 0, done.stderr) - worktree = repo.temp / "proj-item-3" - self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-3") + self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main")) + worktree = repo.temp / "proj-item-7" + self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-7") self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main")) for fact in ( - "Last version cut: v0.1.0. Unreleased: 2 entries under CHANGELOG.md → ## Unreleased.", - "Next release: 0.2.0. Its first item that does not wait: item 3, L 4, E + I 5.", - f"Worktree: {worktree}, on the new branch item-3, made off origin/main.", - "- item 7, L 1, E + I 2, S 1: **Do the thing after.**", - "- `src/app.py`: 3 lines", - "- `src`: 1 file", - "Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", - "- Open pull requests from item-3: #12 https://forge/pulls/12\n", + "fast-forwarded to origin/main", + "item 7, L 1, E + I 2", + f"{worktree}, on the new branch item-7, made off origin/main.", + "#12 https://forge/pulls/12", + "`src/app.py`: 3 lines", + "`src`: 1 file", "`rank_todo.py --check todo.md` exited 0", - "`larv-review needs-scoring-run 3` exited 0", + "`larv-review needs-scoring-run 7` exited 0", "`reading-cost` exited 0", "`larv-review places` exited 0", + f"to {worktree}/docs/reading-cost.md", ): self.assertIn(fact, done.stdout) - self.assertNotIn("item 5,", done.stdout) - self.assertNotIn("item 8,", done.stdout) - self.assertNotIn("item 9,", done.stdout) + self.assertNotIn("#13", done.stdout) self.assertNotIn("`gone.py`:", done.stdout) - self.assertIn(f"to {worktree}/docs/reading-cost.md", done.stdout) def test_continues_the_items_worktree_and_else_its_pushed_branch(self): repo = Repo(self) @@ -131,12 +140,19 @@ class ChunkPreflightTool(unittest.TestCase): self.assertIn(f"Worktree: {worktree}, on the new branch item-3, made off origin/item-3.", repo.preflight().stdout) self.assertTrue((worktree / "work.txt").exists()) + def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self): + repo = Repo(self) + (repo.temp / "proj-item-3").mkdir() + done = repo.preflight() + self.assertIn(f"Worktree: none made, since {repo.temp / 'proj-item-3'} exists", done.stdout) + self.assertNotIn("`reading-cost`", done.stdout) + def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self): repo = Repo(self, todo="") done = repo.preflight() self.assertEqual(done.returncode, 0, done.stderr) self.assertIn("Last version cut: v0.1.0.", done.stdout) - self.assertIn("No plan item: origin/main holds no todo.md items table, so no worktree was made.", done.stdout) + self.assertIn("No plan item: the checkout holds no todo.md items table, so no worktree was made.", done.stdout) self.assertFalse((repo.temp / "proj-item-3").exists()) def test_exits_1_outside_a_checkout(self): @@ -146,15 +162,97 @@ class ChunkPreflightTool(unittest.TestCase): self.assertIn("git rev-parse --show-toplevel", done.stderr) -class Facts(unittest.TestCase): - def test_counts_the_top_level_entries_under_unreleased(self): - self.assertEqual(facts.unreleased_entries(CHANGELOG), 2) - self.assertEqual(facts.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0) - self.assertIsNone(facts.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n")) +def item_facts(**fields): + """Item 3's facts, its worktree made, with fields given replacing the rest.""" + plan = planned(TODO) + return ItemFacts(**{"plan": plan, "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields}) - def test_bundles_an_item_blocked_only_by_items_the_chunk_may_take(self): - found = items(TODO.replace("| 9 | 0.3.0 | |", "| 9 | 0.2.0 | 7 |")) - self.assertEqual([item.id for item in facts.bundle_candidates(found, found[1])], [7, 9]) + +def rendered(item, release=Release("v0.1.0", CHANGELOG, 4), kept_as_is=None): + return "\n".join(render(Gathered("origin/main", None, kept_as_is, release, item))) + + +class Render(unittest.TestCase): + def test_states_the_next_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self): + said = rendered(item_facts()) + self.assertIn("0.2.0", said) + self.assertIn("item 3, L 4, E + I 5", said) + self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said) + self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said) + self.assertNotIn("item 8,", said) + + def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self): + self.assertIn("v0.1.0. Unreleased: 2 entries", rendered("no item")) + self.assertIn("v0.1.0. Unreleased: 4 commits since v0.1.0", rendered("no item", Release("v0.1.0", "# Changelog\n", 4))) + self.assertIn("none. Unreleased: 1 commit on origin/main", rendered("no item", Release(None, "", 1))) + + def test_states_whether_the_checkout_was_fast_forwarded_and_why_there_is_no_plan_item(self): + self.assertIn("The checkout was fast-forwarded to origin/main.", rendered("every item waits")) + said = rendered("every item waits", kept_as_is="it holds uncommitted changes") + self.assertIn("The checkout was not fast-forwarded: it holds uncommitted changes", said) + self.assertIn("No plan item: every item waits, so no worktree was made.", said) + + def test_states_the_open_pull_requests_from_the_items_branch_or_why_none_are_listed(self): + self.assertIn("Open pull requests from item-3: #12 https://forge/pulls/12\n", rendered(item_facts(pulls=("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", ""))))) + self.assertIn("Open pull requests from item-3: none.", rendered(item_facts(pulls=("gh", Ran(0, "", ""))))) + self.assertIn("Open pull requests from item-3: none, as the checkout has no origin remote.", rendered(item_facts())) + self.assertIn("Open pull requests from item-3: cannot be listed: `tea pulls list` exited 1: no login", rendered(item_facts(pulls=("tea", Ran(1, "", "no login\n"))))) + + def test_states_each_named_files_lines_and_each_named_folders_files(self): + said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8"))])) + self.assertIn("`src/app.py`: 3 lines", said) + self.assertIn("`src`: 2 files", said) + self.assertIn("`bad.py`: cannot be read: not UTF-8", said) + + def test_states_what_each_tool_printed_and_its_exit_code(self): + said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review places", Failure("could not finish: timed out"))])) + self.assertIn("`rank_todo.py --check todo.md` exited 0, printing:\n\n> ranked", said) + self.assertIn("`reading-cost` exited 1, printing nothing.", said) + self.assertIn("`larv-review places` could not finish: timed out", said) + + +class OpenPulls(unittest.TestCase): + def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self): + self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"]) + self.assertEqual(open_pulls("index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n13\tother\thttps://forge/pulls/13\n", "tea", "item-3"), ["#12 https://forge/pulls/12"]) + + +class Gathering(unittest.TestCase): + def test_counts_the_top_level_entries_under_unreleased(self): + self.assertEqual(unreleased_entries(CHANGELOG), 2) + self.assertEqual(unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0) + self.assertIsNone(unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n")) + + def test_picks_the_next_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self): + self.assertEqual(planned(TODO).first.id, 3) + self.assertEqual(planned(""), "the checkout holds no todo.md items table") + self.assertEqual(planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |")), "every item of the checkout's next release waits") + self.assertEqual(planned(Failure("Permission denied")), "the checkout's todo.md cannot be read: Permission denied") + self.assertIn("todo.md's details cannot be read", planned(TODO + "```\n").text) + + def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self): + path = pathlib.Path("/c/proj-item-3") + self.assertEqual(worktree_add("item-3", path, "origin/main", True, True)[0], ["worktree", "add", "--quiet", "/c/proj-item-3", "item-3"]) + self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"]) + self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"]) + + def test_lists_pull_requests_with_gh_on_a_github_origin_and_with_tea_elsewhere(self): + self.assertEqual(forge_of("git@github.com:o/r.git"), "gh") + self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea") + + def test_fast_forwards_only_a_clean_checkout_on_the_default_branch_that_is_behind_it(self): + cases = ( + (("main", "main\n", "", "2\n"), "it has no origin remote"), + (("origin/main", Failure(""), "", "2\n"), "it is on no branch"), + (("origin/main", "item-5\n", "", "2\n"), "it is on item-5, not main"), + (("origin/main", "main\n", " M todo.md\n", "2\n"), "it holds uncommitted changes"), + (("origin/main", "main\n", "", "0\n"), "it is not behind origin/main"), + (("origin/main", "main\n", Failure("git status: broken"), "2\n"), "its status cannot be read: git status: broken"), + (("origin/main", "main\n", "", "2\n"), None), + ) + for found, why in cases: + with self.subTest(found=found): + self.assertEqual(held_back(*found), why) if __name__ == "__main__": diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 24dd0cce..faf513b1 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -114,7 +114,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, preflight=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 97bbcc75..f130248a 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -14,23 +14,29 @@ REVIEWS: tuple[tuple[str, ReviewKind], ...] = (("each reviewer", "reviewer"), (" def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str: - """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text, or empty.""" + """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip() - routed = f"{routed_by(route, anchor)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") - found = f"{facts}\n\n" if facts else "" - return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{found}The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" + routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") + return f"{task}\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" def routed_by(route: Route, anchor: Rung | None) -> str: - return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)} After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." + return f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item {route.item}.{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}" + + +def recount(route: Route) -> str: + """Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code.""" + return f" After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." def preflight_facts(printed: str) -> str: + """What chunk-preflight printed, for the worker to take as found.""" return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}" def preflight_failed(reason: str) -> str: - return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself: {reason}" + """Has the worker find the facts chunk-preflight would have, its worktree and open pull request among them.""" + return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Continue any open draft PR or worktree for the chunk before creating a new one. Why it could not run: {reason}" def review_launches(route: Route, anchor: Rung | None) -> str: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 0ef0d778..fb5ed116 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -25,6 +25,8 @@ from model_routing import worker_rungs @dataclasses.dataclass(frozen=True) class Cycle: effects: Effects + # What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began. + facts: str judge_model: str paths: Paths premises: str @@ -84,9 +86,8 @@ def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop: print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) if stop := keep_answer(cycle, answered): return stop - facts = preflight(cycle) if answered is None and not session_open(cycle.session) else "" # worker_start runs inside the lambda: a failed attempt may have opened the session. - if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, facts), worker_environment(cycle), cycle.effects), cycle.effects): + if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered), worker_environment(cycle), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") @@ -97,23 +98,12 @@ def worker_environment(cycle: Cycle) -> dict[str, str]: return worker_rungs.environment(cycle.anchor, cycle.route) -def preflight(cycle: Cycle) -> str: - """The facts chunk-preflight printed for a fresh worker, or why it could not run them; run once per chunk start, outside the worker's retries.""" - try: - done = cycle.effects.preflight(cycle.root) - except OSError as failure: - return prompts.preflight_failed(str(failure)) - if done.returncode: - return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") - return prompts.preflight_facts(done.stdout.strip()) - - -def worker_start(cycle: Cycle, answered: QuotedAnswer | None, facts: str) -> list[str]: +def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]: if answered is not None: return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer), resume=True) if session_open(cycle.session): return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True) - return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, facts), resume=False) + return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False) def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 7a20fe50..215980c1 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -1,12 +1,12 @@ import dataclasses import os -import pathlib import subprocess import sys import time import typing -PREFLIGHT = pathlib.Path(__file__).resolve().parents[1] / "chunk-preflight" +# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. +PYTHON_TIMEOUT = 600 class Streaming(typing.Protocol): @@ -27,9 +27,8 @@ class Effects: local_time: typing.Callable[[float], str] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] - # Runs chunk-preflight in the given directory. - preflight: typing.Callable[[str], subprocess.CompletedProcess[str]] - python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]] + # Runs a Python script in a directory, as run_python does. + python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] sleep: typing.Callable[[float], None] stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming] @@ -56,8 +55,16 @@ def system_effects() -> Effects: local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), - preflight=lambda cwd: subprocess.run([sys.executable, str(PREFLIGHT)], capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True), - python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), + python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT), sleep=time.sleep, stream_claude=StreamingClaude, ) + + +def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]: + """Runs a Python script in cwd. One still running after timeout seconds is stopped, and reads as exit 1, saying so on stderr.""" + command = [sys.executable, *args] + try: + return subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 13e4c54b..db2aadd9 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -5,9 +5,11 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md -items, or else the task, and never widen them. Before that first worker, loop-claude runs -bin/chunk-preflight at the checkout root, which finds the chunk's mechanical facts and makes its -worktree; the prompt quotes what it printed, or why it could not run. A judge then reads the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, +items, or else the task, and never widen them. As a chunk starts, before it is routed, loop-claude +runs bin/chunk-preflight (bin/chunk_preflight/), which fast-forwards the checkout and finds the +chunk's facts; chunk-preflight --help lists them, and prompts.preflight_facts in +bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A judge then reads the +transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a @@ -46,8 +48,9 @@ run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_ for the worker and the interrupt; with both set, nothing is asked. Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the -interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, todo.md's top -item in the next release that does not wait routes it: an item waits while it is marked question, +interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, the checkout's +todo.md, read once chunk-preflight has run, routes it, so routing and the preflight's facts name one +item: the next release's top item that does not wait. An item waits while it is marked question, or while an item that blocks it is still in the table. The item's L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I unscored, the chunk runs on the model's @@ -55,9 +58,9 @@ cheapest rung. The item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there, never below the worker's rung. The worker's first prompt names the rung and the item, and asks the worker to name each item the chunk takes, with its L and E + I, and to count the item's size again -once it has read the code: a re-score whose L picks a higher rung is an escalation trigger. The prompt names the rung of each -review that runs on a rung other than the worker's: the reviewers' rung for the reviewers, and the -cheapest rung for each comprehension seat and the security pass. It also names the reviewers' rung +once it has read the code (prompts.recount). The prompt names the rung of each review that runs on +a rung other than the worker's: the reviewers' rung for the reviewers, and the cheapest rung for +each comprehension seat and the security pass. It also names the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run. When the worker runs below the cheapest rung, the prompt has it launch each subagent that files or scores todo.md items on the rung subagent-rung --plan prints. The prompt after @@ -161,10 +164,11 @@ from transcript_archive import outcomes from loop_claude.paths import Paths from project_key import project_key from model_routing.ladder import project_rung, Rung +from loop_claude.cycle import prompts from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records from model_routing.route import Route, route_from -from claude_code.session import Session, session_named, transcript_file +from claude_code.session import Session, session_named, session_open, transcript_file from loop_claude.stop import Stop @@ -191,6 +195,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if stop := exec_if_edited(launcher, baseline, loop_run, effects): return stop loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) + # First, so the premises, the records and the plan item routing reads are the checkout's as the preflight fast-forwarded it. + facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects) premises = read_premises(loop_run.root) if isinstance(premises, Stop): return premises @@ -205,7 +211,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(root)) route = loop_run.route or Route(Rung(models.worker)) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) - verdict = run_cycle(Cycle(anchor=anchor, effects=effects, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) + verdict = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) if isinstance(verdict, Stop): return verdict before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict) @@ -250,8 +256,19 @@ def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | No return route_from(worker) if worker else None +def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str: + """What chunk-preflight printed at the checkout root, for a fresh worker's prompt, or why it could not run.""" + try: + done = effects.python([str(preflight)], root) + except OSError as failure: + return prompts.preflight_failed(str(failure)) + if done.returncode: + return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") + return prompts.preflight_facts(done.stdout.strip()) + + def plan_item(root: str) -> Item | None: - """The item that routes a chunk; None without one, so the chunk runs on the project's rung.""" + """The item that routes a chunk, from the checkout's todo.md: the file chunk-preflight reads, and the pick, todo_table.next_item, it makes. None without one, so the chunk runs on the project's rung.""" try: item = routed_item(pathlib.Path(root, "todo.md").read_text(encoding="utf-8")) except FileNotFoundError: diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index a4298d3e..404cd9be 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -81,7 +81,7 @@ def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, eff if fingerprint(launcher) == baseline: return None try: - trial = effects.python([str(launcher), "--help"]) + trial = effects.python([str(launcher), "--help"], loop_run.root) if trial.returncode != 0: print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) return None diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 27648b7e..1e4f2fb6 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -351,9 +351,9 @@ class Cycles(unittest.TestCase): self.assertIsNone(argument(workers[1], "--session-id")) self.assertIsNone(argument(workers[1], "--name")) self.assertEqual(argument(workers[2], "--session-id"), session) - self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) + self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\n")) self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe.")) - self.assertIn("`~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- No default branch: no origin remote, and no main or master branch to take as the default branch\n\nThe chunk's", argument(workers[0], "-p")) + self.assertIn("\n\n- No default branch: no origin remote, and no main or master branch to take as the default branch\n\nThe chunk's", argument(workers[0], "-p")) self.assertNotIn(TASK, argument(workers[1], "-p")) self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p")) self.assertIn("as the work remaining:\n\n> started\n\n", argument(workers[1], "-p")) @@ -398,6 +398,30 @@ class Cycles(unittest.TestCase): self.assertIn(" Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at medium effort, routed by item 4's L of 2 and E + I of 3\n\n Stepped up\n\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) self.assertIn(" Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) + def test_fast_forwards_the_checkout_before_routing_so_routing_and_the_preflight_name_the_same_item(self): + checkout = Checkout(self) + checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" + origin = checkout.temp / "origin.git" + checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin)) + checkout.git("symbolic-ref", "HEAD", "refs/heads/main") + (checkout.root / "todo.md").write_text(TODO) + checkout.git("add", "-A") + checkout.git("commit", "--quiet", "-m", "plan item 4") + checkout.git("remote", "add", "origin", str(origin)) + checkout.git("push", "--quiet", "--set-upstream", "origin", "main") + # Item 4 ships elsewhere, and item 6 is next; the checkout is behind origin. + elsewhere = checkout.temp / "elsewhere" + checkout.git("clone", "--quiet", str(origin), str(elsewhere)) + (elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |")) + checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "item 4 shipped, plan item 6") + checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main") + run = checkout.run([worker()]) + self.assertEqual(run.code, 130) + prompt = argument(run.calls[0], "-p") + self.assertIn("routed by item 6's L of 4", prompt) + self.assertIn("Its first item that does not wait: item 6,", prompt) + self.assertIn("The checkout was fast-forwarded to origin/main.", prompt) + def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index b70255cb..546eb48c 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -18,7 +18,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive from loop_claude.project import checkout, model_choice, records -from loop_claude.effects import Effects +from loop_claude.effects import Effects, run_python from claude_code import entries, reply, session from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from @@ -48,9 +48,9 @@ def human(content): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), preflight=(), python=(), streams=(), on_terminal=True): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True): self.calls = [] - self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "preflight": list(preflight), "python": list(python), "stream_claude": list(streams)} + self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} self.terminal = on_terminal self.worker_environments = [] self.terminal_environments = [] @@ -65,8 +65,7 @@ class FakeEffects: local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW, on_terminal=lambda: self.terminal, - preflight=self.preflight, - python=lambda args: self.answer("python", args), + python=lambda args, cwd: self.answer("python", (args, cwd)), sleep=lambda seconds: self.calls.append(("sleep", seconds)), stream_claude=self.stream, ) @@ -75,13 +74,6 @@ class FakeEffects: self.terminal_environments.append(env) return self.answer("claude_on_terminal", args) - def preflight(self, cwd): - """Answers from the script while it lasts, and else with one fact, since most cycles start a fresh worker.""" - if self.scripts["preflight"]: - return self.answer("preflight", cwd) - self.calls.append(("preflight", cwd)) - return ran("- A preflight fact.") - def stream(self, args, cwd, env): self.worker_environments.append(env) return self.answer("stream_claude", args) @@ -192,8 +184,8 @@ class Cycles(unittest.TestCase): self.session = session.session_named("A proj loop-claude", self.paths.claude_code_transcripts) self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) - def cycle(self, fake, records="", unfinished_evidence=""): - return run.Cycle(anchor=None, effects=fake.effects(), judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence) + def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): + return run.Cycle(anchor=None, effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence) def archived_outcomes(self): return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md")) @@ -204,23 +196,14 @@ class Cycles(unittest.TestCase): self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"]) self.assertIsNone(session.transcript_file(self.session)) - def test_a_fresh_worker_reads_what_the_preflight_printed_at_the_checkout_root_and_a_resumed_one_runs_none(self): + def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self): worker = Worker(self.paths.claude_code_transcripts.parent) fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")]) self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working")) self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Finished("working")) - self.assertEqual(fake.made("preflight"), [str(self.home)]) fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude")) - self.assertIn("loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- A preflight fact.", fresh) - self.assertNotIn("chunk-preflight", resumed) - - def test_a_fresh_worker_finds_the_facts_itself_where_the_preflight_fails(self): - for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (OSError(2, "No such file or directory"), "[Errno 2] No such file or directory")): - with self.subTest(why=why): - fake = FakeEffects(preflight=[failed], streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working")) - args = fake.made("stream_claude")[0] - self.assertIn(f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself: {why}", args[args.index("-p") + 1]) + self.assertIn("- A preflight fact.", fresh) + self.assertNotIn("- A preflight fact.", resumed) def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviewers_in_its_environment(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) @@ -819,39 +802,79 @@ class Steps(unittest.TestCase): self.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) +class ChunkFacts(unittest.TestCase): + PREFLIGHT = pathlib.Path("/b/chunk-preflight") + + def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self): + fake = FakeEffects(python=[ran("- A fact.\n")]) + said = main.chunk_facts(self.PREFLIGHT, "/r", fake.effects()) + self.assertEqual(fake.made("python"), [(["/b/chunk-preflight"], "/r")]) + self.assertIn("\n\n- A fact.", said) + + def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self): + for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "it exited 1"), (OSError(2, "No such file or directory"), "No such file or directory")): + with self.subTest(why=why): + said = main.chunk_facts(self.PREFLIGHT, "/r", FakeEffects(python=[failed]).effects()) + self.assertIn("find the chunk's facts yourself", said) + self.assertIn(why, said) + + +class PythonEffect(unittest.TestCase): + def test_runs_a_script_in_the_given_directory(self): + with tempfile.TemporaryDirectory() as cwd: + self.assertEqual(run_python(["-c", "import os; print(os.getcwd())"], cwd, 60).stdout.strip(), os.path.realpath(cwd)) + + def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self): + done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5) + self.assertEqual(done.returncode, 1) + self.assertIn("after 0.5 s", done.stderr) + + class WorkerArgs(unittest.TestCase): SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung." + # What the preflight found, as the fresh prompt quotes it. + FACTS = "- A preflight fact." def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): - routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, "") - self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3. After your first read", routed) - unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, "") - self.assertIn("before creating a new one.\n\nThe chunk's", unrouted) + routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + self.assertIn("Do it.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed) + unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) + self.assertIn(f"Do it.\n\n{self.FACTS}\n\nThe chunk's", unrouted) self.assertNotIn("loop-claude runs you on", unrouted) - def test_puts_the_preflights_facts_before_the_scope_and_asks_the_worker_to_count_the_items_size_again(self): - fresh = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, prompts.preflight_facts("- A fact.")) - self.assertIn("whether or not it is item 3. After your first read of the code, count item 3's size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1.\n\nloop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n- A fact.\n\nThe chunk's", fresh) + def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): + routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + self.assertIn("After your first read of the code, count item 3's size again", routed) + self.assertIn("escalation trigger 1", routed) + self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) + self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) + + def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_and_continue_an_open_pr_itself(self): + self.assertIn("Take what it printed as found rather than finding it again:\n\n- A fact.", prompts.preflight_facts("- A fact.")) + failed = prompts.preflight_failed("git could not start") + self.assertIn("find the chunk's facts yourself", failed) + self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.", failed) + self.assertIn("git could not start", failed) def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): opus = Rung("claude-opus-5-5", "medium") - below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, "") + below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS) self.assertIn(f"whether or not it is item 3. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 ` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", below) - self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) + self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)) def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): opus = Rung("claude-opus-5-5", "medium") - level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, "") + level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS) self.assertIn("whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", level) - below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, "") + below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS) self.assertIn(f"whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below) self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 6), opus)) def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): opus = Rung("claude-opus-5-5", "medium") taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8." - self.assertIn(f"whether or not it is item 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) + self.assertIn(f"whether or not it is item 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus)) self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 4), opus)) self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus)) @@ -864,7 +887,7 @@ class WorkerArgs(unittest.TestCase): def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): opus = Rung("claude-opus-5-5", "medium") - above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, "") + above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, self.FACTS) stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus) self.assertIn(f"{prompts.ANSWERS_RECORDED}. loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", stepped_up) self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus)) @@ -873,7 +896,7 @@ class WorkerArgs(unittest.TestCase): def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): opus = Rung("claude-opus-5-5", "medium") - fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "") + fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS) self.assertIn("whether or not it is item 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh) self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)) self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus)) @@ -881,12 +904,12 @@ class WorkerArgs(unittest.TestCase): self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus)) - self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, "")) + self.assertIn("Do it.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS)) def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): opus = Rung("claude-opus-5-5", "medium") offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`." - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)) self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)) self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus)) @@ -895,19 +918,19 @@ class WorkerArgs(unittest.TestCase): both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`." self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both)) self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both)) - self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, "").split("\n\nThe chunk's")[0].endswith(both)) + self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both)) self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort xhigh`, and a comprehension seat with `model opus, effort high`.")) self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort max`, and a comprehension seat with `model opus, effort high`.")) self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.")) self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None)) - self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, "")) - self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, "")) + self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)) + self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)) fable = Rung("claude-fable-5-1", "max") self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable)) def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) - fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, ""), resume=False) + fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False) self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True) diff --git a/bin/stability_replay/test_stability_replay.py b/bin/stability_replay/test_stability_replay.py index c26416c7..d1012e4a 100644 --- a/bin/stability_replay/test_stability_replay.py +++ b/bin/stability_replay/test_stability_replay.py @@ -213,7 +213,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, preflight=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 94af948c..311a94f0 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -342,6 +342,13 @@ class Blockers(unittest.TestCase): rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)] self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"]) + def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self): + # Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release. + waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |")) + self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), []) + answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |")) + self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 4, 5]) + def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self): finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |") ranked = self.ranked(finished) diff --git a/bin/todo_table.py b/bin/todo_table.py index 37df9035..6e797230 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -158,9 +158,9 @@ def items_table(lines: list[str]) -> Table | None | Failure: return table -def waiting(found: list[Item]) -> set[int]: - """The IDs of the items that wait: each marked question, or blocked by an item the table still holds. Row order does not change the result.""" - held = {item.id for item in found} +def waiting(found: list[Item], done: set[int]) -> set[int]: + """The IDs of the items that wait: each marked question, or blocked by an item the table still holds and done does not name. Row order does not change the result.""" + held = {item.id for item in found} - done return {item.id for item in found if item.exempt == "question" or held.intersection(item.blocked_by)} @@ -169,10 +169,19 @@ def next_item(found: list[Item]) -> Item | None: if not found: return None release = min(item.release for item in found) - waits = waiting(found) + waits = waiting(found, set()) return next((item for item in found if item.release == release and item.id not in waits), None) +def bundle_candidates(found: list[Item], first: Item) -> list[Item]: + """The items of first's release, in the table's order, that a chunk taking first may take too: those that do not wait once the chunk's own items count as done.""" + chunk = {item.id for item in found if item.release == first.release} + # Dropping an item that waits may make another wait on it, so drop until none waits. + while waits := waiting(found, chunk) & chunk: + chunk -= waits + return [item for item in found if item.id in chunk and item.id != first.id] + + def item_details(todo: str) -> dict[int, str] | Failure: """Each item's detail under ## Details, by ID; empty where todo.md has no such section.""" section = DETAILS.search(todo) -- 2.52.0 From 50541c32fdd3335e86f1fb03ac7d3d431b784039 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 01:04:44 +0200 Subject: [PATCH 05/22] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20nothing=20to=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 495184b9c64277d522c3d0c5e20fae084f1a45f6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:07:40 +0200 Subject: [PATCH 06/22] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1;=20read=20the=20plan=20from=20?= =?UTF-8?q?the=20fetched=20default=20branch=20for=20routing=20and=20the=20?= =?UTF-8?q?preflight=20alike=20and=20drop=20the=20fast-forward,=20name=20n?= =?UTF-8?q?o=20item=20where=20the=20release=20after=20the=20last=20tag=20h?= =?UTF-8?q?as=20none,=20tell=20an=20empty=20items=20table=20from=20none,?= =?UTF-8?q?=20time=20out=20the=20fetch,=20return=20run=5Fpython's=20errors?= =?UTF-8?q?=20as=20exit=20codes,=20test=20the=20error=20paths=20and=20the?= =?UTF-8?q?=20gh=20rows,=20assert=20facts=20in=20place=20of=20sentences,?= =?UTF-8?q?=20keep=20the=20open-PR=20sentence=20in=20every=20fresh=20promp?= =?UTF-8?q?t,=20name=20the=20item=20branch=20in=20CLAUDE.md,=20and=20measu?= =?UTF-8?q?re=20item=20175=20against=20five=20chunks=20with=20counter-sign?= =?UTF-8?q?als?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- CLAUDE.md | 3 +- README.md | 2 +- bin/chunk-preflight | 3 +- bin/chunk_preflight/facts.py | 32 +- bin/chunk_preflight/gathered.py | 94 +++--- bin/chunk_preflight/main.py | 138 ++++---- bin/chunk_preflight/test_chunk_preflight.py | 348 ++++++++++++++++---- bin/git_repo.py | 71 ++-- bin/larv_review/git.py | 6 +- bin/loop_claude/cycle/prompts.py | 6 +- bin/loop_claude/effects.py | 6 +- bin/loop_claude/loop/main.py | 51 ++- bin/loop_claude/loop/reload.py | 8 +- bin/loop_claude/test_black_box.py | 47 ++- bin/loop_claude/test_loop_claude.py | 59 ++-- bin/repo_checks/test_types.py | 2 +- bin/test_git_repo.py | 28 ++ bin/test_rank_todo.py | 4 + skills/larv-review/SKILL.md | 2 +- todo.md | 6 +- 21 files changed, 621 insertions(+), 297 deletions(-) create mode 100644 bin/test_git_repo.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fd56429a..64d761d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ - `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names. - `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`. - `loop-claude` archives each judge reply it rejects in the chunk's `.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1. -- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight first fast-forwards the checkout to origin's default branch where the checkout is on that branch and holds no uncommitted change, so the chunk is routed on the plan origin holds. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. +- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight fetches origin and reads `todo.md` from its default branch, leaving the checkout as it is, and `loop-claude` routes on that same `todo.md`, so an edit to `todo.md` routes a chunk only once the default branch holds it. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Where `todo.md` holds no item for the release after the newest tag, it names no item, and says that release is finished and ready to cut, or is to be planned first. It stops a fetch, forge CLI or tool still running after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. ## 0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md index 6c1f692a..1753de5d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them. -- **Read the plan and the decisions only as far as the chunk needs.** Run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs. +- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the item's row and detail and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs. - **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which four things hold: one PR title states what they achieve together, without listing them; they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open. - **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it. @@ -78,6 +78,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. +- Branch for a `todo.md` item without a ticket: `item-`, in the worktree `-item-` beside the checkout, as `chunk-preflight` makes them. - Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. ## Handoffs diff --git a/README.md b/README.md index bad1a399..38ffbad1 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. -- `chunk-preflight` fast-forwards the checkout, finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts. +- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts. - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places; `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. diff --git a/bin/chunk-preflight b/bin/chunk-preflight index 4a0ec9bb..b31d06cc 100755 --- a/bin/chunk-preflight +++ b/bin/chunk-preflight @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import sys @@ -6,4 +7,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from chunk_preflight import main -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], os.environ)) diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 78bb02dd..76ad7d95 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,18 +1,17 @@ """The lines the preflight prints, stated from what it gathered.""" from todo_table import bundle_candidates, Item from failure import Failure -from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Plan, pulls_command, Ran, Release +from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, PULLS_LIST, Ran, Release, version from markdown_text import quoted, sections def render(found: Gathered) -> list[str]: """One `- ` line per fact, then the item's tagline and detail, and what each tool printed.""" note = [f"- {found.note}"] if found.note else [] - checkout = f"- The checkout was not fast-forwarded: {found.kept_as_is}" if found.kept_as_is else f"- The checkout was fast-forwarded to {found.default}." - head = [*note, checkout, f"- {last_release(found.default, found.release)}"] - if isinstance(found.item, str): - return [*head, f"- No plan item: {found.item}, so no worktree was made."] - return [*head, *item_lines(found.item)] + head = [*note, f"- {last_release(found.default, found.release)}"] + if isinstance(found.item, NoItem): + return [*head, f"- No plan item: {found.item.why} No worktree was made."] + return [*head, *item_lines(found.default, found.item)] def last_release(default: str, release: Release) -> str: @@ -22,9 +21,10 @@ def last_release(default: str, release: Release) -> str: entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." - commits = release.commits.reason if isinstance(release.commits, Failure) else counted(release.commits, "commit", "commits") since = f"since {release.tag}" if release.tag else f"on {default}" - return f"{cut} Unreleased: {commits} {since}, and no ## Unreleased in CHANGELOG.md." + commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}" + changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md" + return f"{cut} Unreleased: {commits}; {changelog}." def unreleased_entries(changelog: str) -> int | None: @@ -33,11 +33,11 @@ def unreleased_entries(changelog: str) -> int | None: return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) -def item_lines(item: ItemFacts) -> list[str]: +def item_lines(default: str, item: ItemFacts) -> list[str]: first = item.plan.first worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}" return [ - f"- Next release, in the checkout's todo.md: {release_name(first)}. Its first item that does not wait: item {first.id}, {levels(first)}.", + f"- The earliest release in {default}'s todo.md: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.", f"- Worktree: {worktree}", f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}", *bundled(item.plan), @@ -52,7 +52,7 @@ def pulls_text(pulls: tuple[Forge, Ran | Failure] | None, branch: str) -> str: if pulls is None: return "none, as the checkout has no origin remote." forge, done = pulls - shown = " ".join(pulls_command(forge, branch)[:3]) + shown = " ".join(PULLS_LIST[forge]) if isinstance(done, Failure): return f"cannot be listed: `{shown}` {done.reason}" if done.code: @@ -71,9 +71,9 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]: def bundled(plan: Plan) -> list[str]: first, candidates = plan.first, bundle_candidates(plan.items, plan.first) if not candidates: - return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."] - listed = [f" - item {item.id}, {levels(item)}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates] - return [f'- The items of release {release_name(first)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed] + return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."] + listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates] + return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed] def named_lines(named: list[NamedPath] | Failure) -> list[str]: @@ -104,9 +104,5 @@ def levels(item: Item) -> str: return f"L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}" -def release_name(item: Item) -> str: - return ".".join(map(str, item.release)) - - def counted(count: int, one: str, many: str) -> str: return f"{count} {one if count == 1 else many}" diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 248f2a26..83f82a4e 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -9,6 +9,11 @@ from todo_table import Item, item_details, items, next_item # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. Forge = typing.Literal["gh", "tea"] +# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields. +PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} +# How the plan's earliest release stands to the version x.y.z the newest tag names. "next": it is x.y.z+1, x.y+1.0 or x+1.0.0, or no tag names a version. "cut": it is x.y.z or earlier. +# Else the release after the tag holds no item: "finished" where commits followed the tag, "unplanned" where none did, and "unknown" where they cannot be counted. +Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] @dataclasses.dataclass(frozen=True) @@ -30,7 +35,7 @@ class Release: @dataclasses.dataclass(frozen=True) class Plan: - """The checkout's todo.md items, and first, the item the next chunk takes first.""" + """The default branch's todo.md items, and first, the item the next chunk takes first.""" items: list[Item] first: Item # first's tagline and detail. @@ -42,6 +47,12 @@ class Plan: return f"item-{self.first.id}" +@dataclasses.dataclass(frozen=True) +class NoItem: + """Why the plan names no item for the next chunk, as a sentence the worker reads.""" + why: str + + @dataclasses.dataclass(frozen=True) class Worktree: path: pathlib.Path @@ -77,48 +88,57 @@ class Gathered: default: str # Why origin reads as last fetched; None after a fetch. note: str | None - # Why the checkout was not fast-forwarded to default; None once it was. - kept_as_is: str | None release: Release - # The plan's first item and what was found or made for it; else why there is none. - item: ItemFacts | str + # What was found or made for the plan's first item; else why the plan names none. + item: ItemFacts | NoItem -def planned(todo: str | Failure) -> Plan | str: - """The checkout's plan and its first item, as todo_table.next_item picks it; else why there is none.""" +def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoItem: + """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.next_item's pick, where standing finds the plan's earliest release next; else why there is none.""" + where = f"{default}'s todo.md" if isinstance(todo, Failure): - return f"the checkout's todo.md cannot be read: {todo.reason}" + return NoItem(f"{where} cannot be read: {todo.reason}.") found = items(todo) if isinstance(found, Failure): - return f"the checkout's todo.md cannot be read: {found.reason}" - listed = found or [] - first = next_item(listed) + return NoItem(f"{where} cannot be read: {found.reason}.") + if found is None: + return NoItem(f"{where} holds no items table.") + earliest = min((item.release for item in found), default=None) + stands = standing(release, earliest) + if earliest is not None and stands == "cut": + return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {release.tag}.") + gap = f"{where} holds no item for the release after the last cut, {release.tag}, and" + if stands == "finished": + return NoItem(f"{gap} commits have landed since, so that release is finished and ready to cut, and the working loop stops here.") + if stands == "unplanned": + return NoItem(f"{gap} no commit has landed since, so that release is to be planned first.") + if stands == "unknown": + return NoItem(f"{gap} the commits since it cannot be counted.") + first = next_item(found) if first is None: - return "every item of the checkout's next release waits" if listed else "the checkout holds no todo.md items table" + return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.") details = item_details(todo) detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})" - return Plan(listed, first, f"{first.tagline}\n\n{detail}".strip()) + return Plan(found, first, f"{first.tagline}\n\n{detail}".strip()) -def held_back(default: str, head: str | Failure, status: str | Failure, behind: str | Failure) -> str | None: - """Why the checkout is not fast-forwarded to default, from its branch, its tracked changes and how many commits it is behind; None where nothing holds it back. +def standing(release: Release, earliest: tuple[int, int, int] | None) -> Standing: + """How the plan's earliest release, None where the plan holds no item, stands to the version the release's tag names, as Standing says.""" + cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", release.tag) if isinstance(release.tag, str) else None + if cut is None: + return "next" + major, minor, patch = (int(part) for part in cut.groups()) + if earliest in ((major, minor, patch + 1), (major, minor + 1, 0), (major + 1, 0, 0)): + return "next" + if earliest is not None and earliest <= (major, minor, patch): + return "cut" + if isinstance(release.commits, Failure): + return "unknown" + return "finished" if release.commits else "unplanned" - A dirty checkout is never fast-forwarded, as `~/.claude/CLAUDE.md` → "Working with the codebase" asks: its changes are for the human to see, never to carry along. - """ - branch = default.removeprefix("origin/") - if branch == default: - return "it has no origin remote" - if isinstance(head, Failure): - return "it is on no branch" - if head.strip() != branch: - return f"it is on {head.strip()}, not {branch}" - if isinstance(status, Failure): - return f"its status cannot be read: {status.reason}" - if status.strip(): - return "it holds uncommitted changes" - if isinstance(behind, Failure): - return f"how far it is behind {default} cannot be read: {behind.reason}" - return f"it is not behind {default}" if int(behind) == 0 else None + +def version(release: tuple[int, int, int]) -> str: + return ".".join(map(str, release)) def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: @@ -133,11 +153,11 @@ def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None: def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]: """The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default.""" if local: - return ["worktree", "add", "--quiet", str(path), branch], f"on the branch {branch}, which existed already." + return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already." if pushed: - return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"on the new branch {branch}, made off origin/{branch}." + return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}." # --no-track: tracking the default branch would point a bare `git push` at it. - return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"on the new branch {branch}, made off {default}." + return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}." def forge_of(origin_url: str) -> Forge: @@ -147,12 +167,12 @@ def forge_of(origin_url: str) -> Forge: def pulls_command(forge: Forge, branch: str) -> list[str]: """The command that lists open pull requests, by number, head and URL. gh lists only branch's; tea lists every one, for facts.open_pulls to pick branch's.""" if forge == "gh": - return ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] - return ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"] + return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] + return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"] def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]: """Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file.""" - spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text)) + spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text)) held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans) return [(span, count) for span, count in held if count] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index ca834673..d78042cd 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -5,14 +5,17 @@ usage: chunk-preflight Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that remote, and takes origin's default branch, or else the -local main or master, as larv-review does. It fast-forwards the checkout to that branch where the -checkout is on it, behind it and holds no uncommitted change; else it says why not. It then reads -the checkout's own todo.md, the file loop-claude routes on, and prints: +local main or master, as larv-review does. It leaves the checkout as it is: it reads todo.md as +that branch holds it, the plan loop-claude routes on, and prints: - the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how many commits followed the tag; -- the next release in todo.md, and that release's first item that does not wait, the item - loop-claude routes on, with its L and E + I; +- the earliest release in todo.md, and that release's first item that does not wait, the item + loop-claude routes on, with its L and E + I. It names that item only where the tag names no + version x.y.z, or the release is x.y.z+1, x.y+1.0 or x+1.0.0. For a later release, or a todo.md + that holds no item, it says the release after the tag holds none: finished and ready to cut where + commits followed the tag, and else to be planned first. For x.y.z or an earlier release, it says + todo.md files items under a release already cut; - the item's worktree: a sibling of the checkout named -item-, on the branch item-. It continues a worktree already on that branch; else it adds one on the local branch, else on a new branch tracking origin's, else on a new branch off the default branch; @@ -27,84 +30,97 @@ the checkout's own todo.md, the file loop-claude routes on, and prints: `larv-review places` print in the worktree, each with its exit code. reading-cost appends to the worktree's docs/reading-cost.md, for the chunk to commit. -A fact it cannot find it says it cannot, and why, and goes on. A tool or forge CLI still running -after TIMEOUT seconds is stopped. With no item, it makes no worktree and runs none of those four -tools. +A fact it cannot find it says it cannot, and why, and goes on. A fetch, forge CLI or tool still +running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT sets, is stopped; a +stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of +those four tools. -Exit 1, saying why, on any argument, or when git cannot start or finds no checkout. +Exit 1, saying why, on any argument, on a CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds +above 0, or when git cannot start or finds no checkout or no default branch. """ import pathlib +import re import subprocess import sys +import typing -from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top +from git_repo import commit_exists, commits_since, default_branch, default_branch_todo, file_at, git, newest_release_tag, top from failure import Failure -from chunk_preflight.gathered import Forge, forge_of, Gathered, held_back, ItemFacts, named_paths, NamedPath, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on +from chunk_preflight.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on from chunk_preflight.facts import render BIN = pathlib.Path(__file__).resolve().parents[1] # Each tool run in the item's worktree, {item} standing for the item's ID. TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places")) -# Seconds before a tool or forge CLI is stopped, so a hung one leaves the facts the others find. +# Seconds before a fetch, forge CLI or tool is stopped, so a hung one leaves the facts the others find; TIMEOUT_SETTING sets others. TIMEOUT = 60 +TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT" -def main(argv: list[str]) -> int: +def main(argv: list[str], env: typing.Mapping[str, str]) -> int: if argv in (["-h"], ["--help"]): - print(__doc__.strip()) + print(__doc__.strip().format(timeout=TIMEOUT)) return 0 if argv: print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr) return 1 - root = top() - if isinstance(root, Failure): - print(root.reason, file=sys.stderr) + printed = run(env.get(TIMEOUT_SETTING)) + if isinstance(printed, Failure): + print(printed.reason, file=sys.stderr) return 1 - print("\n".join(preflight(pathlib.Path(root)))) + print("\n".join(printed)) return 0 -def preflight(root: pathlib.Path) -> list[str]: - """Gathers the facts step by step, each step taking what the ones before it found, and renders them.""" - default = default_branch(stale_ok=True) +def run(setting: str | None) -> list[str] | Failure: + """The preflight's lines, given what TIMEOUT_SETTING holds; a Failure where that is no number of seconds, or git finds no checkout or no default branch.""" + timeout = seconds(setting) + if isinstance(timeout, Failure): + return timeout + root = top() + return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout) + + +def seconds(setting: str | None) -> float | Failure: + """The seconds a TIMEOUT_SETTING of setting gives, TIMEOUT where it is unset; a Failure where it is no number above 0.""" + if setting is None: + return TIMEOUT + if re.fullmatch(r"[0-9]+(\.[0-9]+)?", setting) and float(setting) > 0: + return float(setting) + return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0") + + +def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure: + """Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch.""" + default = default_branch(stale_ok=True, timeout=timeout) if isinstance(default, Failure): - return [f"- No default branch: {default.reason}"] + return default ref, note = default - # First, so the plan read next is the fast-forwarded checkout's. - kept_as_is = fast_forward(ref) - plan = planned(text_of(root / "todo.md")) - item = plan if isinstance(plan, str) else item_facts(root, ref, plan) - return render(Gathered(ref, note, kept_as_is, release(ref), item)) + cut = release(ref, root) + plan = planned(default_branch_todo(str(root), timeout), cut, ref) + item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout) + return render(Gathered(ref, note, cut, item)) -def fast_forward(default: str) -> str | None: - """Fast-forwards the checkout to default unless held_back says why not; None once it has.""" - held = held_back(default, git("symbolic-ref", "--quiet", "--short", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("rev-list", "--count", f"HEAD..{default}")) - if held is not None: - return held - merged = git("merge", "--ff-only", "--quiet", default) - return merged.reason if isinstance(merged, Failure) else None - - -def release(default: str) -> Release: +def release(default: str, root: pathlib.Path) -> Release: tag = newest_release_tag(default) - commits = git("rev-list", "--count", f"{tag}..{default}" if isinstance(tag, str) else default) - return Release(tag, file_at(default, "CHANGELOG.md"), commits if isinstance(commits, Failure) else int(commits)) + commits = tag if isinstance(tag, Failure) else commits_since(tag, default) + return Release(tag, file_at(default, "CHANGELOG.md", str(root)), commits) -def item_facts(root: pathlib.Path, default: str, plan: Plan) -> ItemFacts: +def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> ItemFacts: worktree = item_worktree(root, plan.branch, default) - made = worktree.path if isinstance(worktree, Worktree) else None - return ItemFacts(plan, worktree, pull_listing(root, plan.branch), named_files(plan.text, made or root), tools_run(plan.first.id, made) if made else []) + path = worktree.path if isinstance(worktree, Worktree) else None + return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else []) def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | Failure: """The worktree on branch, made where none is; a Failure where git cannot make it, or its path holds something else.""" - held = git("worktree", "list", "--porcelain") - if isinstance(held, Failure): - return held - if (path := worktree_on(held, branch)) is not None: - return Worktree(path, f"on the branch {branch}, which it already held.") + listing = git("worktree", "list", "--porcelain") + if isinstance(listing, Failure): + return listing + if (path := worktree_on(listing, branch)) is not None: + return Worktree(path, f"continued, on the branch {branch}.") path = root.parent / f"{root.name}-{branch}" if path.exists(): return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}") @@ -113,12 +129,12 @@ def item_worktree(root: pathlib.Path, branch: str, default: str) -> Worktree | F return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else Worktree(path, how) -def pull_listing(root: pathlib.Path, branch: str) -> tuple[Forge, Ran | Failure] | None: +def pull_listing(root: pathlib.Path, branch: str, timeout: float) -> tuple[Forge, Ran | Failure] | None: url = git("remote", "get-url", "origin") if isinstance(url, Failure): return None forge = forge_of(url) - return forge, ran(pulls_command(forge, branch), root) + return forge, ran(pulls_command(forge, branch), root, timeout) def named_files(text: str, base: pathlib.Path) -> list[NamedPath] | Failure: @@ -132,28 +148,20 @@ def line_count(path: pathlib.Path) -> int | Failure | None: """A file's lines, or why they cannot be read; None for a folder.""" if not path.is_file(): return None - text = text_of(path) - return text if isinstance(text, Failure) else len(text.splitlines()) - - -def tools_run(item_id: int, worktree: pathlib.Path) -> list[tuple[str, Ran | Failure]]: - commands = [[part.format(item=item_id) for part in tool] for tool in TOOLS] - return [(" ".join(command), ran([sys.executable, str(BIN / command[0]), *command[1:]], worktree)) for command in commands] - - -def text_of(path: pathlib.Path) -> str | Failure: - """A file's text; empty where there is no such file.""" try: - return path.read_text(encoding="utf-8") - except FileNotFoundError: - return "" + return len(path.read_text(encoding="utf-8").splitlines()) except (OSError, UnicodeDecodeError) as failure: return Failure(str(failure)) -def ran(command: list[str], cwd: pathlib.Path) -> Ran | Failure: +def tools_run(item_id: int, worktree: pathlib.Path, timeout: float) -> list[tuple[str, Ran | Failure]]: + commands = [[part.format(item=item_id) for part in tool] for tool in TOOLS] + return [(" ".join(command), ran([sys.executable, str(BIN / command[0]), *command[1:]], worktree, timeout)) for command in commands] + + +def ran(command: list[str], cwd: pathlib.Path, timeout: float) -> Ran | Failure: try: - done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT) + done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout) except (OSError, subprocess.TimeoutExpired) as failure: return Failure(f"could not finish: {failure}") return Ran(done.returncode, done.stdout, done.stderr) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index d0e1a755..c515ccdb 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -9,8 +9,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from chunk_preflight.gathered import forge_of, Gathered, held_back, ItemFacts, NamedPath, planned, Ran, Release, Worktree, worktree_add +from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Release, standing, Worktree, worktree_add from test_env import isolated_env +from chunk_preflight.main import line_count, ran, seconds, TIMEOUT from chunk_preflight.facts import open_pulls, render, unreleased_entries BIN = pathlib.Path(__file__).resolve().parents[1] @@ -44,26 +45,40 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`. """ # The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files. SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.") +# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left. +LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n" +# An items table that holds no row. +EMPTY = TODO[:TODO.index("| 5 |")] CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" +# What the preflight reads of the last release: tag v0.1.0, two entries under ## Unreleased, and 4 commits since the tag. +CUT = Release("v0.1.0", CHANGELOG, 4) # Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1. FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n" +# Item 3's open pull request, as `gh pr list` prints it through the preflight's template; any other arguments exit 1. +FAKE_GH = """#!PYTHON +import sys +if sys.argv[1:] != ["pr", "list", "--head", "item-3", "--json", "number,url", "--template", "{{range .}}{{.number}}\\t{{.url}}\\n{{end}}"]: + sys.exit(1) +print("12\\thttps://github.com/o/r/pull/12") +""".replace("PYTHON", sys.executable) class Repo: - """An origin with a tagged release, a clone of it at /proj, and a fake tea on PATH.""" + """An origin with a tagged release, a clone of it at /proj, and a fake tea and gh on PATH.""" - def __init__(self, test, todo=TODO): + def __init__(self, test, todo=TODO, origin="origin.git"): temp = tempfile.TemporaryDirectory() test.addCleanup(temp.cleanup) self.temp = pathlib.Path(os.path.realpath(temp.name)) - self.origin = self.temp / "origin.git" + self.origin = self.temp / origin self.root = self.temp / "proj" - fake = self.temp / "fake-bin" - fake.mkdir() - (fake / "tea").write_text(FAKE_TEA) - (fake / "tea").chmod(0o755) - (fake / "git").symlink_to(shutil.which("git")) - self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")} + self.fake = self.temp / "fake-bin" + self.fake.mkdir() + for name, script in (("gh", FAKE_GH), ("tea", FAKE_TEA)): + (self.fake / name).write_text(script) + (self.fake / name).chmod(0o755) + (self.fake / "git").symlink_to(shutil.which("git")) + self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")} self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin)) self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root)) self.write(self.root, "README.md", README) @@ -95,24 +110,34 @@ class Repo: self.commit(other, "elsewhere") self.git(other, "push", "--quiet", "origin", "main") - def preflight(self): - return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env=self.env, text=True, timeout=120) + def stub_git(self, arm): + """Puts a git on PATH that runs arm, a shell case arm, on its arguments, and the real git on any others.""" + stub = self.fake / "git" + stub.unlink() + stub.write_text(f'#!/bin/sh\ncase "$*" in\n{arm}\nesac\nexec {shutil.which("git")} "$@"\n') + stub.chmod(0o755) + + def preflight(self, **env): + return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120) class ChunkPreflightTool(unittest.TestCase): - def test_fast_forwards_the_checkout_reads_its_plan_and_makes_the_items_worktree_off_the_fetched_default_branch(self): + def test_reads_the_fetched_default_branchs_plan_and_makes_the_items_worktree_off_it_leaving_the_checkout_as_it_was(self): repo = Repo(self) repo.push_from_elsewhere("todo.md", SHIPPED) + # Claude Code rewrites tracked files, such as settings.json, so a checkout behind origin often holds changes. + repo.write(repo.root, "todo.md", TODO + "\nA change of the checkout's own.\n") + head = repo.git(repo.root, "rev-parse", "HEAD") done = repo.preflight() self.assertEqual(done.returncode, 0, done.stderr) - self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main")) + self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), head) worktree = repo.temp / "proj-item-7" self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-7") self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main")) for fact in ( - "fast-forwarded to origin/main", "item 7, L 1, E + I 2", - f"{worktree}, on the new branch item-7, made off origin/main.", + str(worktree), + "item-7, made off origin/main", "#12 https://forge/pulls/12", "`src/app.py`: 3 lines", "`src`: 1 file", @@ -120,9 +145,10 @@ class ChunkPreflightTool(unittest.TestCase): "`larv-review needs-scoring-run 7` exited 0", "`reading-cost` exited 0", "`larv-review places` exited 0", - f"to {worktree}/docs/reading-cost.md", + f"{worktree}/docs/reading-cost.md", ): - self.assertIn(fact, done.stdout) + with self.subTest(fact=fact): + self.assertIn(fact, done.stdout) self.assertNotIn("#13", done.stdout) self.assertNotIn("`gone.py`:", done.stdout) @@ -130,31 +156,87 @@ class ChunkPreflightTool(unittest.TestCase): repo = Repo(self) repo.preflight() worktree = repo.temp / "proj-item-3" - self.assertIn(f"Worktree: {worktree}, on the branch item-3, which it already held.", repo.preflight().stdout) + continued = repo.preflight().stdout + self.assertIn(str(worktree), continued) + self.assertIn("continued", continued) (worktree / "work.txt").write_text("work\n") repo.git(worktree, "add", "work.txt") repo.git(worktree, "commit", "--quiet", "-m", "work") repo.git(worktree, "push", "--quiet", "origin", "item-3") repo.git(repo.root, "worktree", "remove", "--force", str(worktree)) repo.git(repo.root, "branch", "--quiet", "-D", "item-3") - self.assertIn(f"Worktree: {worktree}, on the new branch item-3, made off origin/item-3.", repo.preflight().stdout) + pushed = repo.preflight().stdout + self.assertIn(str(worktree), pushed) + self.assertIn("made off origin/item-3", pushed) self.assertTrue((worktree / "work.txt").exists()) def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self): repo = Repo(self) (repo.temp / "proj-item-3").mkdir() done = repo.preflight() - self.assertIn(f"Worktree: none made, since {repo.temp / 'proj-item-3'} exists", done.stdout) + self.assertIn(f"none made, since {repo.temp / 'proj-item-3'} exists", done.stdout) self.assertNotIn("`reading-cost`", done.stdout) + def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_add_it(self): + repo = Repo(self) + repo.temp.chmod(0o555) + self.addCleanup(repo.temp.chmod, 0o755) + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("Worktree: none made: git worktree add", done.stdout) + self.assertNotIn("`reading-cost`", done.stdout) + self.assertFalse((repo.temp / "proj-item-3").exists()) + + def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_list_the_worktrees(self): + repo = Repo(self) + repo.stub_git('"worktree list --porcelain") echo "listing broke" >&2; exit 1;;') + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("listing broke", done.stdout) + self.assertNotIn("`reading-cost`", done.stdout) + self.assertFalse((repo.temp / "proj-item-3").exists()) + + def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self): + repo = Repo(self) + repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;') + done = repo.preflight(CHUNK_PREFLIGHT_TIMEOUT="1") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("as last fetched", done.stdout) + self.assertIn("item 3, L 4, E + I 5", done.stdout) + self.assertIn("`reading-cost` exited 0", done.stdout) + + def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self): + repo = Repo(self, origin="github.com/o/r.git") + self.assertIn("#12 https://github.com/o/r/pull/12", repo.preflight().stdout) + def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self): repo = Repo(self, todo="") done = repo.preflight() self.assertEqual(done.returncode, 0, done.stderr) - self.assertIn("Last version cut: v0.1.0.", done.stdout) - self.assertIn("No plan item: the checkout holds no todo.md items table, so no worktree was made.", done.stdout) + self.assertIn("v0.1.0", done.stdout) + self.assertIn("no items table", done.stdout) self.assertFalse((repo.temp / "proj-item-3").exists()) + def test_states_its_timeout_in_its_help(self): + done = subprocess.run([sys.executable, str(BIN / "chunk-preflight"), "--help"], capture_output=True, env=isolated_env(), text=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn(f"after {TIMEOUT} seconds", done.stdout) + + def test_exits_1_on_a_timeout_setting_that_is_no_number_of_seconds(self): + done = Repo(self).preflight(CHUNK_PREFLIGHT_TIMEOUT="soon") + self.assertEqual(done.returncode, 1) + self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", done.stderr) + self.assertEqual(done.stdout, "") + + def test_exits_1_without_a_default_branch(self): + with tempfile.TemporaryDirectory() as temp: + env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} + subprocess.run(["git", "init", "--quiet", "--initial-branch=trunk", temp], check=True, env=env) + done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env=env, text=True) + self.assertEqual(done.returncode, 1) + self.assertIn("main or master", done.stderr) + self.assertEqual(done.stdout, "") + def test_exits_1_outside_a_checkout(self): with tempfile.TemporaryDirectory() as temp: done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True) @@ -162,52 +244,98 @@ class ChunkPreflightTool(unittest.TestCase): self.assertIn("git rev-parse --show-toplevel", done.stderr) -def item_facts(**fields): - """Item 3's facts, its worktree made, with fields given replacing the rest.""" - plan = planned(TODO) - return ItemFacts(**{"plan": plan, "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields}) +def item_facts(todo=TODO, **fields): + """The facts of todo's next item, its worktree made, with fields given replacing the rest.""" + return ItemFacts(**{"plan": planned(todo, CUT, "origin/main"), "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "added on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields}) -def rendered(item, release=Release("v0.1.0", CHANGELOG, 4), kept_as_is=None): - return "\n".join(render(Gathered("origin/main", None, kept_as_is, release, item))) +def rendered(item, release=CUT, note=None): + return "\n".join(render(Gathered("origin/main", note, release, item))) class Render(unittest.TestCase): - def test_states_the_next_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self): + def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self): said = rendered(item_facts()) - self.assertIn("0.2.0", said) + self.assertIn("origin/main's todo.md: 0.2.0", said) self.assertIn("item 3, L 4, E + I 5", said) self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said) self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said) self.assertNotIn("item 8,", said) - def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self): - self.assertIn("v0.1.0. Unreleased: 2 entries", rendered("no item")) - self.assertIn("v0.1.0. Unreleased: 4 commits since v0.1.0", rendered("no item", Release("v0.1.0", "# Changelog\n", 4))) - self.assertIn("none. Unreleased: 1 commit on origin/main", rendered("no item", Release(None, "", 1))) + def test_states_the_items_worktree_or_why_none_was_made(self): + self.assertIn("/c/proj-item-3", rendered(item_facts())) + self.assertIn("none made: path taken", rendered(item_facts(worktree=Failure("none made: path taken")))) - def test_states_whether_the_checkout_was_fast_forwarded_and_why_there_is_no_plan_item(self): - self.assertIn("The checkout was fast-forwarded to origin/main.", rendered("every item waits")) - said = rendered("every item waits", kept_as_is="it holds uncommitted changes") - self.assertIn("The checkout was not fast-forwarded: it holds uncommitted changes", said) - self.assertIn("No plan item: every item waits, so no worktree was made.", said) + def test_states_that_no_other_item_may_join_the_chunk(self): + said = rendered(item_facts(TODO.replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | 5 |"))) + self.assertIn("No other item", said) + self.assertNotIn("item 7,", said) + + def test_states_an_unscored_level_as_unscored(self): + unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 4 | 2 | 3 | 7 | 3 |", "| 7 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |") + self.assertIn("item 3, L unscored, E + I unscored", rendered(item_facts(unscored))) + + def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self): + self.assertIn("v0.1.0. Unreleased: 2 entries", rendered(NoItem("x."))) + self.assertIn("1 entry", rendered(NoItem("x."), Release("v0.1.0", "## Unreleased\n\n- One.\n", 4))) + without = rendered(NoItem("x."), Release("v0.1.0", "# Changelog\n", 4)) + self.assertIn("4 commits since v0.1.0", without) + self.assertIn("no ## Unreleased", without) + untagged = rendered(NoItem("x."), Release(None, "", 1)) + self.assertIn("cut: none", untagged) + self.assertIn("1 commit on origin/main", untagged) + + def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self): + said = rendered(NoItem("x."), Release("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"))) + self.assertIn("changelog unreadable", said) + self.assertIn("cannot be counted: count unreadable", said) + self.assertNotIn("no ## Unreleased", said) + + def test_states_why_origin_reads_as_last_fetched_and_nothing_after_a_fetch(self): + self.assertIn("- reading origin as last fetched: fetch stalled", rendered(NoItem("x."), note="reading origin as last fetched: fetch stalled")) + fetched = rendered(NoItem("x.")) + self.assertNotIn("last fetched", fetched) + self.assertNotIn("None", fetched) + + def test_states_why_there_is_no_plan_item(self): + said = rendered(NoItem("every item waits.")) + self.assertIn("every item waits.", said) + self.assertNotIn("Worktree", said) def test_states_the_open_pull_requests_from_the_items_branch_or_why_none_are_listed(self): - self.assertIn("Open pull requests from item-3: #12 https://forge/pulls/12\n", rendered(item_facts(pulls=("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", ""))))) - self.assertIn("Open pull requests from item-3: none.", rendered(item_facts(pulls=("gh", Ran(0, "", ""))))) - self.assertIn("Open pull requests from item-3: none, as the checkout has no origin remote.", rendered(item_facts())) - self.assertIn("Open pull requests from item-3: cannot be listed: `tea pulls list` exited 1: no login", rendered(item_facts(pulls=("tea", Ran(1, "", "no login\n"))))) + cases = ( + (("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", "")), ("#12 https://forge/pulls/12",)), + (("gh", Ran(0, "12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "")), ("#12 https://github.com/o/r/pull/12, #14 https://github.com/o/r/pull/14",)), + (("gh", Ran(0, "", "")), ("item-3: none.",)), + (None, ("item-3: none", "no origin remote")), + (("tea", Ran(1, "", "no login\n")), ("`tea pulls list`", "exited 1", "no login")), + (("gh", Ran(1, "", "not logged in\n")), ("`gh pr list`", "exited 1", "not logged in")), + (("gh", Failure("could not finish: timed out")), ("`gh pr list`", "could not finish: timed out")), + ) + for pulls, facts in cases: + with self.subTest(pulls=pulls): + said = rendered(item_facts(pulls=pulls)) + for fact in facts: + self.assertIn(fact, said) def test_states_each_named_files_lines_and_each_named_folders_files(self): - said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8"))])) + said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8")), NamedPath("one.py", 1, 1), NamedPath("docs", 1, None)])) self.assertIn("`src/app.py`: 3 lines", said) self.assertIn("`src`: 2 files", said) self.assertIn("`bad.py`: cannot be read: not UTF-8", said) + self.assertIn("`one.py`: 1 line\n", said) + self.assertIn("`docs`: 1 file\n", said) + + def test_states_that_the_item_names_no_tracked_file_or_why_they_cannot_be_listed(self): + self.assertIn("no file", rendered(item_facts(named=[]))) + self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke")))) def test_states_what_each_tool_printed_and_its_exit_code(self): - said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review places", Failure("could not finish: timed out"))])) - self.assertIn("`rank_todo.py --check todo.md` exited 0, printing:\n\n> ranked", said) - self.assertIn("`reading-cost` exited 1, printing nothing.", said) + said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))])) + self.assertIn("`rank_todo.py --check todo.md` exited 0", said) + self.assertIn("> ranked", said) + self.assertIn("`reading-cost` exited 1, printing nothing", said) + self.assertIn("> out\n> err", said) self.assertIn("`larv-review places` could not finish: timed out", said) @@ -217,18 +345,88 @@ class OpenPulls(unittest.TestCase): self.assertEqual(open_pulls("index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n13\tother\thttps://forge/pulls/13\n", "tea", "item-3"), ["#12 https://forge/pulls/12"]) +class Plans(unittest.TestCase): + def test_picks_the_earliest_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self): + self.assertEqual(planned(TODO, CUT, "origin/main").first.id, 3) + waits = planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |"), CUT, "origin/main") + self.assertIn("waits", waits.why) + self.assertIn("0.2.0", waits.why) + self.assertIn("Permission denied", planned(Failure("Permission denied"), CUT, "origin/main").why) + self.assertIn("L 'x'", planned(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), CUT, "origin/main").why) + self.assertIn("details cannot be read", planned(TODO + "```\n", CUT, "origin/main").text) + + def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self): + without = planned("", CUT, "origin/main").why + self.assertIn("origin/main", without) + self.assertIn("no items table", without) + empty = planned(EMPTY, Release(None, "", 4), "origin/main").why + self.assertIn("holds no item", empty) + self.assertNotIn("no items table", empty) + + def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self): + cases = ( + (LATER, 4, "finished and ready to cut"), + (LATER, 0, "planned first"), + (EMPTY, 4, "finished and ready to cut"), + (EMPTY, 0, "planned first"), + (LATER, Failure("count unreadable"), "cannot be counted"), + ) + for todo, commits, fact in cases: + with self.subTest(todo=todo, commits=commits): + why = planned(todo, Release("v0.1.0", "", commits), "origin/main").why + self.assertIn(fact, why) + self.assertIn("v0.1.0", why) + + def test_says_the_plan_files_items_under_a_release_already_cut(self): + why = planned(TODO, Release("v0.2.0", "", 4), "origin/main").why + self.assertIn("release 0.2.0", why) + self.assertIn("v0.2.0", why) + self.assertIn("not after", why) + + def test_takes_an_item_without_a_detail_as_its_tagline_alone(self): + self.assertEqual(planned(TODO[:TODO.index("## Details")], CUT, "origin/main").text, "**Do the next thing.**") + + +class Standing(unittest.TestCase): + def test_takes_the_earliest_release_where_it_is_the_next_patch_minor_or_major_or_no_tag_names_a_version(self): + cases = ( + (Release("v1.2.3", "", 4), (1, 2, 4), "next"), + (Release("v1.2.3", "", 4), (1, 3, 0), "next"), + (Release("v1.2.3", "", 4), (2, 0, 0), "next"), + (Release(None, "", 4), (0, 2, 0), "next"), + (Release(None, "", 4), None, "next"), + (Release("v1.2.3-rc.1", "", 4), (1, 2, 3), "next"), + (Release(Failure("tags unreadable"), "", 4), (0, 2, 0), "next"), + (Release("v1.2.3", "", 4), (1, 2, 3), "cut"), + (Release("v1.2.3", "", 4), (1, 2, 2), "cut"), + (Release("v1.2.3", "", 4), (1, 2, 5), "finished"), + (Release("v1.2.3", "", 4), (1, 3, 1), "finished"), + (Release("v1.2.3", "", 4), (2, 0, 1), "finished"), + (Release("v1.2.3", "", 4), None, "finished"), + (Release("v1.2.3", "", 0), (1, 4, 0), "unplanned"), + (Release("v1.2.3", "", 0), None, "unplanned"), + (Release("v1.2.3", "", Failure("count unreadable")), (1, 4, 0), "unknown"), + ) + for release, earliest, stands in cases: + with self.subTest(release=release, earliest=earliest): + self.assertEqual(standing(release, earliest), stands) + + class Gathering(unittest.TestCase): def test_counts_the_top_level_entries_under_unreleased(self): self.assertEqual(unreleased_entries(CHANGELOG), 2) self.assertEqual(unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0) self.assertIsNone(unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n")) - def test_picks_the_next_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self): - self.assertEqual(planned(TODO).first.id, 3) - self.assertEqual(planned(""), "the checkout holds no todo.md items table") - self.assertEqual(planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |")), "every item of the checkout's next release waits") - self.assertEqual(planned(Failure("Permission denied")), "the checkout's todo.md cannot be read: Permission denied") - self.assertIn("todo.md's details cannot be read", planned(TODO + "```\n").text) + def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self): + cases = ( + ("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]), + ("`src/`", ["src/app.py", "src/b.py"], [("src", 2)]), + ("`src/app.py`, `gone.py` and `run`", ["src/app.py"], [("src/app.py", 1)]), + ) + for text, tracked, named in cases: + with self.subTest(text=text): + self.assertEqual(named_paths(text, tracked), named) def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self): path = pathlib.Path("/c/proj-item-3") @@ -240,19 +438,35 @@ class Gathering(unittest.TestCase): self.assertEqual(forge_of("git@github.com:o/r.git"), "gh") self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea") - def test_fast_forwards_only_a_clean_checkout_on_the_default_branch_that_is_behind_it(self): - cases = ( - (("main", "main\n", "", "2\n"), "it has no origin remote"), - (("origin/main", Failure(""), "", "2\n"), "it is on no branch"), - (("origin/main", "item-5\n", "", "2\n"), "it is on item-5, not main"), - (("origin/main", "main\n", " M todo.md\n", "2\n"), "it holds uncommitted changes"), - (("origin/main", "main\n", "", "0\n"), "it is not behind origin/main"), - (("origin/main", "main\n", Failure("git status: broken"), "2\n"), "its status cannot be read: git status: broken"), - (("origin/main", "main\n", "", "2\n"), None), - ) - for found, why in cases: - with self.subTest(found=found): - self.assertEqual(held_back(*found), why) + def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self): + self.assertEqual(seconds(None), TIMEOUT) + self.assertEqual(seconds("2.5"), 2.5) + for setting in ("soon", "0", "-1", "1e3", ""): + with self.subTest(setting=setting): + self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", seconds(setting).reason) + + +class Running(unittest.TestCase): + def test_says_why_a_command_could_not_finish(self): + with tempfile.TemporaryDirectory() as cwd: + cases = (([str(pathlib.Path(cwd, "missing"))], 60, "missing"), ([sys.executable, "-c", "import time; time.sleep(5)"], 0.2, "0.2")) + for command, timeout, fact in cases: + with self.subTest(fact=fact): + done = ran(command, pathlib.Path(cwd), timeout) + self.assertIsInstance(done, Failure) + self.assertIn(fact, done.reason) + + def test_counts_a_files_lines_says_why_they_cannot_be_read_and_counts_none_for_a_folder(self): + with tempfile.TemporaryDirectory() as temp: + folder = pathlib.Path(temp) + (folder / "two.txt").write_text("a\nb\n") + (folder / "latin.txt").write_bytes(b"caf\xe9\n") + (folder / "locked.txt").write_text("a\n") + (folder / "locked.txt").chmod(0) + self.assertEqual(line_count(folder / "two.txt"), 2) + self.assertIn("utf-8", line_count(folder / "latin.txt").reason) + self.assertIn("locked.txt", line_count(folder / "locked.txt").reason) + self.assertIsNone(line_count(folder)) if __name__ == "__main__": diff --git a/bin/git_repo.py b/bin/git_repo.py index a84eaf22..20bee97c 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -1,15 +1,20 @@ -"""Run git in the current directory, and read the checkout, its default branch and its files.""" +"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.""" import re import subprocess from failure import Failure -def git(*args: str) -> str | Failure: +def git(*args: str, cwd: str | None = None, timeout: float | None = None) -> str | Failure: + """What git printed, run in cwd, else in the current directory. A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.""" try: - ran = subprocess.run(["git", *args], capture_output=True, text=True) + ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", timeout=timeout) + except UnicodeDecodeError as failure: + return Failure(f"git {' '.join(args)} printed text that is not UTF-8: {failure}") except (OSError, ValueError) as failure: return Failure(f"git could not start: {failure}") + except subprocess.TimeoutExpired: + return Failure(f"git {' '.join(args)}: stopped after {timeout} s") return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") @@ -18,28 +23,36 @@ def top() -> str | Failure: return found if isinstance(found, Failure) else found.strip() -def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure: - """The default branch's ref, `origin/` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so.""" +def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, str | None] | Failure: + """The default branch's ref, as default_ref names it after a fetch where the checkout has an origin remote, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so. A call to origin still running after timeout seconds fails.""" remotes = git("remote") + if isinstance(remotes, Failure): + return remotes + fetch = git("fetch", "--quiet", "origin", timeout=timeout) if "origin" in remotes.split() else "" + if isinstance(fetch, Failure) and not stale_ok: + return fetch + ref = default_ref(timeout=timeout) + note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None + return ref if isinstance(ref, Failure) else (ref, note) + + +def default_ref(cwd: str | None = None, timeout: float | None = None) -> str | Failure: + """The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/` with that remote, else the local main or master. Asking origin, where the checkout records no default branch for it, fails after timeout seconds.""" + remotes = git("remote", cwd=cwd) if isinstance(remotes, Failure): return remotes if "origin" in remotes.split(): - fetch = git("fetch", "--quiet", "origin") - if isinstance(fetch, Failure) and not stale_ok: - return fetch - note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None - default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") - named = default.strip() if not isinstance(default, Failure) else origin_head() - return named if isinstance(named, Failure) else (named, note) + recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd) + return recorded.strip() if not isinstance(recorded, Failure) else origin_head(cwd, timeout) for branch in ("main", "master"): - if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): - return branch, None + if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd), Failure): + return branch return Failure("no origin remote, and no main or master branch to take as the default branch") -def origin_head() -> str | Failure: +def origin_head(cwd: str | None, timeout: float | None) -> str | Failure: """The default branch origin names, for a clone made by `git init` and `git remote add`, which records none.""" - listed = git("ls-remote", "--symref", "origin", "HEAD") + listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout) if isinstance(listed, Failure): return listed if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed): @@ -47,6 +60,12 @@ def origin_head() -> str | Failure: return Failure("origin names no default branch; set it with `git remote set-head origin --auto`") +def default_branch_todo(root: str, timeout: float) -> str | Failure: + """todo.md on the default branch as last fetched, read in the checkout at root; empty where that branch holds none. Asking origin, where the checkout records no default branch for it, fails after timeout seconds.""" + ref = default_ref(root, timeout) + return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", root) + + def newest_release_tag(branch: str) -> str | None | Failure: """The newest `v*` tag merged into branch, None when it has none.""" # Sorts v1.0.0-rc.1 below v1.0.0. @@ -54,18 +73,24 @@ def newest_release_tag(branch: str) -> str | None | Failure: return tags if isinstance(tags, Failure) else next(iter(tags.split()), None) -def commit_exists(commit: str) -> bool: - return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure) +def commits_since(tag: str | None, branch: str) -> int | Failure: + """How many commits branch holds after tag, or holds in all where tag is None.""" + count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch) + return count if isinstance(count, Failure) else int(count) -def file_at(revision: str, path: str) -> str | Failure: - """A file's text at a revision, empty where the revision is not a commit, such as a root commit's parent, or holds no such file.""" - if not commit_exists(revision): +def commit_exists(commit: str, cwd: str | None = None) -> bool: + return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure) + + +def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure: + """A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file.""" + if not commit_exists(revision, cwd): return "" - listed = git("ls-tree", "--name-only", revision, "--", path) + listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd) if isinstance(listed, Failure): return listed - return git("show", f"{revision}:{path}") if listed.strip() else "" + return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else "" def full_history() -> Failure | None: diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index b9c8f839..7053047c 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,5 +1,5 @@ +from git_repo import commits_since, file_at, full_history, git, newest_release_tag from failure import Failure -from git_repo import file_at, full_history, git, newest_release_tag from comprehension_history import HISTORY, HistoryChange @@ -27,5 +27,5 @@ def landed_since_release(default: str) -> bool | Failure: newest = newest_release_tag(default) if isinstance(newest, Failure): return newest - count = git("rev-list", "--count", f"{newest}..{default}" if newest else default) - return count if isinstance(count, Failure) else int(count) > 0 + count = commits_since(newest, default) + return count if isinstance(count, Failure) else count > 0 diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index f130248a..b40bb8ba 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -17,7 +17,7 @@ def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: st """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip() routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "") - return f"{task}\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" + return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}" def routed_by(route: Route, anchor: Rung | None) -> str: @@ -35,8 +35,8 @@ def preflight_facts(printed: str) -> str: def preflight_failed(reason: str) -> str: - """Has the worker find the facts chunk-preflight would have, its worktree and open pull request among them.""" - return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Continue any open draft PR or worktree for the chunk before creating a new one. Why it could not run: {reason}" + """Has the worker find the facts chunk-preflight would have, its worktree among them.""" + return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}" def review_launches(route: Route, anchor: Rung | None) -> str: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 215980c1..760444e9 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -62,9 +62,11 @@ def system_effects() -> Effects: def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]: - """Runs a Python script in cwd. One still running after timeout seconds is stopped, and reads as exit 1, saying so on stderr.""" + """Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr.""" command = [sys.executable, *args] try: - return subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=timeout) + return subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout) + except OSError as failure: + return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}") except subprocess.TimeoutExpired: return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index db2aadd9..25d0b542 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -6,11 +6,12 @@ Run it anywhere inside a project checkout whose README.md has ## Goals and ## Au premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md items, or else the task, and never widen them. As a chunk starts, before it is routed, loop-claude -runs bin/chunk-preflight (bin/chunk_preflight/), which fast-forwards the checkout and finds the -chunk's facts; chunk-preflight --help lists them, and prompts.preflight_facts in -bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A judge then reads the -transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, -and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and +runs bin/chunk-preflight (bin/chunk_preflight/), which finds the chunk's facts and makes its +worktree; chunk-preflight --help lists them, and prompts.preflight_facts in +bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A preflight that fails, or is +still running after 600 s and is stopped, leaves the worker to find the facts itself. A judge then +reads the transcript's end, the premises, and the records: the project's AGENTS.md and +docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker @@ -48,13 +49,13 @@ run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_ for the worker and the interrupt; with both set, nothing is asked. Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the -interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, the checkout's -todo.md, read once chunk-preflight has run, routes it, so routing and the preflight's facts name one -item: the next release's top item that does not wait. An item waits while it is marked question, -or while an item that blocks it is still in the table. The item's L picks the worker's rung, -stepping from the model's cheapest rung by WORKER_STEPS in bin/model_routing/ladder.py, below it -for a low L; without such an item, or with its L, E or I unscored, the chunk runs on the model's -cheapest rung. The +interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, todo.md on the +default branch, as chunk-preflight has just fetched it, routes it: its earliest release's top item +that does not wait, the item the preflight states where that release is the next. An item waits +while it is marked question, or while an item that blocks it is still in the table. The item's L +picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in +bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I +unscored, the chunk runs on the model's cheapest rung. The item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there, never below the worker's rung. The worker's first prompt names the rung and the item, and asks the worker to name each item the chunk takes, with its L and E + I, and to count the item's size again @@ -153,6 +154,7 @@ from loop_claude.loop.routing_check import check_routing from loop_claude.project.checkout import checkout_root from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG +from git_repo import default_branch_todo from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Unfinished @@ -171,6 +173,9 @@ from model_routing.route import Route, route_from from claude_code.session import Session, session_named, session_open, transcript_file from loop_claude.stop import Stop +# Seconds before routing gives up asking origin for its default branch, which it asks only where the checkout records none, and routes on the project's rung. +ORIGIN_TIMEOUT = 60 + def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: try: @@ -195,8 +200,6 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if stop := exec_if_edited(launcher, baseline, loop_run, effects): return stop loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) - # First, so the premises, the records and the plan item routing reads are the checkout's as the preflight fast-forwarded it. - facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects) premises = read_premises(loop_run.root) if isinstance(premises, Stop): return premises @@ -206,9 +209,11 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc models = get_or_ask_models(key, paths, env, effects) if isinstance(models, Stop): return models + # Before routing, which reads the plan as the preflight's fetch left it; after the reads above, so a loop that stops on one makes no worktree. + facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects) anchor = project_rung(models.worker) root = loop_run.root - loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(root)) + loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(default_branch_todo(root, ORIGIN_TIMEOUT))) route = loop_run.route or Route(Rung(models.worker)) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) verdict = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) @@ -258,23 +263,15 @@ def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | No def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str: """What chunk-preflight printed at the checkout root, for a fresh worker's prompt, or why it could not run.""" - try: - done = effects.python([str(preflight)], root) - except OSError as failure: - return prompts.preflight_failed(str(failure)) + done = effects.python([str(preflight)], root) if done.returncode: return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") return prompts.preflight_facts(done.stdout.strip()) -def plan_item(root: str) -> Item | None: - """The item that routes a chunk, from the checkout's todo.md: the file chunk-preflight reads, and the pick, todo_table.next_item, it makes. None without one, so the chunk runs on the project's rung.""" - try: - item = routed_item(pathlib.Path(root, "todo.md").read_text(encoding="utf-8")) - except FileNotFoundError: - return None - except (OSError, ValueError) as failure: - item = Failure(f"could not read todo.md: {failure}") +def plan_item(todo: str | Failure) -> Item | None: + """The item that routes a chunk, from todo.md as git_repo.default_branch_todo reads it, as chunk-preflight does, so both take todo_table.next_item's pick. None without one, so the chunk runs on the project's rung.""" + item = todo if isinstance(todo, Failure) else routed_item(todo) if isinstance(item, Failure): print(f"routing on the project's rung: {item.reason}", file=sys.stderr) return None diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 404cd9be..87363c54 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -80,11 +80,11 @@ def fingerprint(launcher: pathlib.Path) -> str: def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None + trial = effects.python([str(launcher), "--help"], loop_run.root) + if trial.returncode != 0: + print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) + return None try: - trial = effects.python([str(launcher), "--help"], loop_run.root) - if trial.returncode != 0: - print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) - return None effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))]) except OSError as failure: return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude ") diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 1e4f2fb6..42031b5d 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -190,6 +190,12 @@ class Checkout: def git(self, *args): subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env) + def commit_plan(self, todo): + """Commits todo as todo.md on the checkout's branch, the default branch routing reads it from.""" + (self.root / "todo.md").write_text(todo) + self.git("add", "todo.md") + self.git("commit", "--quiet", "-m", "plan") + def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None): for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"): pathlib.Path(self.env[name]).unlink(missing_ok=True) @@ -318,6 +324,14 @@ class Premises(unittest.TestCase): self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.stderr.strip(), "could not start git: No such file or directory") + def test_makes_no_worktree_for_a_readme_without_premises(self): + checkout = Checkout(self) + checkout.commit_plan(TODO) + (checkout.root / "README.md").write_text("# Project\n") + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertFalse((checkout.home / "code" / "proj-item-4").exists()) + def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self): checkout = Checkout(self) for root in (checkout.temp / "elsewhere", checkout.home / "code"): @@ -351,9 +365,9 @@ class Cycles(unittest.TestCase): self.assertIsNone(argument(workers[1], "--session-id")) self.assertIsNone(argument(workers[1], "--name")) self.assertEqual(argument(workers[2], "--session-id"), session) - self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\n")) + self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe.")) - self.assertIn("\n\n- No default branch: no origin remote, and no main or master branch to take as the default branch\n\nThe chunk's", argument(workers[0], "-p")) + self.assertIn("main or master", argument(workers[0], "-p")) self.assertNotIn(TASK, argument(workers[1], "-p")) self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p")) self.assertIn("as the work remaining:\n\n> started\n\n", argument(workers[1], "-p")) @@ -375,7 +389,7 @@ class Cycles(unittest.TestCase): def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" - (checkout.root / "todo.md").write_text(CHEAP) + checkout.commit_plan(CHEAP) run = checkout.run([ worker(say="one"), judge(evidence="one"), worker(say="two"), judge(evidence="two"), @@ -398,34 +412,34 @@ class Cycles(unittest.TestCase): self.assertIn(" Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at medium effort, routed by item 4's L of 2 and E + I of 3\n\n Stepped up\n\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) self.assertIn(" Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) - def test_fast_forwards_the_checkout_before_routing_so_routing_and_the_preflight_name_the_same_item(self): + def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" origin = checkout.temp / "origin.git" checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin)) checkout.git("symbolic-ref", "HEAD", "refs/heads/main") - (checkout.root / "todo.md").write_text(TODO) - checkout.git("add", "-A") - checkout.git("commit", "--quiet", "-m", "plan item 4") + checkout.commit_plan(TODO) checkout.git("remote", "add", "origin", str(origin)) checkout.git("push", "--quiet", "--set-upstream", "origin", "main") - # Item 4 ships elsewhere, and item 6 is next; the checkout is behind origin. + # Item 4 ships elsewhere, and item 6 is next; the checkout is behind origin, and holds a change of its own. elsewhere = checkout.temp / "elsewhere" checkout.git("clone", "--quiet", str(origin), str(elsewhere)) (elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |")) checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "item 4 shipped, plan item 6") checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main") - run = checkout.run([worker()]) + (checkout.root / "todo.md").write_text(TODO + "\nA change of the checkout's own.\n") + (checkout.root / "sub").mkdir() + run = checkout.run([worker()], cwd=checkout.root / "sub") self.assertEqual(run.code, 130) prompt = argument(run.calls[0], "-p") self.assertIn("routed by item 6's L of 4", prompt) - self.assertIn("Its first item that does not wait: item 6,", prompt) - self.assertIn("The checkout was fast-forwarded to origin/main.", prompt) + self.assertIn("item 6, L 4, E + I 5", prompt) + self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir()) def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" - (checkout.root / "todo.md").write_text(TODO) + checkout.commit_plan(TODO) run = checkout.run([ worker(say="Stability round 2: a 🔴. Trigger 3 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Stability round 2: a 🔴."), worker(say="Trigger 2 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Trigger 2 fired; … a higher rung."), @@ -447,7 +461,7 @@ class Cycles(unittest.TestCase): def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5" - (checkout.root / "todo.md").write_text(CHEAP) + checkout.commit_plan(CHEAP) run = checkout.run([worker(say="one"), judge(finished=True, evidence="one"), worker(say="next chunk")]) self.assertEqual(run.code, 130) first = next(call for call in run.calls if call["role"] == "worker") @@ -460,7 +474,7 @@ class Cycles(unittest.TestCase): def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5" - (checkout.root / "todo.md").write_text(CHEAP) + checkout.commit_plan(CHEAP) run = checkout.run([ worker(say="one"), judge(evidence="one", bundled_escape_and_impact=6), worker(say="two"), judge(finished=True, evidence="two"), @@ -478,11 +492,12 @@ class Cycles(unittest.TestCase): def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self): checkout = Checkout(self) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" - (checkout.root / "todo.md").write_text(TODO) + checkout.commit_plan(TODO) run = checkout.run([worker(), judge(), worker(), judge()]) self.assertEqual(run.code, 130) self.assertEqual(argument(run.calls[-1], "--effort"), "xhigh") - (checkout.root / "todo.md").unlink() + checkout.git("rm", "--quiet", "todo.md") + checkout.git("commit", "--quiet", "-m", "drop the plan") run = checkout.run([worker()]) self.assertIsNotNone(argument(run.calls[0], "--resume")) self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh")) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 546eb48c..c5329bc0 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -18,7 +18,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive from loop_claude.project import checkout, model_choice, records -from loop_claude.effects import Effects, run_python +from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python from claude_code import entries, reply, session from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from @@ -721,17 +721,13 @@ class Routing(unittest.TestCase): class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - with tempfile.TemporaryDirectory() as root: - self.assertIsNone(main.plan_item(root)) - todo = pathlib.Path(root, "todo.md") - todo.write_text(TODO) - self.assertEqual(main.plan_item(root).id, 3) - for text, said in ((TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (b"\xff", "routing on the project's rung: could not read todo.md: ")): - with self.subTest(said=said): - todo.write_bytes(text if isinstance(text, bytes) else text.encode()) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.plan_item(root)) - self.assertTrue(stderr.getvalue().startswith(said), stderr.getvalue()) + self.assertIsNone(main.plan_item("")) + self.assertEqual(main.plan_item(TODO).id, 3) + for todo, said in ((TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("git show origin/main:todo.md printed text that is not UTF-8"), "routing on the project's rung: git show origin/main:todo.md printed text that is not UTF-8\n")): + with self.subTest(said=said): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsNone(main.plan_item(todo)) + self.assertTrue(stderr.getvalue().startswith(said), stderr.getvalue()) def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self): with tempfile.TemporaryDirectory() as home: @@ -810,12 +806,13 @@ class ChunkFacts(unittest.TestCase): said = main.chunk_facts(self.PREFLIGHT, "/r", fake.effects()) self.assertEqual(fake.made("python"), [(["/b/chunk-preflight"], "/r")]) self.assertIn("\n\n- A fact.", said) + self.assertNotIn("yourself", said) def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self): - for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "it exited 1"), (OSError(2, "No such file or directory"), "No such file or directory")): + for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")): with self.subTest(why=why): said = main.chunk_facts(self.PREFLIGHT, "/r", FakeEffects(python=[failed]).effects()) - self.assertIn("find the chunk's facts yourself", said) + self.assertIn("yourself", said) self.assertIn(why, said) @@ -827,7 +824,18 @@ class PythonEffect(unittest.TestCase): def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self): done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5) self.assertEqual(done.returncode, 1) - self.assertIn("after 0.5 s", done.stderr) + self.assertIn("0.5 s", done.stderr) + + def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self): + with tempfile.TemporaryDirectory() as cwd: + self.assertEqual(run_python(["-c", "import sys; sys.stdout.buffer.write(b'caf\\xe9')"], cwd, 60).stdout, "caf�") + + def test_reads_a_script_that_cannot_start_as_exit_1_saying_why(self): + with tempfile.TemporaryDirectory() as temp: + gone = str(pathlib.Path(temp, "gone")) + done = run_python(["-c", "pass"], gone, 60) + self.assertEqual(done.returncode, 1) + self.assertIn(gone, done.stderr) class WorkerArgs(unittest.TestCase): @@ -838,25 +846,29 @@ class WorkerArgs(unittest.TestCase): def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn("Do it.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed) + self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 3.", routed) unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) - self.assertIn(f"Do it.\n\n{self.FACTS}\n\nThe chunk's", unrouted) + self.assertIn(f"before creating a new one.\n\n{self.FACTS}\n\nThe chunk's", unrouted) self.assertNotIn("loop-claude runs you on", unrouted) def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn("After your first read of the code, count item 3's size again", routed) + self.assertIn("item 3's size again", routed) self.assertIn("escalation trigger 1", routed) self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) - def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_and_continue_an_open_pr_itself(self): - self.assertIn("Take what it printed as found rather than finding it again:\n\n- A fact.", prompts.preflight_facts("- A fact.")) + def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): + self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact.")) failed = prompts.preflight_failed("git could not start") - self.assertIn("find the chunk's facts yourself", failed) - self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.", failed) + self.assertIn("yourself", failed) self.assertIn("git could not start", failed) + def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self): + for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")): + with self.subTest(facts=facts): + self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) + def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): opus = Rung("claude-opus-5-5", "medium") below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS) @@ -904,7 +916,7 @@ class WorkerArgs(unittest.TestCase): self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None)) self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus)) - self.assertIn("Do it.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS)) + self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS)) def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): opus = Rung("claude-opus-5-5", "medium") @@ -1110,6 +1122,7 @@ class HelpLimits(unittest.TestCase): self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60)) self.assertIn("fails three times running, retried a minute apart", said) self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) + self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said) class ExitContract(unittest.TestCase): diff --git a/bin/repo_checks/test_types.py b/bin/repo_checks/test_types.py index ec14b846..4271ed85 100644 --- a/bin/repo_checks/test_types.py +++ b/bin/repo_checks/test_types.py @@ -15,5 +15,5 @@ class Types(unittest.TestCase): self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "stability_replay", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "stability_replay", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/bin/test_git_repo.py b/bin/test_git_repo.py new file mode 100644 index 00000000..45c55c1e --- /dev/null +++ b/bin/test_git_repo.py @@ -0,0 +1,28 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from failure import Failure +from git_repo import git + + +class Git(unittest.TestCase): + # Each command is a shell alias, so it touches no repository, whatever GIT_DIR the test runs under. + + def test_stops_git_still_running_after_the_timeout_and_says_so(self): + done = git("-c", "alias.hang=!sleep 5", "hang", timeout=0.2) + self.assertIsInstance(done, Failure) + self.assertIn("hang", done.reason) + self.assertIn("0.2 s", done.reason) + + def test_says_git_printed_text_that_is_not_utf_8(self): + done = git("-c", "alias.latin=!printf 'caf\\351'", "latin") + self.assertIsInstance(done, Failure) + self.assertIn("latin", done.reason) + self.assertIn("UTF-8", done.reason) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 311a94f0..ae5d1ef9 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -111,6 +111,10 @@ class Rank(unittest.TestCase): self.assertEqual(ranked.notes, []) self.assertEqual(self.ranked(ranked.text), ranked) + def test_keeps_a_detail_that_opens_with_markdown_quoted_by_four_spaces(self): + quoting = TODO.replace("Fast detail.", " ## Goals\n\nFast detail.") + self.assertIn("### 3. Make it fast, `a | b`.\n\n ## Goals\n\nFast detail.\n", self.ranked(quoting).text) + def test_weighs_each_achieve_goal_by_its_sum_reciprocal_rank(self): readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n" self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme)).items()}, {"1": 0.5455, "1.1": 0.5455, "1.2": 0.2727, "2": 0.1818}) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 70625d6e..17f1cffd 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -24,7 +24,7 @@ The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.m Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary. -**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it. +**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree, unless loop-claude's prompt already shows its output there, and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it. ## 3. Passes diff --git a/todo.md b/todo.md index 275a4ffb..2d7cb57e 100644 --- a/todo.md +++ b/todo.md @@ -38,7 +38,7 @@ | 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 | | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | -| 175 | 0.3.0 | | | **Compare the time and fresh tokens before the first edit in the first five chunks loop-claude starts with `chunk-preflight` against item 140's, and file an item where they did not fall.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | +| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds and unfinished verdicts, and file an item where the preflight did not pay.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -205,9 +205,9 @@ lilleman asked, on 2026-10-16, for a standing audit each release, so the loop ke The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it. -### 175. Compare the time and fresh tokens before the first edit in the first five chunks loop-claude starts with `chunk-preflight` against item 140's, and file an item where they did not fall. +### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds and unfinished verdicts, and file an item where the preflight did not pay. -Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure the same figures from loop-claude's archive for the first five chunks that started with the preflight. Where their median did not fall, file an item naming the facts the workers still found by hand. +Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure goal 1.4's counter-signal beside them, review rounds and unfinished verdicts per chunk, since a worker that reads less may start sooner and need more rounds. Where time or tokens did not fall, or rounds or unfinished verdicts rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. -- 2.52.0 From 0472ec045287d6a0c2086353347eface7570544f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:07:40 +0200 Subject: [PATCH 07/22] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20nothing=20to=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 786860683e528e7c0a9b6176cfcc2f18e130dd04 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:07:40 +0200 Subject: [PATCH 08/22] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1;=20answered=20in=20the=20princ?= =?UTF-8?q?iples=20round=201=20commit:=20name=20no=20item=20where=20the=20?= =?UTF-8?q?release=20after=20the=20last=20tag=20has=20none,=20tell=20an=20?= =?UTF-8?q?empty=20items=20table=20from=20none,=20add=20the=20tests=20the?= =?UTF-8?q?=20surviving=20mutants=20named,=20print=20an=20unreadable=20cha?= =?UTF-8?q?ngelog's=20reason=20and=20the=20timeout's=20value;=20Effects'?= =?UTF-8?q?=20restructure=20stays=20out=20of=20this=20item?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 45004e1b0bc50f915f053514179bff6cbd56a698 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:07:40 +0200 Subject: [PATCH 09/22] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=203=20=F0=9F=9F=A1;=20answered=20in=20the=20pr?= =?UTF-8?q?inciples=20round=201=20commit:=20route=20and=20preflight=20on?= =?UTF-8?q?=20the=20fetched=20default=20branch's=20todo.md,=20name=20no=20?= =?UTF-8?q?item=20where=20the=20release=20after=20the=20last=20tag=20has?= =?UTF-8?q?=20none,=20keep=20the=20open-PR=20sentence=20in=20every=20fresh?= =?UTF-8?q?=20prompt=20and=20name=20the=20item=20branch=20in=20CLAUDE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 4cf3c2bd8c27398e8e0f88dd182f28ea2645c862 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:19:11 +0200 Subject: [PATCH 10/22] =?UTF-8?q?Answer=20architecture=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1;=20pick=20the=20next=20chunk's?= =?UTF-8?q?=20item=20in=20one=20function,=20todo=5Ftable.chunk=5Fitem,=20w?= =?UTF-8?q?hich=20routing=20and=20the=20preflight=20both=20call,=20so=20ro?= =?UTF-8?q?uting=20names=20no=20item=20where=20the=20release=20after=20the?= =?UTF-8?q?=20last=20cut=20has=20none?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/gathered.py | 25 ++---------- bin/chunk_preflight/main.py | 15 +++---- bin/chunk_preflight/test_chunk_preflight.py | 27 +------------ bin/git_repo.py | 34 +++++++++++----- bin/loop_claude/loop/main.py | 22 ++++++---- bin/loop_claude/routing.py | 8 ++-- bin/loop_claude/test_loop_claude.py | 45 +++++++++++++-------- bin/test_rank_todo.py | 25 ++++++++++++ bin/todo_table.py | 24 +++++++++++ 9 files changed, 130 insertions(+), 95 deletions(-) diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 83f82a4e..f7bc8786 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -4,16 +4,13 @@ import pathlib import re import typing +from todo_table import chunk_item, Item, item_details, items from failure import Failure -from todo_table import Item, item_details, items, next_item # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. Forge = typing.Literal["gh", "tea"] # The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields. PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} -# How the plan's earliest release stands to the version x.y.z the newest tag names. "next": it is x.y.z+1, x.y+1.0 or x+1.0.0, or no tag names a version. "cut": it is x.y.z or earlier. -# Else the release after the tag holds no item: "finished" where commits followed the tag, "unplanned" where none did, and "unknown" where they cannot be counted. -Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] @dataclasses.dataclass(frozen=True) @@ -94,7 +91,7 @@ class Gathered: def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoItem: - """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.next_item's pick, where standing finds the plan's earliest release next; else why there is none.""" + """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick, which routing makes too; else why there is none.""" where = f"{default}'s todo.md" if isinstance(todo, Failure): return NoItem(f"{where} cannot be read: {todo.reason}.") @@ -104,7 +101,7 @@ def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoIte if found is None: return NoItem(f"{where} holds no items table.") earliest = min((item.release for item in found), default=None) - stands = standing(release, earliest) + stands, first = chunk_item(found, release.tag, release.commits) if earliest is not None and stands == "cut": return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {release.tag}.") gap = f"{where} holds no item for the release after the last cut, {release.tag}, and" @@ -114,7 +111,6 @@ def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoIte return NoItem(f"{gap} no commit has landed since, so that release is to be planned first.") if stands == "unknown": return NoItem(f"{gap} the commits since it cannot be counted.") - first = next_item(found) if first is None: return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.") details = item_details(todo) @@ -122,21 +118,6 @@ def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoIte return Plan(found, first, f"{first.tagline}\n\n{detail}".strip()) -def standing(release: Release, earliest: tuple[int, int, int] | None) -> Standing: - """How the plan's earliest release, None where the plan holds no item, stands to the version the release's tag names, as Standing says.""" - cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", release.tag) if isinstance(release.tag, str) else None - if cut is None: - return "next" - major, minor, patch = (int(part) for part in cut.groups()) - if earliest in ((major, minor, patch + 1), (major, minor + 1, 0), (major + 1, 0, 0)): - return "next" - if earliest is not None and earliest <= (major, minor, patch): - return "cut" - if isinstance(release.commits, Failure): - return "unknown" - return "finished" if release.commits else "unplanned" - - def version(release: tuple[int, int, int]) -> str: return ".".join(map(str, release)) diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index d78042cd..cc0bc3ee 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -44,7 +44,7 @@ import subprocess import sys import typing -from git_repo import commit_exists, commits_since, default_branch, default_branch_todo, file_at, git, newest_release_tag, top +from git_repo import commit_exists, default_branch, default_plan, file_at, git, top from failure import Failure from chunk_preflight.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on from chunk_preflight.facts import render @@ -96,18 +96,15 @@ def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure: if isinstance(default, Failure): return default ref, note = default - cut = release(ref, root) - plan = planned(default_branch_todo(str(root), timeout), cut, ref) + held = default_plan(str(root), timeout) + if isinstance(held, Failure): + return held + cut = Release(held.tag, file_at(ref, "CHANGELOG.md", str(root)), held.commits) + plan = planned(held.todo, cut, ref) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout) return render(Gathered(ref, note, cut, item)) -def release(default: str, root: pathlib.Path) -> Release: - tag = newest_release_tag(default) - commits = tag if isinstance(tag, Failure) else commits_since(tag, default) - return Release(tag, file_at(default, "CHANGELOG.md", str(root)), commits) - - def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> ItemFacts: worktree = item_worktree(root, plan.branch, default) path = worktree.path if isinstance(worktree, Worktree) else None diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index c515ccdb..48a641a6 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -9,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Release, standing, Worktree, worktree_add +from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Release, Worktree, worktree_add from test_env import isolated_env from chunk_preflight.main import line_count, ran, seconds, TIMEOUT from chunk_preflight.facts import open_pulls, render, unreleased_entries @@ -387,31 +387,6 @@ class Plans(unittest.TestCase): self.assertEqual(planned(TODO[:TODO.index("## Details")], CUT, "origin/main").text, "**Do the next thing.**") -class Standing(unittest.TestCase): - def test_takes_the_earliest_release_where_it_is_the_next_patch_minor_or_major_or_no_tag_names_a_version(self): - cases = ( - (Release("v1.2.3", "", 4), (1, 2, 4), "next"), - (Release("v1.2.3", "", 4), (1, 3, 0), "next"), - (Release("v1.2.3", "", 4), (2, 0, 0), "next"), - (Release(None, "", 4), (0, 2, 0), "next"), - (Release(None, "", 4), None, "next"), - (Release("v1.2.3-rc.1", "", 4), (1, 2, 3), "next"), - (Release(Failure("tags unreadable"), "", 4), (0, 2, 0), "next"), - (Release("v1.2.3", "", 4), (1, 2, 3), "cut"), - (Release("v1.2.3", "", 4), (1, 2, 2), "cut"), - (Release("v1.2.3", "", 4), (1, 2, 5), "finished"), - (Release("v1.2.3", "", 4), (1, 3, 1), "finished"), - (Release("v1.2.3", "", 4), (2, 0, 1), "finished"), - (Release("v1.2.3", "", 4), None, "finished"), - (Release("v1.2.3", "", 0), (1, 4, 0), "unplanned"), - (Release("v1.2.3", "", 0), None, "unplanned"), - (Release("v1.2.3", "", Failure("count unreadable")), (1, 4, 0), "unknown"), - ) - for release, earliest, stands in cases: - with self.subTest(release=release, earliest=earliest): - self.assertEqual(standing(release, earliest), stands) - - class Gathering(unittest.TestCase): def test_counts_the_top_level_entries_under_unreleased(self): self.assertEqual(unreleased_entries(CHANGELOG), 2) diff --git a/bin/git_repo.py b/bin/git_repo.py index 20bee97c..85e5605e 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -1,4 +1,5 @@ """Run git, in the current directory or a given one, and read the checkout, its default branch and its files.""" +import dataclasses import re import subprocess @@ -60,22 +61,37 @@ def origin_head(cwd: str | None, timeout: float | None) -> str | Failure: return Failure("origin names no default branch; set it with `git remote set-head origin --auto`") -def default_branch_todo(root: str, timeout: float) -> str | Failure: - """todo.md on the default branch as last fetched, read in the checkout at root; empty where that branch holds none. Asking origin, where the checkout records no default branch for it, fails after timeout seconds.""" +@dataclasses.dataclass(frozen=True) +class DefaultPlan: + """What the default branch, as last fetched, holds for picking the next chunk's item: todo_table.chunk_item's inputs.""" + ref: str + # todo.md's text, empty where the branch holds none. + todo: str | Failure + # The newest v* tag on the branch, None where it has none. + tag: str | None | Failure + # How many commits follow the tag, or make up the branch where it has none. + commits: int | Failure + + +def default_plan(root: str, timeout: float) -> DefaultPlan | Failure: + """What the default branch as last fetched holds for the pick, read in the checkout at root. Asking origin, where the checkout records no default branch for it, fails after timeout seconds.""" ref = default_ref(root, timeout) - return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", root) + if isinstance(ref, Failure): + return ref + tag = newest_release_tag(ref, root) + return DefaultPlan(ref, file_at(ref, "todo.md", root), tag, tag if isinstance(tag, Failure) else commits_since(tag, ref, root)) -def newest_release_tag(branch: str) -> str | None | Failure: - """The newest `v*` tag merged into branch, None when it has none.""" +def newest_release_tag(branch: str, cwd: str | None = None) -> str | None | Failure: + """The newest `v*` tag merged into branch, read in cwd, else in the current directory; None when it has none.""" # Sorts v1.0.0-rc.1 below v1.0.0. - tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", branch, "--sort=-v:refname") + tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", branch, "--sort=-v:refname", cwd=cwd) return tags if isinstance(tags, Failure) else next(iter(tags.split()), None) -def commits_since(tag: str | None, branch: str) -> int | Failure: - """How many commits branch holds after tag, or holds in all where tag is None.""" - count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch) +def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> int | Failure: + """How many commits branch holds after tag, or holds in all where tag is None; read in cwd, else in the current directory.""" + count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd) return count if isinstance(count, Failure) else int(count) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 25d0b542..a8919d2b 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -50,9 +50,10 @@ for the worker and the interrupt; with both set, nothing is asked. Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, todo.md on the -default branch, as chunk-preflight has just fetched it, routes it: its earliest release's top item -that does not wait, the item the preflight states where that release is the next. An item waits -while it is marked question, or while an item that blocks it is still in the table. The item's L +default branch, as chunk-preflight has just fetched it, routes it on the item the preflight names +(todo_table.chunk_item): the earliest release's top item that does not wait, where that release is +the one after the newest v* tag, or there is no such tag. An item waits while it is marked +question, or while an item that blocks it is still in the table. The item's L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I unscored, the chunk runs on the model's cheapest rung. The @@ -154,7 +155,7 @@ from loop_claude.loop.routing_check import check_routing from loop_claude.project.checkout import checkout_root from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG -from git_repo import default_branch_todo +from git_repo import default_plan, DefaultPlan from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Unfinished @@ -213,7 +214,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects) anchor = project_rung(models.worker) root = loop_run.root - loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(default_branch_todo(root, ORIGIN_TIMEOUT))) + loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(default_plan(root, ORIGIN_TIMEOUT))) route = loop_run.route or Route(Rung(models.worker)) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) verdict = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) @@ -269,9 +270,14 @@ def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str: return prompts.preflight_facts(done.stdout.strip()) -def plan_item(todo: str | Failure) -> Item | None: - """The item that routes a chunk, from todo.md as git_repo.default_branch_todo reads it, as chunk-preflight does, so both take todo_table.next_item's pick. None without one, so the chunk runs on the project's rung.""" - item = todo if isinstance(todo, Failure) else routed_item(todo) +def plan_item(plan: DefaultPlan | Failure) -> Item | None: + """The item that routes a chunk, from the default branch as git_repo.default_plan reads it, as chunk-preflight does, so both take todo_table.chunk_item's pick. None without one, so the chunk runs on the project's rung.""" + if isinstance(plan, Failure): + item: Item | Failure | None = plan + elif isinstance(plan.todo, Failure): + item = plan.todo + else: + item = routed_item(plan.todo, plan.tag, plan.commits) if isinstance(item, Failure): print(f"routing on the project's rung: {item.reason}", file=sys.stderr) return None diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 92ba42ac..06224c2f 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -1,9 +1,9 @@ """Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.""" import dataclasses +from todo_table import chunk_item, Item, items from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung from failure import Failure -from todo_table import Item, items, next_item from model_routing.route import Route UNFINISHED_PER_STEP = 2 @@ -13,12 +13,12 @@ ESCALATION_CAP = 2 JUDGE_REPLAYED = ("claude-opus-5-5",) -def routed_item(todo: str) -> Item | Failure | None: - """The item todo_table.next_item names; None when there is none, or it lacks L, E or I.""" +def routed_item(todo: str, tag: str | None | Failure, commits: int | Failure) -> Item | Failure | None: + """The item todo_table.chunk_item picks from todo.md, given the newest v* tag and the commits since it; None when there is none, or it lacks L, E or I.""" found = items(todo) if isinstance(found, Failure): return found - takes = next_item(found or []) + _, takes = chunk_item(found or [], tag, commits) return takes if takes and takes.likelihood and takes.escape_and_impact else None diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index c5329bc0..0c546bdc 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -18,6 +18,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive from loop_claude.project import checkout, model_choice, records +from git_repo import DefaultPlan from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python from claude_code import entries, reply, session from failure import Failure @@ -587,24 +588,32 @@ class Routing(unittest.TestCase): SONNET = Rung("claude-sonnet-5-5", "high") def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): - self.assertEqual(routing.routed_item(TODO).id, 3) - self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"))) - self.assertIsNone(routing.routed_item("# todo\n")) - self.assertIsNone(routing.routed_item(TODO[:TODO.index("| 7 |")])) + self.assertEqual(routing.routed_item(TODO, None, 0).id, 3) + self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"), None, 0)) + self.assertIsNone(routing.routed_item("# todo\n", None, 0)) + self.assertIsNone(routing.routed_item(TODO[:TODO.index("| 7 |")], None, 0)) old_shape = "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | **Do the next thing.** | 5 | 3 | 6 | 8 | 9 | 1 | 25 |\n" - self.assertIsNone(routing.routed_item(old_shape)) - self.assertEqual(routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), Failure("item 3's L 'x' is not a whole number from 1 to 4")) + self.assertIsNone(routing.routed_item(old_shape, None, 0)) + self.assertEqual(routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), None, 0), Failure("item 3's L 'x' is not a whole number from 1 to 4")) + + def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self): + self.assertEqual(routing.routed_item(TODO, "v0.1.0", 3).id, 3) + self.assertIsNone(routing.routed_item(TODO, "v0.2.0", 3)) + later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):] + self.assertIsNone(routing.routed_item(later_only, "v0.1.0", 3)) + self.assertIsNone(routing.routed_item(later_only, "v0.1.0", 0)) + self.assertEqual(routing.routed_item(later_only, "v0.2.0", 3).id, 1) def test_routes_past_an_item_a_waiting_item_blocks(self): todo = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n| 8 | 0.2.0 | 7 | | **Use the answer.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 9 | 0.2.0 | 8 | | **Build on it.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n" - self.assertEqual(routing.routed_item(todo).id, 3) - self.assertEqual(routing.routed_item(todo.replace("| question |", "| |")).id, 7) + self.assertEqual(routing.routed_item(todo, None, 0).id, 3) + self.assertEqual(routing.routed_item(todo.replace("| question |", "| |"), None, 0).id, 7) first = "| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n" - self.assertEqual(routing.routed_item(todo.replace(first, "") + first).id, 3) + self.assertEqual(routing.routed_item(todo.replace(first, "") + first, None, 0).id, 3) def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self): - self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), Route(self.HIGH, 3, 4, 5)) - cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |")) + self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, None, 0)), Route(self.HIGH, 3, 4, 5)) + cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), None, 0) self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-haiku-5-5", "max"), 3, 1, 5)) self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS)) @@ -679,7 +688,7 @@ class Routing(unittest.TestCase): def test_routes_nothing_on_an_item_without_e_or_i(self): without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") - self.assertIsNone(routing.routed_item(without_i)) + self.assertIsNone(routing.routed_item(without_i, None, 0)) def test_archives_the_route_in_a_line_it_reads_back(self): route = Route(self.HIGH, 3, 4, 5) @@ -705,7 +714,7 @@ class Routing(unittest.TestCase): def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): def run_with(route=None): return main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=route) - item = routing.routed_item(TODO) + item = routing.routed_item(TODO, None, 0) archived = Route(self.XHIGH, 3, 4, 5) def never(): raise AssertionError("not asked") @@ -721,12 +730,14 @@ class Routing(unittest.TestCase): class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - self.assertIsNone(main.plan_item("")) - self.assertEqual(main.plan_item(TODO).id, 3) - for todo, said in ((TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("git show origin/main:todo.md printed text that is not UTF-8"), "routing on the project's rung: git show origin/main:todo.md printed text that is not UTF-8\n")): + self.assertIsNone(main.plan_item(DefaultPlan("origin/main", "", None, 0))) + self.assertEqual(main.plan_item(DefaultPlan("origin/main", TODO, "v0.1.0", 3)).id, 3) + self.assertIsNone(main.plan_item(DefaultPlan("origin/main", TODO, "v0.2.0", 3))) + unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8") + for plan, said in ((DefaultPlan("origin/main", TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), None, 0), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan("origin/main", unreadable, None, 0), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): with self.subTest(said=said): with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.plan_item(todo)) + self.assertIsNone(main.plan_item(plan)) self.assertTrue(stderr.getvalue().startswith(said), stderr.getvalue()) def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self): diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index ae5d1ef9..f01c1e3c 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -415,6 +415,31 @@ class Blockers(unittest.TestCase): self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line")) +class Standing(unittest.TestCase): + def test_takes_the_earliest_release_where_it_is_the_next_patch_minor_or_major_or_no_tag_names_a_version(self): + cases = ( + ("v1.2.3", 4, (1, 2, 4), "next"), + ("v1.2.3", 4, (1, 3, 0), "next"), + ("v1.2.3", 4, (2, 0, 0), "next"), + (None, 4, (0, 2, 0), "next"), + (None, 4, None, "next"), + ("v1.2.3-rc.1", 4, (1, 2, 3), "next"), + (Failure("tags unreadable"), 4, (0, 2, 0), "next"), + ("v1.2.3", 4, (1, 2, 3), "cut"), + ("v1.2.3", 4, (1, 2, 2), "cut"), + ("v1.2.3", 4, (1, 2, 5), "finished"), + ("v1.2.3", 4, (1, 3, 1), "finished"), + ("v1.2.3", 4, (2, 0, 1), "finished"), + ("v1.2.3", 4, None, "finished"), + ("v1.2.3", 0, (1, 4, 0), "unplanned"), + ("v1.2.3", 0, None, "unplanned"), + ("v1.2.3", Failure("count unreadable"), (1, 4, 0), "unknown"), + ) + for tag, commits, earliest, stands in cases: + with self.subTest(tag=tag, commits=commits, earliest=earliest): + self.assertEqual(todo_table.standing(tag, commits, earliest), stands) + + class Main(unittest.TestCase): def run_main(self, *argv): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: diff --git a/bin/todo_table.py b/bin/todo_table.py index 6e797230..c41376cf 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -17,6 +17,9 @@ BLOCKED_BY = "Blocked by" MOVES = "Moves" # How the items table's header opens, which tells it from any other table in todo.md. HEADER_START = "| ID | Release |" +# How the plan's earliest release stands to the version x.y.z the newest tag names. "next": it is x.y.z+1, x.y+1.0 or x+1.0.0, or no tag names a version. "cut": it is x.y.z or earlier. +# Else the release after the tag holds no item: "finished" where commits followed the tag, "unplanned" where none did, and "unknown" where they cannot be counted. +Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] # todo.md's ## Details section, its body the first group. DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) # Each goal an item names, in its order, with how far the item moves it; None in OLD_SHAPE, whose Goals cell names no move. @@ -173,6 +176,27 @@ def next_item(found: list[Item]) -> Item | None: return next((item for item in found if item.release == release and item.id not in waits), None) +def standing(tag: str | None | Failure, commits: int | Failure, earliest: tuple[int, int, int] | None) -> Standing: + """How the plan's earliest release, None where the plan holds no item, stands to the newest v* tag, as Standing says; commits counts those after the tag.""" + cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None + if cut is None: + return "next" + major, minor, patch = (int(part) for part in cut.groups()) + if earliest in ((major, minor, patch + 1), (major, minor + 1, 0), (major + 1, 0, 0)): + return "next" + if earliest is not None and earliest <= (major, minor, patch): + return "cut" + if isinstance(commits, Failure): + return "unknown" + return "finished" if commits else "unplanned" + + +def chunk_item(found: list[Item], tag: str | None | Failure, commits: int | Failure) -> tuple[Standing, Item | None]: + """The item the next chunk takes first, next_item's pick, where standing finds the plan's earliest release the next; else None. Routing and chunk-preflight both pick with it, so they name one item; standing comes with it, so a caller can say why there is none.""" + stands = standing(tag, commits, min((item.release for item in found), default=None)) + return stands, next_item(found) if stands == "next" else None + + def bundle_candidates(found: list[Item], first: Item) -> list[Item]: """The items of first's release, in the table's order, that a chunk taking first may take too: those that do not wait once the chunk's own items count as done.""" chunk = {item.id for item in found if item.release == first.release} -- 2.52.0 From 5ba8920dbf66a53d192f50581a908c6f4d7b1c5f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:34:15 +0200 Subject: [PATCH 11/22] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1;=20take=20the=20next=20release?= =?UTF-8?q?=20as=20the=20earliest=20todo.md=20has=20named=20since=20the=20?= =?UTF-8?q?last=20cut,=20so=20an=20emptied=20patch=20or=20a=20major=20jump?= =?UTF-8?q?=20stops=20the=20loop=20too,=20count=20work=20landed=20by=20the?= =?UTF-8?q?=20Unreleased=20entries=20before=20commits,=20read=20the=20defa?= =?UTF-8?q?ult=20branch=20once,=20and=20test=20the=20emptied=20release=20a?= =?UTF-8?q?nd=20the=20stalled=20origin=20through=20real=20git?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/chunk_preflight/facts.py | 16 ++---- bin/chunk_preflight/gathered.py | 27 ++++------ bin/chunk_preflight/main.py | 20 ++++---- bin/chunk_preflight/test_chunk_preflight.py | 41 ++++++++++----- bin/git_repo.py | 32 ++++++++---- bin/loop_claude/loop/main.py | 15 ++++-- bin/loop_claude/routing.py | 8 +-- bin/loop_claude/test_loop_claude.py | 47 +++++++++-------- bin/test_git_repo.py | 40 ++++++++++----- bin/test_rank_todo.py | 55 ++++++++++++-------- bin/todo_table.py | 57 ++++++++++++++++----- todo.md | 6 +-- 13 files changed, 224 insertions(+), 142 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64d761d7..20c94658 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ - `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names. - `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`. - `loop-claude` archives each judge reply it rejects in the chunk's `.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1. -- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight fetches origin and reads `todo.md` from its default branch, leaving the checkout as it is, and `loop-claude` routes on that same `todo.md`, so an edit to `todo.md` routes a chunk only once the default branch holds it. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Where `todo.md` holds no item for the release after the newest tag, it names no item, and says that release is finished and ready to cut, or is to be planned first. It stops a fetch, forge CLI or tool still running after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. +- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight fetches origin and reads `todo.md` from its default branch, leaving the checkout as it is, and `loop-claude` routes on that same `todo.md`, so an edit to `todo.md` routes a chunk only once the default branch holds it. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Where `todo.md` holds no item for the next release, the earliest it has named since the newest tag, it names no item and `loop-claude` routes on none; it says that release is finished and ready to cut where work has landed since the tag, or else is to be planned first. It stops a fetch, forge CLI or tool still running after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. ## 0.1.0 diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 76ad7d95..8a6af2aa 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,20 +1,20 @@ """The lines the preflight prints, stated from what it gathered.""" -from todo_table import bundle_candidates, Item +from todo_table import bundle_candidates, Item, LastCut, unreleased_entries from failure import Failure -from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, PULLS_LIST, Ran, Release, version -from markdown_text import quoted, sections +from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, PULLS_LIST, Ran, version +from markdown_text import quoted def render(found: Gathered) -> list[str]: """One `- ` line per fact, then the item's tagline and detail, and what each tool printed.""" note = [f"- {found.note}"] if found.note else [] - head = [*note, f"- {last_release(found.default, found.release)}"] + head = [*note, f"- {last_release(found.default, found.cut)}"] if isinstance(found.item, NoItem): return [*head, f"- No plan item: {found.item.why} No worktree was made."] return [*head, *item_lines(found.default, found.item)] -def last_release(default: str, release: Release) -> str: +def last_release(default: str, release: LastCut) -> str: if isinstance(release.tag, Failure): return f"Last version cut: cannot be read: {release.tag.reason}" cut = f"Last version cut: {release.tag or 'none'}." @@ -27,12 +27,6 @@ def last_release(default: str, release: Release) -> str: return f"{cut} Unreleased: {commits}; {changelog}." -def unreleased_entries(changelog: str) -> int | None: - """How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section.""" - found = sections(changelog).get("Unreleased") - return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) - - def item_lines(default: str, item: ItemFacts) -> list[str]: first = item.plan.first worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}" diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index f7bc8786..2b582b66 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -4,7 +4,7 @@ import pathlib import re import typing -from todo_table import chunk_item, Item, item_details, items +from todo_table import chunk_item, Item, item_details, items, LastCut from failure import Failure # The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other. @@ -21,15 +21,6 @@ class Ran: stderr: str -@dataclasses.dataclass(frozen=True) -class Release: - """What the last release fact rests on, each read from the default branch.""" - tag: str | None | Failure - changelog: str | Failure - # How many commits follow the tag, or make up the branch where it has none. - commits: int | Failure - - @dataclasses.dataclass(frozen=True) class Plan: """The default branch's todo.md items, and first, the item the next chunk takes first.""" @@ -85,12 +76,12 @@ class Gathered: default: str # Why origin reads as last fetched; None after a fetch. note: str | None - release: Release + cut: LastCut # What was found or made for the plan's first item; else why the plan names none. item: ItemFacts | NoItem -def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoItem: +def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick, which routing makes too; else why there is none.""" where = f"{default}'s todo.md" if isinstance(todo, Failure): @@ -101,16 +92,16 @@ def planned(todo: str | Failure, release: Release, default: str) -> Plan | NoIte if found is None: return NoItem(f"{where} holds no items table.") earliest = min((item.release for item in found), default=None) - stands, first = chunk_item(found, release.tag, release.commits) + stands, first = chunk_item(found, cut) if earliest is not None and stands == "cut": - return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {release.tag}.") - gap = f"{where} holds no item for the release after the last cut, {release.tag}, and" + return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}.") + gap = f"{where} holds no item for the next release after the last cut, {cut.tag}, and" if stands == "finished": - return NoItem(f"{gap} commits have landed since, so that release is finished and ready to cut, and the working loop stops here.") + return NoItem(f"{gap} work has landed since, so that release is finished and ready to cut, and the working loop stops here.") if stands == "unplanned": - return NoItem(f"{gap} no commit has landed since, so that release is to be planned first.") + return NoItem(f"{gap} no work has landed since, so that release is to be planned first.") if stands == "unknown": - return NoItem(f"{gap} the commits since it cannot be counted.") + return NoItem(f"{gap} the work landed since it cannot be counted.") if first is None: return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.") details = item_details(todo) diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index cc0bc3ee..844ff872 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -12,10 +12,11 @@ that branch holds it, the plan loop-claude routes on, and prints: holds under ## Unreleased, or else how many commits followed the tag; - the earliest release in todo.md, and that release's first item that does not wait, the item loop-claude routes on, with its L and E + I. It names that item only where the tag names no - version x.y.z, or the release is x.y.z+1, x.y+1.0 or x+1.0.0. For a later release, or a todo.md - that holds no item, it says the release after the tag holds none: finished and ready to cut where - commits followed the tag, and else to be planned first. For x.y.z or an earlier release, it says - todo.md files items under a release already cut; + version x.y.z, or the release is the earliest after x.y.z that todo.md has named at the tag or + since: the next release. Where the next release holds no item, it says so: finished and ready to + cut where work landed since the tag, counted as the ## Unreleased entries or else the commits, and + else to be planned first. For x.y.z or an earlier release, it says todo.md files items under a + release already cut; - the item's worktree: a sibling of the checkout named -item-, on the branch item-. It continues a worktree already on that branch; else it adds one on the local branch, else on a new branch tracking origin's, else on a new branch off the default branch; @@ -46,7 +47,7 @@ import typing from git_repo import commit_exists, default_branch, default_plan, file_at, git, top from failure import Failure -from chunk_preflight.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Release, Worktree, worktree_add, worktree_on +from chunk_preflight.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Worktree, worktree_add, worktree_on from chunk_preflight.facts import render BIN = pathlib.Path(__file__).resolve().parents[1] @@ -96,13 +97,10 @@ def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure: if isinstance(default, Failure): return default ref, note = default - held = default_plan(str(root), timeout) - if isinstance(held, Failure): - return held - cut = Release(held.tag, file_at(ref, "CHANGELOG.md", str(root)), held.commits) - plan = planned(held.todo, cut, ref) + held = default_plan(str(root), ref) + plan = planned(held.todo, held.cut, ref) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout) - return render(Gathered(ref, note, cut, item)) + return render(Gathered(ref, note, held.cut, item)) def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> ItemFacts: diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 48a641a6..dc785be4 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -9,10 +9,11 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Release, Worktree, worktree_add +from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Worktree, worktree_add from test_env import isolated_env +from todo_table import LastCut, unreleased_entries from chunk_preflight.main import line_count, ran, seconds, TIMEOUT -from chunk_preflight.facts import open_pulls, render, unreleased_entries +from chunk_preflight.facts import open_pulls, render BIN = pathlib.Path(__file__).resolve().parents[1] README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n" @@ -51,7 +52,7 @@ LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** EMPTY = TODO[:TODO.index("| 5 |")] CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" # What the preflight reads of the last release: tag v0.1.0, two entries under ## Unreleased, and 4 commits since the tag. -CUT = Release("v0.1.0", CHANGELOG, 4) +CUT = LastCut("v0.1.0", CHANGELOG, 4, []) # Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1. FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n" # Item 3's open pull request, as `gh pr list` prints it through the preflight's template; any other arguments exit 1. @@ -66,7 +67,7 @@ print("12\\thttps://github.com/o/r/pull/12") class Repo: """An origin with a tagged release, a clone of it at /proj, and a fake tea and gh on PATH.""" - def __init__(self, test, todo=TODO, origin="origin.git"): + def __init__(self, test, todo=TODO, origin="origin.git", changelog=CHANGELOG): temp = tempfile.TemporaryDirectory() test.addCleanup(temp.cleanup) self.temp = pathlib.Path(os.path.realpath(temp.name)) @@ -85,7 +86,7 @@ class Repo: self.write(self.root, "src/app.py", "def run():\n\treturn 1\n\n") self.commit(self.root, "start") self.git(self.root, "tag", "v0.1.0") - self.write(self.root, "CHANGELOG.md", CHANGELOG) + self.write(self.root, "CHANGELOG.md", changelog) if todo: self.write(self.root, "todo.md", todo) self.commit(self.root, "plan") @@ -152,6 +153,19 @@ class ChunkPreflightTool(unittest.TestCase): self.assertNotIn("#13", done.stdout) self.assertNotIn("`gone.py`:", done.stdout) + def test_names_no_item_and_makes_no_worktree_where_the_release_after_the_last_cut_has_emptied(self): + for changelog, fact in ((CHANGELOG, "finished and ready to cut"), ("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n", "planned first")): + with self.subTest(fact=fact): + repo = Repo(self, changelog=changelog) + repo.write(repo.root, "todo.md", LATER) + repo.commit(repo.root, "ship 0.2.0") + repo.git(repo.root, "push", "--quiet", "origin", "main") + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn(fact, done.stdout) + self.assertNotIn("item 9", done.stdout) + self.assertFalse((repo.temp / "proj-item-9").exists()) + def test_continues_the_items_worktree_and_else_its_pushed_branch(self): repo = Repo(self) repo.preflight() @@ -277,16 +291,16 @@ class Render(unittest.TestCase): def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self): self.assertIn("v0.1.0. Unreleased: 2 entries", rendered(NoItem("x."))) - self.assertIn("1 entry", rendered(NoItem("x."), Release("v0.1.0", "## Unreleased\n\n- One.\n", 4))) - without = rendered(NoItem("x."), Release("v0.1.0", "# Changelog\n", 4)) + self.assertIn("1 entry", rendered(NoItem("x."), LastCut("v0.1.0", "## Unreleased\n\n- One.\n", 4, []))) + without = rendered(NoItem("x."), LastCut("v0.1.0", "# Changelog\n", 4, [])) self.assertIn("4 commits since v0.1.0", without) self.assertIn("no ## Unreleased", without) - untagged = rendered(NoItem("x."), Release(None, "", 1)) + untagged = rendered(NoItem("x."), LastCut(None, "", 1, [])) self.assertIn("cut: none", untagged) self.assertIn("1 commit on origin/main", untagged) def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self): - said = rendered(NoItem("x."), Release("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"))) + said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), [])) self.assertIn("changelog unreadable", said) self.assertIn("cannot be counted: count unreadable", said) self.assertNotIn("no ## Unreleased", said) @@ -359,7 +373,7 @@ class Plans(unittest.TestCase): without = planned("", CUT, "origin/main").why self.assertIn("origin/main", without) self.assertIn("no items table", without) - empty = planned(EMPTY, Release(None, "", 4), "origin/main").why + empty = planned(EMPTY, LastCut(None, "", 4, []), "origin/main").why self.assertIn("holds no item", empty) self.assertNotIn("no items table", empty) @@ -373,12 +387,15 @@ class Plans(unittest.TestCase): ) for todo, commits, fact in cases: with self.subTest(todo=todo, commits=commits): - why = planned(todo, Release("v0.1.0", "", commits), "origin/main").why + why = planned(todo, LastCut("v0.1.0", "", commits, [TODO]), "origin/main").why self.assertIn(fact, why) self.assertIn("v0.1.0", why) + def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self): + self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main").first.id, 9) + def test_says_the_plan_files_items_under_a_release_already_cut(self): - why = planned(TODO, Release("v0.2.0", "", 4), "origin/main").why + why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main").why self.assertIn("release 0.2.0", why) self.assertIn("v0.2.0", why) self.assertIn("not after", why) diff --git a/bin/git_repo.py b/bin/git_repo.py index 85e5605e..d776eb9f 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -4,6 +4,7 @@ import re import subprocess from failure import Failure +from todo_table import LastCut def git(*args: str, cwd: str | None = None, timeout: float | None = None) -> str | Failure: @@ -67,19 +68,30 @@ class DefaultPlan: ref: str # todo.md's text, empty where the branch holds none. todo: str | Failure - # The newest v* tag on the branch, None where it has none. - tag: str | None | Failure - # How many commits follow the tag, or make up the branch where it has none. - commits: int | Failure + cut: LastCut -def default_plan(root: str, timeout: float) -> DefaultPlan | Failure: - """What the default branch as last fetched holds for the pick, read in the checkout at root. Asking origin, where the checkout records no default branch for it, fails after timeout seconds.""" - ref = default_ref(root, timeout) - if isinstance(ref, Failure): - return ref +def default_plan(root: str, ref: str) -> DefaultPlan: + """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) - return DefaultPlan(ref, file_at(ref, "todo.md", root), tag, tag if isinstance(tag, Failure) else commits_since(tag, ref, root)) + commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root) + return DefaultPlan(ref, file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root))) + + +def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure: + """todo.md's text at tag and at each later commit on ref that changed it, read in cwd; empty where there is no tag.""" + if not isinstance(tag, str): + return [] + changed = git("log", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd) + if isinstance(changed, Failure): + return changed + texts = [] + for commit in [tag, *changed.split()]: + text = file_at(commit, "todo.md", cwd) + if isinstance(text, Failure): + return text + texts.append(text) + return texts def newest_release_tag(branch: str, cwd: str | None = None) -> str | None | Failure: diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index a8919d2b..d47a3cba 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -52,7 +52,8 @@ Where that model is on the routing ladder (bin/model_routing/ladder.py), the wor interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, todo.md on the default branch, as chunk-preflight has just fetched it, routes it on the item the preflight names (todo_table.chunk_item): the earliest release's top item that does not wait, where that release is -the one after the newest v* tag, or there is no such tag. An item waits while it is marked +the next, the earliest after the newest v* tag that todo.md has named since that tag, or there is no +such tag; else no item routes it. An item waits while it is marked question, or while an item that blocks it is still in the table. The item's L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I @@ -155,7 +156,7 @@ from loop_claude.loop.routing_check import check_routing from loop_claude.project.checkout import checkout_root from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG -from git_repo import default_plan, DefaultPlan +from git_repo import default_plan, default_ref, DefaultPlan from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Unfinished @@ -214,7 +215,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects) anchor = project_rung(models.worker) root = loop_run.root - loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(default_plan(root, ORIGIN_TIMEOUT))) + loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(fetched_plan(root))) route = loop_run.route or Route(Rung(models.worker)) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) verdict = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) @@ -270,6 +271,12 @@ def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str: return prompts.preflight_facts(done.stdout.strip()) +def fetched_plan(root: str) -> DefaultPlan | Failure: + """What the default branch, as chunk-preflight's fetch left it, holds for routing.""" + ref = default_ref(root, ORIGIN_TIMEOUT) + return ref if isinstance(ref, Failure) else default_plan(root, ref) + + def plan_item(plan: DefaultPlan | Failure) -> Item | None: """The item that routes a chunk, from the default branch as git_repo.default_plan reads it, as chunk-preflight does, so both take todo_table.chunk_item's pick. None without one, so the chunk runs on the project's rung.""" if isinstance(plan, Failure): @@ -277,7 +284,7 @@ def plan_item(plan: DefaultPlan | Failure) -> Item | None: elif isinstance(plan.todo, Failure): item = plan.todo else: - item = routed_item(plan.todo, plan.tag, plan.commits) + item = routed_item(plan.todo, plan.cut) if isinstance(item, Failure): print(f"routing on the project's rung: {item.reason}", file=sys.stderr) return None diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 06224c2f..09e5ec49 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -1,7 +1,7 @@ """Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`.""" import dataclasses -from todo_table import chunk_item, Item, items +from todo_table import chunk_item, Item, items, LastCut from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung from failure import Failure from model_routing.route import Route @@ -13,12 +13,12 @@ ESCALATION_CAP = 2 JUDGE_REPLAYED = ("claude-opus-5-5",) -def routed_item(todo: str, tag: str | None | Failure, commits: int | Failure) -> Item | Failure | None: - """The item todo_table.chunk_item picks from todo.md, given the newest v* tag and the commits since it; None when there is none, or it lacks L, E or I.""" +def routed_item(todo: str, cut: LastCut) -> Item | Failure | None: + """The item todo_table.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I.""" found = items(todo) if isinstance(found, Failure): return found - _, takes = chunk_item(found or [], tag, commits) + _, takes = chunk_item(found or [], cut) return takes if takes and takes.likelihood and takes.escape_and_impact else None diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 0c546bdc..bf23d212 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -25,6 +25,7 @@ from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker from model_routing.ladder import LADDER, Rung +from todo_table import LastCut from claude_code.reply import Limited from loop_claude.loop import main, reload, routing_check from transcript_archive import outcomes, write @@ -568,6 +569,8 @@ class ModelPrompt(unittest.TestCase): self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended")) +# A plan read with no release cut yet. +NO_CUT = LastCut(None, "", 0, []) TODO = """# todo ## Items @@ -588,32 +591,32 @@ class Routing(unittest.TestCase): SONNET = Rung("claude-sonnet-5-5", "high") def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): - self.assertEqual(routing.routed_item(TODO, None, 0).id, 3) - self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"), None, 0)) - self.assertIsNone(routing.routed_item("# todo\n", None, 0)) - self.assertIsNone(routing.routed_item(TODO[:TODO.index("| 7 |")], None, 0)) + self.assertEqual(routing.routed_item(TODO, NO_CUT).id, 3) + self.assertIsNone(routing.routed_item(TODO.replace("| | **Do", "| question | **Do"), NO_CUT)) + self.assertIsNone(routing.routed_item("# todo\n", NO_CUT)) + self.assertIsNone(routing.routed_item(TODO[:TODO.index("| 7 |")], NO_CUT)) old_shape = "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | **Do the next thing.** | 5 | 3 | 6 | 8 | 9 | 1 | 25 |\n" - self.assertIsNone(routing.routed_item(old_shape, None, 0)) - self.assertEqual(routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), None, 0), Failure("item 3's L 'x' is not a whole number from 1 to 4")) + self.assertIsNone(routing.routed_item(old_shape, NO_CUT)) + self.assertEqual(routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), Failure("item 3's L 'x' is not a whole number from 1 to 4")) def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self): - self.assertEqual(routing.routed_item(TODO, "v0.1.0", 3).id, 3) - self.assertIsNone(routing.routed_item(TODO, "v0.2.0", 3)) + self.assertEqual(routing.routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3) + self.assertIsNone(routing.routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO]))) later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):] - self.assertIsNone(routing.routed_item(later_only, "v0.1.0", 3)) - self.assertIsNone(routing.routed_item(later_only, "v0.1.0", 0)) - self.assertEqual(routing.routed_item(later_only, "v0.2.0", 3).id, 1) + self.assertIsNone(routing.routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO]))) + self.assertIsNone(routing.routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO]))) + self.assertEqual(routing.routed_item(later_only, LastCut("v0.2.0", "", 3, [later_only])).id, 1) def test_routes_past_an_item_a_waiting_item_blocks(self): todo = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n| 8 | 0.2.0 | 7 | | **Use the answer.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 9 | 0.2.0 | 8 | | **Build on it.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n" - self.assertEqual(routing.routed_item(todo, None, 0).id, 3) - self.assertEqual(routing.routed_item(todo.replace("| question |", "| |"), None, 0).id, 7) + self.assertEqual(routing.routed_item(todo, NO_CUT).id, 3) + self.assertEqual(routing.routed_item(todo.replace("| question |", "| |"), NO_CUT).id, 7) first = "| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n" - self.assertEqual(routing.routed_item(todo.replace(first, "") + first, None, 0).id, 3) + self.assertEqual(routing.routed_item(todo.replace(first, "") + first, NO_CUT).id, 3) def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self): - self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, None, 0)), Route(self.HIGH, 3, 4, 5)) - cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), None, 0) + self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.HIGH, 3, 4, 5)) + cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT) self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-haiku-5-5", "max"), 3, 1, 5)) self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS)) @@ -688,7 +691,7 @@ class Routing(unittest.TestCase): def test_routes_nothing_on_an_item_without_e_or_i(self): without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") - self.assertIsNone(routing.routed_item(without_i, None, 0)) + self.assertIsNone(routing.routed_item(without_i, NO_CUT)) def test_archives_the_route_in_a_line_it_reads_back(self): route = Route(self.HIGH, 3, 4, 5) @@ -714,7 +717,7 @@ class Routing(unittest.TestCase): def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): def run_with(route=None): return main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=route) - item = routing.routed_item(TODO, None, 0) + item = routing.routed_item(TODO, NO_CUT) archived = Route(self.XHIGH, 3, 4, 5) def never(): raise AssertionError("not asked") @@ -730,11 +733,11 @@ class Routing(unittest.TestCase): class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - self.assertIsNone(main.plan_item(DefaultPlan("origin/main", "", None, 0))) - self.assertEqual(main.plan_item(DefaultPlan("origin/main", TODO, "v0.1.0", 3)).id, 3) - self.assertIsNone(main.plan_item(DefaultPlan("origin/main", TODO, "v0.2.0", 3))) + self.assertIsNone(main.plan_item(DefaultPlan("origin/main", "", NO_CUT))) + self.assertEqual(main.plan_item(DefaultPlan("origin/main", TODO, LastCut("v0.1.0", "", 3, [TODO]))).id, 3) + self.assertIsNone(main.plan_item(DefaultPlan("origin/main", TODO, LastCut("v0.2.0", "", 3, [TODO])))) unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8") - for plan, said in ((DefaultPlan("origin/main", TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), None, 0), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan("origin/main", unreadable, None, 0), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): + for plan, said in ((DefaultPlan("origin/main", TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan("origin/main", unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): with self.subTest(said=said): with contextlib.redirect_stderr(io.StringIO()) as stderr: self.assertIsNone(main.plan_item(plan)) diff --git a/bin/test_git_repo.py b/bin/test_git_repo.py index 45c55c1e..0d32f6f7 100644 --- a/bin/test_git_repo.py +++ b/bin/test_git_repo.py @@ -1,27 +1,41 @@ +import contextlib import pathlib +import subprocess import sys +import tempfile +import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from failure import Failure -from git_repo import git +import git_repo -class Git(unittest.TestCase): - # Each command is a shell alias, so it touches no repository, whatever GIT_DIR the test runs under. +class StalledOrigin(unittest.TestCase): + """A checkout whose origin, run through git's ext transport, answers nothing for 10 s, and which records no default branch for it.""" - def test_stops_git_still_running_after_the_timeout_and_says_so(self): - done = git("-c", "alias.hang=!sleep 5", "hang", timeout=0.2) - self.assertIsInstance(done, Failure) - self.assertIn("hang", done.reason) - self.assertIn("0.2 s", done.reason) + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = temp.name + for args in (("init", "--quiet"), ("config", "protocol.ext.allow", "always"), ("remote", "add", "origin", "ext::sleep 10")): + subprocess.run(["git", *args], capture_output=True, check=True, cwd=self.root) - def test_says_git_printed_text_that_is_not_utf_8(self): - done = git("-c", "alias.latin=!printf 'caf\\351'", "latin") - self.assertIsInstance(done, Failure) - self.assertIn("latin", done.reason) - self.assertIn("UTF-8", done.reason) + def test_reading_the_default_branch_fails_after_the_timeout(self): + started = time.monotonic() + ref = git_repo.default_ref(self.root, 0.5) + self.assertLess(time.monotonic() - started, 5) + self.assertIsInstance(ref, Failure) + self.assertIn("stopped after 0.5 s", ref.reason) + + def test_fetching_the_default_branch_fails_after_the_timeout(self): + started = time.monotonic() + with contextlib.chdir(self.root): + found = git_repo.default_branch(stale_ok=True, timeout=0.5) + self.assertLess(time.monotonic() - started, 5) + self.assertIsInstance(found, Failure) + self.assertIn("stopped after 0.5 s", found.reason) if __name__ == "__main__": diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index f01c1e3c..f81255e6 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -416,28 +416,43 @@ class Blockers(unittest.TestCase): class Standing(unittest.TestCase): - def test_takes_the_earliest_release_where_it_is_the_next_patch_minor_or_major_or_no_tag_names_a_version(self): + def test_takes_the_earliest_release_where_it_is_the_earliest_named_since_the_last_cut(self): cases = ( - ("v1.2.3", 4, (1, 2, 4), "next"), - ("v1.2.3", 4, (1, 3, 0), "next"), - ("v1.2.3", 4, (2, 0, 0), "next"), - (None, 4, (0, 2, 0), "next"), - (None, 4, None, "next"), - ("v1.2.3-rc.1", 4, (1, 2, 3), "next"), - (Failure("tags unreadable"), 4, (0, 2, 0), "next"), - ("v1.2.3", 4, (1, 2, 3), "cut"), - ("v1.2.3", 4, (1, 2, 2), "cut"), - ("v1.2.3", 4, (1, 2, 5), "finished"), - ("v1.2.3", 4, (1, 3, 1), "finished"), - ("v1.2.3", 4, (2, 0, 1), "finished"), - ("v1.2.3", 4, None, "finished"), - ("v1.2.3", 0, (1, 4, 0), "unplanned"), - ("v1.2.3", 0, None, "unplanned"), - ("v1.2.3", Failure("count unreadable"), (1, 4, 0), "unknown"), + ("v1.2.3", 4, (1, 2, 4), set(), "next"), + ("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, "next"), + ("v0.2.0", 4, (0, 4, 0), set(), "next"), + (None, 4, (0, 2, 0), set(), "next"), + (None, 4, None, set(), "next"), + ("v1.2.3-rc.1", 4, (1, 2, 3), set(), "next"), + (Failure("tags unreadable"), 4, (0, 2, 0), set(), "next"), + ("v1.2.3", 4, (1, 2, 3), set(), "cut"), + ("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, "cut"), + ("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, "finished"), + ("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, "finished"), + ("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, "finished"), + ("v1.2.3", 4, None, {(1, 3, 0)}, "finished"), + ("v1.2.3", 4, None, set(), "finished"), + ("v1.2.3", 0, (1, 3, 0), {(1, 2, 4)}, "unplanned"), + ("v1.2.3", 0, None, set(), "unplanned"), + ("v1.2.3", Failure("count unreadable"), None, set(), "unknown"), ) - for tag, commits, earliest, stands in cases: - with self.subTest(tag=tag, commits=commits, earliest=earliest): - self.assertEqual(todo_table.standing(tag, commits, earliest), stands) + for tag, landed, earliest, named, stands in cases: + with self.subTest(tag=tag, landed=landed, earliest=earliest, named=named): + self.assertEqual(todo_table.standing(tag, landed, earliest, named), stands) + + def test_counts_work_landed_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self): + changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" + self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", changelog, 5, [])), 2) + self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", "# Changelog\n\n## Unreleased\n\n## 0.1.0\n", 5, [])), 0) + self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", "# Changelog\n\n## 0.1.0\n", 5, [])), 5) + self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", Failure("unreadable"), 5, [])), 5) + + def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self): + row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" + header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" + texts = [header + row.format(id=1, release="0.2.0"), "", "not a table | x |", header + row.format(id=2, release="0.3.0")] + self.assertEqual(todo_table.named_releases(texts), {(0, 2, 0), (0, 3, 0)}) + self.assertEqual(todo_table.named_releases(Failure("log unreadable")), set()) class Main(unittest.TestCase): diff --git a/bin/todo_table.py b/bin/todo_table.py index c41376cf..bb3ea8c2 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -3,7 +3,7 @@ import re import typing from failure import Failure -from markdown_text import FENCE +from markdown_text import FENCE, sections # Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level. TOP_SCORE = 10 @@ -17,8 +17,8 @@ BLOCKED_BY = "Blocked by" MOVES = "Moves" # How the items table's header opens, which tells it from any other table in todo.md. HEADER_START = "| ID | Release |" -# How the plan's earliest release stands to the version x.y.z the newest tag names. "next": it is x.y.z+1, x.y+1.0 or x+1.0.0, or no tag names a version. "cut": it is x.y.z or earlier. -# Else the release after the tag holds no item: "finished" where commits followed the tag, "unplanned" where none did, and "unknown" where they cannot be counted. +# How the plan's earliest release stands to the version x.y.z the newest tag names, the last cut. "next": it is the earliest release after x.y.z that todo.md has named since the cut, or no tag names a version. "cut": it is x.y.z or earlier. +# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, "unplanned" where none did, and "unknown" where that cannot be read. Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] # todo.md's ## Details section, its body the first group. DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) @@ -176,24 +176,55 @@ def next_item(found: list[Item]) -> Item | None: return next((item for item in found if item.release == release and item.id not in waits), None) -def standing(tag: str | None | Failure, commits: int | Failure, earliest: tuple[int, int, int] | None) -> Standing: - """How the plan's earliest release, None where the plan holds no item, stands to the newest v* tag, as Standing says; commits counts those after the tag.""" +@dataclasses.dataclass(frozen=True) +class LastCut: + """What the default branch holds about its last release, which chunk_item weighs the plan against.""" + # The newest v* tag, None where the branch has none. + tag: str | None | Failure + # CHANGELOG.md's text, empty where the branch holds none. + changelog: str | Failure + # How many commits follow the tag, or make up the branch where it has none. + commits: int | Failure + # todo.md's text at the tag and at each later commit that changed it; empty without a tag. + todos_since: list[str] | Failure + + +def unreleased_entries(changelog: str) -> int | None: + """How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section.""" + found = sections(changelog).get("Unreleased") + return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines()) + + +def landed(cut: LastCut) -> int | Failure: + """How much work has landed since the last cut: the entries under ## Unreleased, or the commits since the tag where CHANGELOG.md has no such section, as `~/.claude/CLAUDE.md` → "Working loop" counts unreleased changes.""" + entries = unreleased_entries(cut.changelog) if isinstance(cut.changelog, str) else None + return cut.commits if entries is None else entries + + +def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]]: + """Each release the todo.md texts file items under. A text that does not parse names none, and so does a history that cannot be read, which leaves the plan's earliest release as the next.""" + found = [items(todo) for todo in todos] if isinstance(todos, list) else [] + return {item.release for parsed in found if isinstance(parsed, list) for item in parsed} + + +def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[int, int, int] | None, named: set[tuple[int, int, int]]) -> Standing: + """How the plan's earliest release, None where the plan holds no item, stands to the newest v* tag, as Standing says. named holds each release todo.md named since that tag, and landed the work landed since it.""" cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None if cut is None: return "next" - major, minor, patch = (int(part) for part in cut.groups()) - if earliest in ((major, minor, patch + 1), (major, minor + 1, 0), (major + 1, 0, 0)): - return "next" - if earliest is not None and earliest <= (major, minor, patch): + version = tuple(int(part) for part in cut.groups()) + if earliest is not None and earliest <= version: return "cut" - if isinstance(commits, Failure): + if earliest is not None and earliest == min(release for release in named | {earliest} if release > version): + return "next" + if isinstance(landed, Failure): return "unknown" - return "finished" if commits else "unplanned" + return "finished" if landed else "unplanned" -def chunk_item(found: list[Item], tag: str | None | Failure, commits: int | Failure) -> tuple[Standing, Item | None]: +def chunk_item(found: list[Item], cut: LastCut) -> tuple[Standing, Item | None]: """The item the next chunk takes first, next_item's pick, where standing finds the plan's earliest release the next; else None. Routing and chunk-preflight both pick with it, so they name one item; standing comes with it, so a caller can say why there is none.""" - stands = standing(tag, commits, min((item.release for item in found), default=None)) + stands = standing(cut.tag, landed(cut), min((item.release for item in found), default=None), named_releases(cut.todos_since)) return stands, next_item(found) if stands == "next" else None diff --git a/todo.md b/todo.md index 2d7cb57e..5719c9c6 100644 --- a/todo.md +++ b/todo.md @@ -38,7 +38,7 @@ | 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 | | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | -| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds and unfinished verdicts, and file an item where the preflight did not pay.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | +| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds, unfinished verdicts and 🔴 findings, and file an item where the preflight did not pay.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -205,9 +205,9 @@ lilleman asked, on 2026-10-16, for a standing audit each release, so the loop ke The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it. -### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds and unfinished verdicts, and file an item where the preflight did not pay. +### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds, unfinished verdicts and 🔴 findings, and file an item where the preflight did not pay. -Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure goal 1.4's counter-signal beside them, review rounds and unfinished verdicts per chunk, since a worker that reads less may start sooner and need more rounds. Where time or tokens did not fall, or rounds or unfinished verdicts rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. +Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. -- 2.52.0 From ec86fee39f8fd5a00be28cc1255a612e2073865e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:34:15 +0200 Subject: [PATCH 12/22] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20answered=20in=20the=20stabi?= =?UTF-8?q?lity=20round=202=20commit:=20read=20the=20default=20branch=20on?= =?UTF-8?q?ce,=20and=20add=20=F0=9F=94=B4=20findings=20to=20item=20175's?= =?UTF-8?q?=20counter-signals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From c89dd87a188187e0ff5d688fcb434de11a5ab081 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:34:15 +0200 Subject: [PATCH 13/22] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20answered=20in=20the=20st?= =?UTF-8?q?ability=20round=202=20commit:=20count=20work=20landed=20by=20th?= =?UTF-8?q?e=20Unreleased=20entries=20before=20commits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 46ccea132227ff7380bc5f1ae8420267e7e1f0ac Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:50:29 +0200 Subject: [PATCH 14/22] =?UTF-8?q?Answer=20stability=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1;=20test=20todo.md=20at=20the?= =?UTF-8?q?=20cut,=20before=20it=20and=20on=20a=20merged=20side=20branch?= =?UTF-8?q?=20through=20real=20git,=20count=20only=20the=20default=20branc?= =?UTF-8?q?h's=20own=20commits=20since=20the=20cut,=20test=20a=20cut=20rel?= =?UTF-8?q?ease=20named=20at=20the=20tag,=20restore=20the=20UTF-8=20and=20?= =?UTF-8?q?timeout=20tests=20of=20git,=20and=20drop=20the=20wall-clock=20a?= =?UTF-8?q?sserts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/gathered.py | 2 +- bin/chunk_preflight/test_chunk_preflight.py | 36 ++++++++++++++++++++- bin/git_repo.py | 4 +-- bin/test_git_repo.py | 21 +++++++++--- bin/test_rank_todo.py | 5 ++- bin/todo_table.py | 16 +++++---- 6 files changed, 68 insertions(+), 16 deletions(-) diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 2b582b66..248f0ae4 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -101,7 +101,7 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: if stands == "unplanned": return NoItem(f"{gap} no work has landed since, so that release is to be planned first.") if stands == "unknown": - return NoItem(f"{gap} the work landed since it cannot be counted.") + return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: what todo.md named, or the work landed, since then cannot be read. Find the next release yourself.") if first is None: return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.") details = item_details(todo) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index dc785be4..0c8e9efa 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -166,6 +166,37 @@ class ChunkPreflightTool(unittest.TestCase): self.assertNotIn("item 9", done.stdout) self.assertFalse((repo.temp / "proj-item-9").exists()) + def test_weighs_todo_md_at_the_last_cut_and_on_the_default_branch_after_it_alone(self): + """Each case's plans: before the tag, at it, on a side branch merged after it, and after it, each committed in turn where given.""" + cases = ( + ("a release named only before the cut", TODO, LATER, None, None, "item 9"), + ("a release named at the cut", None, TODO, None, LATER, "finished and ready to cut"), + ("a release named only on a side branch", None, LATER, TODO, None, "item 9"), + ) + for name, before, at, side, after, fact in cases: + with self.subTest(name): + repo = Repo(self, todo="") + for todo, title in ((before, "before"), (at, "at")): + if todo is not None: + repo.write(repo.root, "todo.md", todo) + repo.commit(repo.root, title) + repo.git(repo.root, "tag", "--force", "v0.1.0") + if side is not None: + repo.git(repo.root, "switch", "--quiet", "-c", "side") + # The branch ends on a plan main never held, so the merge changes todo.md. + for todo in (side, LATER + "| 10 | 0.3.0 | | | **Do another later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"): + repo.write(repo.root, "todo.md", todo) + repo.commit(repo.root, "side") + repo.git(repo.root, "switch", "--quiet", "main") + repo.git(repo.root, "merge", "--quiet", "--no-ff", "-m", "merge side", "side") + if after is not None: + repo.write(repo.root, "todo.md", after) + repo.commit(repo.root, "after") + repo.git(repo.root, "push", "--quiet", "--force", "origin", "main", "v0.1.0") + done = repo.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn(fact, done.stdout) + def test_continues_the_items_worktree_and_else_its_pushed_branch(self): repo = Repo(self) repo.preflight() @@ -383,7 +414,7 @@ class Plans(unittest.TestCase): (LATER, 0, "planned first"), (EMPTY, 4, "finished and ready to cut"), (EMPTY, 0, "planned first"), - (LATER, Failure("count unreadable"), "cannot be counted"), + (LATER, Failure("count unreadable"), "cannot be read"), ) for todo, commits, fact in cases: with self.subTest(todo=todo, commits=commits): @@ -391,6 +422,9 @@ class Plans(unittest.TestCase): self.assertIn(fact, why) self.assertIn("v0.1.0", why) + def test_says_what_todo_md_named_since_the_last_cut_cannot_be_read(self): + self.assertIn("cannot be read", planned(LATER, LastCut("v0.1.0", "", 4, Failure("log unreadable")), "origin/main").why) + def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self): self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main").first.id, 9) diff --git a/bin/git_repo.py b/bin/git_repo.py index d776eb9f..aa9e8496 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -79,10 +79,10 @@ def default_plan(root: str, ref: str) -> DefaultPlan: def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure: - """todo.md's text at tag and at each later commit on ref that changed it, read in cwd; empty where there is no tag.""" + """todo.md's text at tag and at each later commit on ref that changed it, read in cwd; empty where there is no tag. A pull request's own commits do not count, only the merge that landed it: --first-parent.""" if not isinstance(tag, str): return [] - changed = git("log", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd) + changed = git("log", "--first-parent", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd) if isinstance(changed, Failure): return changed texts = [] diff --git a/bin/test_git_repo.py b/bin/test_git_repo.py index 0d32f6f7..291509a4 100644 --- a/bin/test_git_repo.py +++ b/bin/test_git_repo.py @@ -3,7 +3,6 @@ import pathlib import subprocess import sys import tempfile -import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) @@ -12,6 +11,22 @@ from failure import Failure import git_repo +class Git(unittest.TestCase): + # Each command is a shell alias, so it touches no repository, whatever GIT_DIR the test runs under. + + def test_stops_git_still_running_after_the_timeout_and_says_so(self): + done = git_repo.git("-c", "alias.hang=!sleep 5", "hang", timeout=0.2) + self.assertIsInstance(done, Failure) + self.assertIn("hang", done.reason) + self.assertIn("0.2 s", done.reason) + + def test_says_git_printed_text_that_is_not_utf_8(self): + done = git_repo.git("-c", "alias.latin=!printf 'caf\\351'", "latin") + self.assertIsInstance(done, Failure) + self.assertIn("latin", done.reason) + self.assertIn("UTF-8", done.reason) + + class StalledOrigin(unittest.TestCase): """A checkout whose origin, run through git's ext transport, answers nothing for 10 s, and which records no default branch for it.""" @@ -23,17 +38,13 @@ class StalledOrigin(unittest.TestCase): subprocess.run(["git", *args], capture_output=True, check=True, cwd=self.root) def test_reading_the_default_branch_fails_after_the_timeout(self): - started = time.monotonic() ref = git_repo.default_ref(self.root, 0.5) - self.assertLess(time.monotonic() - started, 5) self.assertIsInstance(ref, Failure) self.assertIn("stopped after 0.5 s", ref.reason) def test_fetching_the_default_branch_fails_after_the_timeout(self): - started = time.monotonic() with contextlib.chdir(self.root): found = git_repo.default_branch(stale_ok=True, timeout=0.5) - self.assertLess(time.monotonic() - started, 5) self.assertIsInstance(found, Failure) self.assertIn("stopped after 0.5 s", found.reason) diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index f81255e6..18a6ccb3 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -420,6 +420,7 @@ class Standing(unittest.TestCase): cases = ( ("v1.2.3", 4, (1, 2, 4), set(), "next"), ("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, "next"), + ("v1.2.3", 4, (1, 3, 0), {(1, 2, 3), (1, 3, 0)}, "next"), ("v0.2.0", 4, (0, 4, 0), set(), "next"), (None, 4, (0, 2, 0), set(), "next"), (None, 4, None, set(), "next"), @@ -435,6 +436,8 @@ class Standing(unittest.TestCase): ("v1.2.3", 0, (1, 3, 0), {(1, 2, 4)}, "unplanned"), ("v1.2.3", 0, None, set(), "unplanned"), ("v1.2.3", Failure("count unreadable"), None, set(), "unknown"), + ("v1.2.3", 4, (1, 3, 0), Failure("log unreadable"), "unknown"), + ("v1.2.3", 4, (1, 2, 3), Failure("log unreadable"), "cut"), ) for tag, landed, earliest, named, stands in cases: with self.subTest(tag=tag, landed=landed, earliest=earliest, named=named): @@ -452,7 +455,7 @@ class Standing(unittest.TestCase): header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" texts = [header + row.format(id=1, release="0.2.0"), "", "not a table | x |", header + row.format(id=2, release="0.3.0")] self.assertEqual(todo_table.named_releases(texts), {(0, 2, 0), (0, 3, 0)}) - self.assertEqual(todo_table.named_releases(Failure("log unreadable")), set()) + self.assertEqual(todo_table.named_releases(Failure("log unreadable")), Failure("log unreadable")) class Main(unittest.TestCase): diff --git a/bin/todo_table.py b/bin/todo_table.py index bb3ea8c2..c06fe5ec 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -18,7 +18,8 @@ MOVES = "Moves" # How the items table's header opens, which tells it from any other table in todo.md. HEADER_START = "| ID | Release |" # How the plan's earliest release stands to the version x.y.z the newest tag names, the last cut. "next": it is the earliest release after x.y.z that todo.md has named since the cut, or no tag names a version. "cut": it is x.y.z or earlier. -# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, "unplanned" where none did, and "unknown" where that cannot be read. +# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, and "unplanned" where none did. "unknown": what todo.md named, or the work landed, since the cut cannot be read. +# A release named since the cut stays the next until a tag cuts it, even once its items moved to a later release: larv_review/plan.py's emptied counts such a release emptied too, and `~/.claude/CLAUDE.md` → "Working loop" then stops for the human, or plans the release with their approval. Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] # todo.md's ## Details section, its body the first group. DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) @@ -201,13 +202,14 @@ def landed(cut: LastCut) -> int | Failure: return cut.commits if entries is None else entries -def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]]: - """Each release the todo.md texts file items under. A text that does not parse names none, and so does a history that cannot be read, which leaves the plan's earliest release as the next.""" - found = [items(todo) for todo in todos] if isinstance(todos, list) else [] - return {item.release for parsed in found if isinstance(parsed, list) for item in parsed} +def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]] | Failure: + """Each release the todo.md texts file items under; a text that does not parse names none.""" + if isinstance(todos, Failure): + return todos + return {item.release for parsed in map(items, todos) if isinstance(parsed, list) for item in parsed} -def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[int, int, int] | None, named: set[tuple[int, int, int]]) -> Standing: +def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[int, int, int] | None, named: set[tuple[int, int, int]] | Failure) -> Standing: """How the plan's earliest release, None where the plan holds no item, stands to the newest v* tag, as Standing says. named holds each release todo.md named since that tag, and landed the work landed since it.""" cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None if cut is None: @@ -215,6 +217,8 @@ def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[i version = tuple(int(part) for part in cut.groups()) if earliest is not None and earliest <= version: return "cut" + if isinstance(named, Failure): + return "unknown" if earliest is not None and earliest == min(release for release in named | {earliest} if release > version): return "next" if isinstance(landed, Failure): -- 2.52.0 From 33f9960c1e31f990b7a0ef69c77008d09328905b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:50:29 +0200 Subject: [PATCH 15/22] =?UTF-8?q?Answer=20principles=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1;=20answered=20in=20the=20stabi?= =?UTF-8?q?lity=20round=203=20commit,=20and=20a=20history=20that=20cannot?= =?UTF-8?q?=20be=20read=20now=20stops=20the=20pick=20as=20unknown;=20a=20r?= =?UTF-8?q?elease=20whose=20items=20moved=20on=20stays=20the=20next=20unti?= =?UTF-8?q?l=20cut,=20as=20larv=5Freview/plan.py=20counts=20it=20emptied,?= =?UTF-8?q?=20now=20said=20beside=20Standing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From f566d1ccd584e95ec0db82d2b3af885329bbd353 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 02:59:13 +0200 Subject: [PATCH 16/22] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2011=20=F0=9F=9F=A1;=20reword=20the=20preflight's?= =?UTF-8?q?=20help=20and=20its=20next-release=20bullet,=20give=20loop-clau?= =?UTF-8?q?de's=20help=20a=20preflight=20paragraph=20and=20a=20plainer=20r?= =?UTF-8?q?outing=20sentence,=20put=20the=20changelog=20entry's=20action?= =?UTF-8?q?=20first,=20correct=20two=20false=20claims=20in=20CLAUDE.md=20a?= =?UTF-8?q?nd=20a=20docstring,=20ease=20five=20comments=20and=20the=20unkn?= =?UTF-8?q?own=20line,=20and=20file=20item=20176=20to=20split=20loop-claud?= =?UTF-8?q?e's=20help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- CLAUDE.md | 2 +- bin/chunk_preflight/facts.py | 2 +- bin/chunk_preflight/gathered.py | 10 +++++----- bin/chunk_preflight/main.py | 32 ++++++++++++++++---------------- bin/git_repo.py | 2 +- bin/loop_claude/loop/main.py | 31 +++++++++++++++++-------------- bin/todo_table.py | 10 +++++----- skills/larv-review/SKILL.md | 2 +- todo.md | 13 +++++++++---- 10 files changed, 57 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20c94658..58e46866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ - `rule-hook` refuses an Agent call that launches a reviewer, a comprehension seat or the security pass on a rung below the one `loop-claude` names for it, and takes no override: pass the model and effort the refusal names. - `score-outcomes` lists a project's score anchors: the shipped items its `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured. `rules/todo-items.md` has a scorer compare a new item with them, and says how to choose two or three per level. Add the file to each project that merges with merge commits; elsewhere, score by the level descriptions in `rules/todo-items.md`. - `loop-claude` archives each judge reply it rejects in the chunk's `.outcomes.md`, with the reason and the reply as json. Before, such a reply reached only stderr, so a run that exited 1 overnight could not say what the judge had returned. stderr now prints only the reason; the reply is in outcomes.md. If archiving fails, `loop-claude` exits 1. -- The new `bin/chunk-preflight` finds a chunk's mechanical facts and makes its worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there. Before it routes each chunk, `loop-claude` runs it and quotes what it printed in the worker's first prompt. The preflight fetches origin and reads `todo.md` from its default branch, leaving the checkout as it is, and `loop-claude` routes on that same `todo.md`, so an edit to `todo.md` routes a chunk only once the default branch holds it. Its facts name the last release and the unreleased changes, the next item with its L, E + I and detail, the items that may join its chunk, the files the item names, the open pull requests, and what `rank_todo.py --check`, `larv-review needs-scoring-run`, `reading-cost` and `larv-review places` print. Where `todo.md` holds no item for the next release, the earliest it has named since the newest tag, it names no item and `loop-claude` routes on none; it says that release is finished and ready to cut where work has landed since the tag, or else is to be planned first. It stops a fetch, forge CLI or tool still running after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. Expect the worker to start editing sooner, and `docs/reading-cost.md` to hold an uncommitted figure in the new worktree for the chunk to commit. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. +- `loop-claude` routes each chunk on `todo.md` as the default branch holds it, freshly fetched: merge a `todo.md` edit before the chunk it should route starts. Where `todo.md` holds no item for the next release, the earliest release it has named since the newest tag, no item routes the chunk, and the worker is told that release is finished and ready to cut, or, where no work has landed since the tag, to be planned first. Before routing, `loop-claude` runs the new `bin/chunk-preflight` and quotes what it prints in the worker's first prompt: the chunk's mechanical facts, which `chunk-preflight --help` lists. The preflight also makes the chunk's worktree, `-item-` beside the checkout on the branch `item-`, or continues the one already there, and leaves an uncommitted figure in that worktree's `docs/reading-cost.md` for the chunk to commit. It stops a fetch, forge CLI or tool after 60 seconds, or after the seconds `CHUNK_PREFLIGHT_TIMEOUT` sets. The prompt also asks the worker to count the item's size again once it has read the code, and to have the item re-scored where its L would change. Expect the worker to start editing sooner. ## 0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md index 1753de5d..3da5ac51 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them. -- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the item's row and detail and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs. +- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs. - **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which four things hold: one PR title states what they achieve together, without listing them; they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open. - **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it. diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 8a6af2aa..0c10234c 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -55,7 +55,7 @@ def pulls_text(pulls: tuple[Forge, Ran | Failure] | None, branch: str) -> str: def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]: - """Each open pull request from branch in the rows pulls_command printed, as `# `: gh's rows are branch's, number and URL; tea's are every one's, index, head and URL, under a header row.""" + """Each open pull request from branch in the rows pulls_command printed, as `# `: gh prints only branch's pull requests, as number and URL; tea prints every pull request, as index, head and URL, under a header row.""" rows = [line.split("\t") for line in stdout.splitlines()] if forge == "gh": return [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2] diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 248f0ae4..407dfa3f 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -23,7 +23,7 @@ class Ran: @dataclasses.dataclass(frozen=True) class Plan: - """The default branch's todo.md items, and first, the item the next chunk takes first.""" + """The default branch's todo.md items, and `first`: the item the next chunk takes first.""" items: list[Item] first: Item # first's tagline and detail. @@ -82,7 +82,7 @@ class Gathered: def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: - """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick, which routing makes too; else why there is none.""" + """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick; else why there is none.""" where = f"{default}'s todo.md" if isinstance(todo, Failure): return NoItem(f"{where} cannot be read: {todo.reason}.") @@ -94,14 +94,14 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: earliest = min((item.release for item in found), default=None) stands, first = chunk_item(found, cut) if earliest is not None and stands == "cut": - return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}.") + return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.") gap = f"{where} holds no item for the next release after the last cut, {cut.tag}, and" if stands == "finished": return NoItem(f"{gap} work has landed since, so that release is finished and ready to cut, and the working loop stops here.") if stands == "unplanned": return NoItem(f"{gap} no work has landed since, so that release is to be planned first.") if stands == "unknown": - return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: what todo.md named, or the work landed, since then cannot be read. Find the next release yourself.") + return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of work landed since then, cannot be read. Find the next release yourself.") if first is None: return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.") details = item_details(todo) @@ -137,7 +137,7 @@ def forge_of(origin_url: str) -> Forge: def pulls_command(forge: Forge, branch: str) -> list[str]: - """The command that lists open pull requests, by number, head and URL. gh lists only branch's; tea lists every one, for facts.open_pulls to pick branch's.""" + """The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's.""" if forge == "gh": return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"] diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 844ff872..d97b1085 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -1,30 +1,30 @@ -"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker reads them rather than finding them. +"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker starts from them. usage: chunk-preflight Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that remote, and takes origin's default branch, or else the -local main or master, as larv-review does. It leaves the checkout as it is: it reads todo.md as -that branch holds it, the plan loop-claude routes on, and prints: +local main or master. It leaves the checkout as it is, and reads todo.md as the default branch +holds it, the plan loop-claude routes on. It prints: - the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how many commits followed the tag; -- the earliest release in todo.md, and that release's first item that does not wait, the item - loop-claude routes on, with its L and E + I. It names that item only where the tag names no - version x.y.z, or the release is the earliest after x.y.z that todo.md has named at the tag or - since: the next release. Where the next release holds no item, it says so: finished and ready to - cut where work landed since the tag, counted as the ## Unreleased entries or else the commits, and - else to be planned first. For x.y.z or an earlier release, it says todo.md files items under a - release already cut; +- the next release and its first item that does not wait, the item loop-claude routes on, with + its L and E + I. An item waits while it is marked question, or while an item still in todo.md + blocks it. Where the newest tag names a version x.y.z, the next release is the earliest after + x.y.z that todo.md has named at that tag or since; otherwise it is todo.md's earliest release. + Where the next release holds no item, it says so: finished and ready to cut where work landed + since the tag (the ## Unreleased entries, or else the commits), and else to be planned first. + Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release + already cut; - the item's worktree: a sibling of the checkout named -item-, on the branch item-. It continues a worktree already on that branch; else it adds one on the local branch, else on a new branch tracking origin's, else on a new branch off the default branch; - the open pull requests whose head is the item's branch, each by its number and URL, as gh lists - them on a github.com origin, and else as tea does. No title reaches the output: on a public forge, - anyone may open a pull request, and its title would reach the worker's prompt; -- the items of that release that a chunk taking the item may take too: none is a question, and no - item outside them and the item blocks one; + them on a github.com origin, and else as tea does. No title reaches the output; +- the items of that release that a chunk taking the item may take too: those that are not + questions and that no item outside the chunk blocks; - each file or folder git tracks that the item's tagline or detail names in backticks, with a file's lines or a folder's files, and the item's tagline and detail; - what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run `, `reading-cost` and @@ -53,7 +53,7 @@ from chunk_preflight.facts import render BIN = pathlib.Path(__file__).resolve().parents[1] # Each tool run in the item's worktree, {item} standing for the item's ID. TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places")) -# Seconds before a fetch, forge CLI or tool is stopped, so a hung one leaves the facts the others find; TIMEOUT_SETTING sets others. +# Seconds before a fetch, forge CLI or tool is stopped, so a hung one cannot keep the rest from printing; TIMEOUT_SETTING overrides it. TIMEOUT = 60 TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT" @@ -83,7 +83,7 @@ def run(setting: str | None) -> list[str] | Failure: def seconds(setting: str | None) -> float | Failure: - """The seconds a TIMEOUT_SETTING of setting gives, TIMEOUT where it is unset; a Failure where it is no number above 0.""" + """The timeout setting as seconds, TIMEOUT where unset; a Failure where it is no number above 0.""" if setting is None: return TIMEOUT if re.fullmatch(r"[0-9]+(\.[0-9]+)?", setting) and float(setting) > 0: diff --git a/bin/git_repo.py b/bin/git_repo.py index aa9e8496..0c65933c 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -26,7 +26,7 @@ def top() -> str | Failure: def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, str | None] | Failure: - """The default branch's ref, as default_ref names it after a fetch where the checkout has an origin remote, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so. A call to origin still running after timeout seconds fails.""" + """The default branch's ref, as default_ref names it after a fetch where the checkout has an origin remote, and a note on why origin reads as last fetched. With stale_ok, a failed fetch reads origin as last fetched, and the note says so. A call to origin still running after timeout seconds fails.""" remotes = git("remote") if isinstance(remotes, Failure): return remotes diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index d47a3cba..a9860928 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -5,13 +5,9 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md -items, or else the task, and never widen them. As a chunk starts, before it is routed, loop-claude -runs bin/chunk-preflight (bin/chunk_preflight/), which finds the chunk's facts and makes its -worktree; chunk-preflight --help lists them, and prompts.preflight_facts in -bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A preflight that fails, or is -still running after 600 s and is stopped, leaves the worker to find the facts itself. A judge then -reads the transcript's end, the premises, and the records: the project's AGENTS.md and -docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and +items, or else the task, and never widen them. A judge then reads the transcript's end, the +premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's +~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker @@ -27,6 +23,12 @@ its session next cycle, and the worker is shown the passage the judge quoted as The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". +As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/), +which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and +prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A +preflight that fails, or is still running after 600 s and is stopped, leaves the worker to find the +facts itself. + Each project has one session, named "A loop-claude", where is the checkout's path relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is @@ -49,11 +51,12 @@ run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_ for the worker and the interrupt; with both set, nothing is asked. Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the -interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, todo.md on the -default branch, as chunk-preflight has just fetched it, routes it on the item the preflight names -(todo_table.chunk_item): the earliest release's top item that does not wait, where that release is -the next, the earliest after the newest v* tag that todo.md has named since that tag, or there is no -such tag; else no item routes it. An item waits while it is marked +interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is routed +on the item chunk-preflight names, read from todo.md on the default branch as the preflight just +fetched it (todo_table.chunk_item). That item is the earliest release's top item that does not wait, +but only where that release is the next one: the earliest after the newest vX.Y.Z tag that todo.md +has named at that tag or since, or any earliest release where no tag names a version. Otherwise no +item routes the chunk. An item waits while it is marked question, or while an item that blocks it is still in the table. The item's L picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I @@ -175,7 +178,7 @@ from model_routing.route import Route, route_from from claude_code.session import Session, session_named, session_open, transcript_file from loop_claude.stop import Stop -# Seconds before routing gives up asking origin for its default branch, which it asks only where the checkout records none, and routes on the project's rung. +# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung. ORIGIN_TIMEOUT = 60 @@ -278,7 +281,7 @@ def fetched_plan(root: str) -> DefaultPlan | Failure: def plan_item(plan: DefaultPlan | Failure) -> Item | None: - """The item that routes a chunk, from the default branch as git_repo.default_plan reads it, as chunk-preflight does, so both take todo_table.chunk_item's pick. None without one, so the chunk runs on the project's rung.""" + """The item that routes a chunk, todo_table.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung.""" if isinstance(plan, Failure): item: Item | Failure | None = plan elif isinstance(plan.todo, Failure): diff --git a/bin/todo_table.py b/bin/todo_table.py index c06fe5ec..ecb03532 100644 --- a/bin/todo_table.py +++ b/bin/todo_table.py @@ -17,9 +17,9 @@ BLOCKED_BY = "Blocked by" MOVES = "Moves" # How the items table's header opens, which tells it from any other table in todo.md. HEADER_START = "| ID | Release |" -# How the plan's earliest release stands to the version x.y.z the newest tag names, the last cut. "next": it is the earliest release after x.y.z that todo.md has named since the cut, or no tag names a version. "cut": it is x.y.z or earlier. -# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, and "unplanned" where none did. "unknown": what todo.md named, or the work landed, since the cut cannot be read. -# A release named since the cut stays the next until a tag cuts it, even once its items moved to a later release: larv_review/plan.py's emptied counts such a release emptied too, and `~/.claude/CLAUDE.md` → "Working loop" then stops for the human, or plans the release with their approval. +# How the plan's earliest release stands to the version x.y.z the newest tag names, the last cut. "next": it is the earliest release after x.y.z that todo.md has named at that tag or since, or no tag names a version, or the tag cannot be read. "cut": it is x.y.z or earlier. +# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, and "unplanned" where none did. "unknown": todo.md's texts since the cut, or the count of work landed since it, cannot be read. +# A release named since the cut stays the next until a tag cuts it, even once its items moved to a later release, as larv_review/plan.py's emptied counts such a release emptied too. Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"] # todo.md's ## Details section, its body the first group. DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S) @@ -169,7 +169,7 @@ def waiting(found: list[Item], done: set[int]) -> set[int]: def next_item(found: list[Item]) -> Item | None: - """The earliest release's first row that does not wait, as waiting says, in the table's order: the item the next chunk takes first.""" + """The earliest release's first row that does not wait, as waiting says, in the table's order; chunk_item takes it as the next chunk's first item where its release is the next.""" if not found: return None release = min(item.release for item in found) @@ -227,7 +227,7 @@ def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[i def chunk_item(found: list[Item], cut: LastCut) -> tuple[Standing, Item | None]: - """The item the next chunk takes first, next_item's pick, where standing finds the plan's earliest release the next; else None. Routing and chunk-preflight both pick with it, so they name one item; standing comes with it, so a caller can say why there is none.""" + """The item the next chunk takes first, next_item's pick, where standing finds the plan's earliest release the next; else None. Routing and chunk-preflight both pick with it, so they name one item. It returns the standing too, so a caller can say why there is none.""" stands = standing(cut.tag, landed(cut), min((item.release for item in found), default=None), named_releases(cut.todos_since)) return stands, next_item(found) if stands == "next" else None diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 17f1cffd..3c7e1378 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -24,7 +24,7 @@ The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.m Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary. -**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree, unless loop-claude's prompt already shows its output there, and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it. +**Reading cost.** Run `~/.claude/bin/reading-cost` in the chunk's worktree, unless loop-claude's prompt shows that `chunk-preflight` already ran it there, and commit what it appends to `docs/reading-cost.md`; the commit re-enters no pass. Resolve a merge conflict in that file by putting the default branch's figures first and dropping a figure for a chunk the default branch already holds. On `Rising:`, file a plan item titled `**Lower the reading cost of the files a chunk reads most before its first commit.**`, scored per `~/.claude/rules/todo-items.md` with the tool's medians and files as its detail; where the plan already holds it, refresh its detail instead. The item names the next release, or the one after when this chunk ships the next release's last item. On exit 1, repair what its message names and run it again; when the message names no repair, file it as a `question` item, or refresh the question item an earlier run filed, and go on. Leave the plan as it is on any other output. The chunk that ships that item runs the tool with `--reset` instead, so the next rise is measured on chunks that finished after it. ## 3. Passes diff --git a/todo.md b/todo.md index 5719c9c6..b6bb1d89 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 176` +`Next ID = 177` ## Items @@ -34,11 +34,12 @@ | 157 | 0.3.0 | | | **Split `docs/decisions.md` → `todo.md: one table of items …`'s 2026-10-02 paragraph into one paragraph per choice.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 | | 106 | 0.3.0 | | | **Make larv-review's "Do not over-read a clean result" cite a rule that says Renovate or Dependabot owns dependency CVEs, or drop the citation.** | 1 | 2 | 1 | 2 | 1 | 1.1 by 5 | 10.9 | | 167 | 0.3.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 7.3 | +| 176 | 0.3.0 | | | **Give `loop-claude --help`'s routing paragraph sub-headings, such as Routing, Judge rung and Routing figures, so a reader finds a rule without reading 39 lines.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 7.3 | | 172 | 0.3.0 | | | **Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.** | 2 | 1 | 3 | 4 | 3 | 1.1 by 3, 1.4 by 3 | 6.2 | | 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 | | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | -| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds, unfinished verdicts and 🔴 findings, and file an item where the preflight did not pay.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | +| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -187,6 +188,10 @@ Found by the goals audit of PR #245. `skills/larv-review/SKILL.md` §3 → "Secu rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invokes `/security-review` in its own context, instead of in a subagent, runs the pass on its own rung, and nothing blocks it. Check Skill calls too: `breaches_of` in bin/rule_hook/main.py takes a Skill call whose skill is `security-review` or `claude-security` as a review launch, and settings.json's PreToolUse matcher gains Skill. Found by the systems-architect's review of PR #295. +### 176. Give `loop-claude --help`'s routing paragraph sub-headings, such as Routing, Judge rung and Routing figures, so a reader finds a rule without reading 39 lines. + +Raised by the prose pass of PR #302: the help, the docstring of `bin/loop_claude/loop/main.py`, is 145 lines, and its routing paragraph one block of 39, from the ladder through the judge's rung to the routing figures. A reader looking for one rule, such as when the worker steps up, reads it all. The comprehension seats already found the help hard (`larv-review places`: "loop-claude --help": a 120-line contract with no pointers to the modules it maps onto). + ### 172. Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it. The architecture pass of PR #296 found one rung under two names: `bin/model_routing/ladder.py` calls it `project`, while `bin/loop_claude/routing.py`, `cycle/prompts.py`, `cycle/run.py`'s `Cycle.anchor` and `loop/main.py` call it `anchor`, and gloss it as "anchor, the project's rung" in docstring after docstring. A reader works out that the two are one rung each time. Make `bin/loop_claude/routing.py`'s `first_route` easier to read. @@ -205,9 +210,9 @@ lilleman asked, on 2026-10-16, for a standing audit each release, so the loop ke The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it. -### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, by time and fresh tokens before the first edit and by review rounds, unfinished verdicts and 🔴 findings, and file an item where the preflight did not pay. +### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off. -Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. In item 140's chunk, before it, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. +Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. -- 2.52.0 From e40e57c46ec4f749801463bcdf69d34f677b6da6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 03:10:39 +0200 Subject: [PATCH 17/22] Record the comprehension check: paired ruling same against 46b79e7 --- docs/comprehension-history.md | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 574c6d0a..b2963354 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -2060,3 +2060,46 @@ Inherited architect, decided by: - Navigation, Self-sufficiency: `bin/loop_claude/cycle/run.py:122` `keep_rejection`: a loop that exits 1 after a rejected judge reply now leads to the archived reply, named like `keep_answer` - Self-sufficiency, Navigation: `workflow-bench/review_git.py:1` module docstring: explains the rule syntax and what the wrapper checks inline - Self-sufficiency: `bin/loop_claude/routing.py:84` `judge_rung`: points to `reviewed_on` in place of a plan item + +## 2026-10-17T01:10:16Z, PR #302 at f566d1c, against 46b79e7 + +Ruling: same + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | better | same | worse | same | same | +| Inherited architect | same | worse | worse | same | worse | +| Maintainability senior | better | same | same | same | same | +| Junior A | same | worse | worse | same | worse | + +Mid A, decided by: + +- Navigation: `bin/loop_claude/loop/main.py:26` `__doc__`: loop-claude's help names `bin/chunk-preflight`, says it runs before routing and points to `prompts.preflight_facts`, so the worker's starting facts lead straight to the file and function +- Navigation: `bin/todo_table.py:229` `chunk_item`: the next chunk's item is picked in one named function both routing and chunk-preflight use, where 46b79e7 wrote it out inside `routed_item` +- Navigation: `bin/chunk_preflight/main.py:94` `preflight`: the tool splits into main (effects), gathered (data and pure choices) and facts (wording), so a wrong printed line leads to `facts.py` and a wrong worktree choice to `gathered.worktree_add` +- Shape: `bin/todo_table.py:212` `standing`: the items-table parser now also holds release policy (`LastCut`, CHANGELOG counting, a five-state standing, bundling), so its name no longer tells the truth, and the `min(... named | {earliest} ...)` test is the densest reading in the change +- Shape: `bin/git_repo.py:74` `default_plan`: the git wrapper imports the plan model and builds a `LastCut`, so a low-level module depends on a higher-level one + +Inherited architect, decided by: + +- Locality: `bin/loop_claude/loop/main.py:217` `run_loop`: routing must run after the chunk-preflight subprocess, reading the plan as its fetch left it; only a comment guards that order, and a resumed session skips the preflight, where 46b79e7 read the working tree's todo.md in place +- Locality: `bin/chunk_preflight/main.py:94` `preflight`: some git calls take the checkout explicitly and others rely on the process's working directory, so seeing that they hit one repo needs how loop-claude launches the tool +- Locality, Shape: `bin/git_repo.py:65` `DefaultPlan`: the git plumbing module now knows todo.md and CHANGELOG.md and imports the plan model, so its name no longer says what it holds +- Shape, Locality: `bin/todo_table.py:212` `standing`: the table parser has taken on release policy that depends on todo.md texts back to the last tag; picking the routed item now runs through four modules, and the key test only makes sense beside the three-line `Standing` comment +- Locality: `bin/loop_claude/cycle/run.py:28` `Cycle.facts`: the first prompt names the chunk's item twice, from routing and from the preflight's facts, which agree only because both call `chunk_item` and nothing lands on origin between the two reads +- Shape: `bin/chunk_preflight/gathered.py:1` `gathered`: it mixes dataclasses with plan, worktree, forge and path decisions, and `facts.py` is the renderer, so two names say less than they hold + +Maintainability senior, decided by: + +- Navigation: `bin/loop_claude/loop/main.py:26` `__doc__`: the new paragraph says the preflight runs before routing and names `bin/chunk_preflight/` and `prompts.preflight_facts`, and the routing paragraph names `todo_table.chunk_item`, so why the worker was told X or routed to item N lands on the right file from --help +- Navigation: `README.md:85` "Tools": the new tool gets one line pointing to its --help, and the import paragraph says loop_claude runs it as a separate process +- Navigation: `bin/todo_table.py:229` `chunk_item`: one function picks for routing and the preflight, where 46b79e7's `routed_item` held its own copy, so a wrong-item symptom leads to one unit + +Junior A, decided by: + +- Locality: `bin/loop_claude/loop/main.py:217` `run_loop`: routing works only after the preflight, since `fetched_plan` never fetches and counts on the preflight's fetch, which only a comment says; at 46b79e7 `plan_item` read the working tree's todo.md wherever it ran +- Locality, Shape: `bin/git_repo.py:65` `DefaultPlan`: the git module imports `LastCut` from `todo_table` and builds the plan pick's inputs, so its name and docstring no longer cover what it holds +- Shape, Locality: `bin/todo_table.py:199` `landed`: it counts ## Unreleased entries first while `larv_review/git.py`'s `landed_since_release` counts commits only, two meanings of "work has landed" +- Shape, Locality: `bin/todo_table.py:212` `standing`: the table parser grew from 247 to 346 lines and now decides how a release stands through a five-valued literal whose three-line comment must be decoded first, where 46b79e7's `routed_item` stated the pick in six lines +- Locality: `bin/chunk_preflight/main.py:30` `__doc__`: the preflight runs reading-cost in the new worktree, and larv-review's step now depends on whether the prompt shows that, so one action is split across a tool, a prompt and a skill +- Shape: `bin/chunk_preflight/gathered.py:1` `gathered`: the name covers the data but not the pure choices it also holds, and `main.py` imports 12 names from it on one line -- 2.52.0 From a93b15ed6197c6cc2ebc4eb5a03d4d90ee2b4dad Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 03:11:00 +0200 Subject: [PATCH 18/22] File item 177: move the next chunk's pick into one module named for it, as the paired ruling's places ask --- todo.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index b6bb1d89..0aa065f5 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 177` +`Next ID = 178` ## Items @@ -40,6 +40,7 @@ | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | | 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | +| 177 | 0.3.0 | | | **Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan.** | 3 | 1 | 3 | 5 | 4 | 1.1 by 4 | 3.6 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -214,6 +215,16 @@ The chunk that ships this item files a copy of it in the release after the one i Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. +### 177. Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan. + +Raised by PR #302's paired ruling, where two of four seats read the project as worse at these places. Item 161 put the pick in `bin/todo_table.py` (`Standing`, `LastCut`, `unreleased_entries`, `landed`, `named_releases`, `standing`, `chunk_item`) and its reader in `bin/git_repo.py` (`DefaultPlan`, `default_plan`, `todos_since`), so the git module now imports the plan model and the table parser decides how a release stands. Make each of those places easier to read: + +- `bin/git_repo.py` → `DefaultPlan`: the git module knows todo.md and CHANGELOG.md. +- `bin/todo_table.py` → `standing`: a five-state literal whose three-line comment must be decoded first. +- `bin/todo_table.py` → `landed`: it counts ## Unreleased entries first, while `bin/larv_review/git.py` → `landed_since_release` counts commits only, two meanings of "work has landed"; give them one meaning or two names. +- `bin/loop_claude/loop/main.py` → `run_loop`: routing reads the plan as chunk-preflight's fetch left it, an order only a comment states. +- `bin/chunk_preflight/gathered.py`: the name covers the data, not the pure choices it also holds. + ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2). -- 2.52.0 From b9cbb06082b8327caa8f284edd29324f3d477778 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 20:10:38 +0200 Subject: [PATCH 19/22] =?UTF-8?q?Answer=20principles=20round=204:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20nothing=20to=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From b6dd8bc20ddaf6bb72435c2439e5a62de677b4fe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 20:11:00 +0200 Subject: [PATCH 20/22] =?UTF-8?q?Answer=20architecture=20round=204:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20nothing=20to=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 9a439a83bd8b508239d03b2c3607bc4652a80842 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 20:14:02 +0200 Subject: [PATCH 21/22] =?UTF-8?q?Answer=20stability=20round=204:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20nothing=20to=20answer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 10a283a5ebf0d6a1b07e3d28a05dd95483c3dc4a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 20:16:16 +0200 Subject: [PATCH 22/22] =?UTF-8?q?Drop=20DefaultPlan's=20unread=20ref,=20as?= =?UTF-8?q?=20architecture=20round=204's=20=F0=9F=9F=A2=20asks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/git_repo.py | 3 +-- bin/loop_claude/test_loop_claude.py | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/bin/git_repo.py b/bin/git_repo.py index 0c65933c..7e54751e 100644 --- a/bin/git_repo.py +++ b/bin/git_repo.py @@ -65,7 +65,6 @@ def origin_head(cwd: str | None, timeout: float | None) -> str | Failure: @dataclasses.dataclass(frozen=True) class DefaultPlan: """What the default branch, as last fetched, holds for picking the next chunk's item: todo_table.chunk_item's inputs.""" - ref: str # todo.md's text, empty where the branch holds none. todo: str | Failure cut: LastCut @@ -75,7 +74,7 @@ def default_plan(root: str, ref: str) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root) - return DefaultPlan(ref, file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root))) + return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root))) def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index bf23d212..6a4e0cf0 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -733,11 +733,11 @@ class Routing(unittest.TestCase): class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - self.assertIsNone(main.plan_item(DefaultPlan("origin/main", "", NO_CUT))) - self.assertEqual(main.plan_item(DefaultPlan("origin/main", TODO, LastCut("v0.1.0", "", 3, [TODO]))).id, 3) - self.assertIsNone(main.plan_item(DefaultPlan("origin/main", TODO, LastCut("v0.2.0", "", 3, [TODO])))) + self.assertIsNone(main.plan_item(DefaultPlan("", NO_CUT))) + self.assertEqual(main.plan_item(DefaultPlan(TODO, LastCut("v0.1.0", "", 3, [TODO]))).id, 3) + self.assertIsNone(main.plan_item(DefaultPlan(TODO, LastCut("v0.2.0", "", 3, [TODO])))) unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8") - for plan, said in ((DefaultPlan("origin/main", TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan("origin/main", unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): + for plan, said in ((DefaultPlan(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): with self.subTest(said=said): with contextlib.redirect_stderr(io.StringIO()) as stderr: self.assertIsNone(main.plan_item(plan)) -- 2.52.0