Answer architecture round 1: 2 🔴, 4 🟡; route and preflight on the one checkout todo.md the preflight fast-forwards, split the preflight into gathering and a pure render, move bundle_candidates onto todo_table.waiting, run the preflight through the python effect with a timeout, give the re-score sentence its own function, and point loop-claude's help at the modules

This commit is contained in:
2026-10-17 01:03:15 +02:00
parent 8b3a5a32a3
commit ecbb7a7cda
17 changed files with 657 additions and 268 deletions
+81 -117
View File
@@ -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 <checkout>-item-<ID>, on the branch
item-<ID>. 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)