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)