Files
claude-config/bin/chunk_preflight/main.py
T

196 lines
10 KiB
Python

"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker reads them rather than finding them.
usage: chunk-preflight
Run it inside a project checkout. loop-claude runs it at the checkout root before each fresh worker,
and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that
remote, and reads origin's default branch, or else the local main or master, as larv-review does.
It then prints:
- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md
holds under ## Unreleased, or else how many commits followed the tag;
- the next release in the default branch's todo.md, and that release's first item that does not
wait, as loop-claude routes on, with its L and E + I;
- the item's worktree: a sibling of the checkout named <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;
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists
them on a github.com origin, and else as tea does. No title reaches the output: on a public forge,
anyone may open a pull request, and its title would reach the worker's prompt;
- the items of that release that a chunk taking the item may take too: none is a question, and no
item outside them and the item blocks one;
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
file's lines or a folder's files, and the item's tagline and detail;
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <ID>`, `reading-cost` and
`larv-review places` print in the worktree, each with its exit code. reading-cost appends to the
worktree's docs/reading-cost.md, for the chunk to commit.
A fact it cannot find it says it cannot, and why, and goes on. With no item, it makes no worktree
and runs none of those four tools.
Exit 1, saying why, on any argument, or when git cannot start or finds no checkout.
"""
import pathlib
import subprocess
import sys
from chunk_preflight.facts import bundle_candidates, named_paths, unreleased_entries
from failure import Failure
from git_repo import commit_exists, default_branch, file_at, git, newest_release_tag, top
from markdown_text import quoted
from todo_table import Item, item_details, items, next_item
BIN = pathlib.Path(__file__).resolve().parents[1]
# A tool or forge CLI still running after this many seconds is stopped, so a hung one cannot hold the loop.
TIMEOUT = 300
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv:
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr)
return 1
root = top()
if isinstance(root, Failure):
print(root.reason, file=sys.stderr)
return 1
print("\n".join(preflight(pathlib.Path(root))))
return 0
def preflight(root: pathlib.Path) -> list[str]:
branch = default_branch(stale_ok=True)
if isinstance(branch, Failure):
return [f"- No default branch: {branch.reason}"]
default, note = branch
found = [f"- {note}"] if note else []
found.append(f"- {last_release(default)}")
todo = file_at(default, "todo.md")
planned = todo if isinstance(todo, Failure) else items(todo)
if isinstance(planned, Failure):
return [*found, f"- No plan item: {default}'s todo.md: {planned.reason}"]
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
def last_release(default: str) -> str:
tag = newest_release_tag(default)
if isinstance(tag, Failure):
return f"Last version cut: cannot be read: {tag.reason}"
changelog = file_at(default, "CHANGELOG.md")
entries = unreleased_entries(changelog) if isinstance(changelog, str) else None
if entries is not None:
return f"Last version cut: {tag or 'none'}. Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased."
commits = git("rev-list", "--count", f"{tag}..{default}" if tag else default)
since = f"since {tag}" if tag else f"on {default}"
return f"Last version cut: {tag or 'none'}. Unreleased: {commits.reason if isinstance(commits, Failure) else counted(int(commits), 'commit', 'commits')} {since}, and no ## Unreleased in CHANGELOG.md."
def item_worktree(root: pathlib.Path, branch: str, default: str) -> tuple[pathlib.Path, str] | Failure:
"""The worktree on branch, and how it came to be; a Failure where git cannot make it, or its path holds something else."""
held = git("worktree", "list", "--porcelain")
if isinstance(held, Failure):
return held
for block in held.split("\n\n"):
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
if fields.get("branch") == f"refs/heads/{branch}":
return pathlib.Path(fields["worktree"]), f"on the branch {branch}, which it already held."
path = root.parent / f"{root.name}-{branch}"
if path.exists():
return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}")
if commit_exists(f"refs/heads/{branch}"):
added, how = git("worktree", "add", "--quiet", str(path), branch), f"on the branch {branch}, which existed already."
elif commit_exists(f"refs/remotes/origin/{branch}"):
added, how = git("worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"), f"on the new branch {branch}, made off origin/{branch}."
else:
# --no-track: tracking the default branch would point a bare `git push` at it.
added, how = git("worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default), f"on the new branch {branch}, made off {default}."
return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else (path, how)
def pull_requests(root: pathlib.Path, branch: str) -> str:
"""Each open pull request from branch, by its number and URL, or why none can be listed."""
url = git("remote", "get-url", "origin")
if isinstance(url, Failure):
return "none, as the checkout has no origin remote."
github = "github.com" in url
command = ["gh", "pr", "list", "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"] if github else ["tea", "pulls", "list", "--fields", "index,head,url", "--output", "tsv"]
done = ran(command, root)
if isinstance(done, Failure) or done.returncode:
return f"cannot be listed: `{' '.join(command[:3])}` {done.reason if isinstance(done, Failure) else f'exited {done.returncode}: {done.stderr.strip()}'}"
rows = [line.split("\t") for line in done.stdout.splitlines()]
opened = [f"#{row[0]} {row[1]}" for row in rows if len(row) == 2] if github else [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch]
return ", ".join(opened) if opened else "none."
def bundled(planned: list[Item], first: Item) -> list[str]:
candidates = bundle_candidates(planned, first)
if not candidates:
return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates]
return [f"- The items of release {release_name(first)} that item {first.id}'s chunk may take too, where `~/.claude/CLAUDE.md` → \"Working loop\" lets them share it:", *listed]
def named(text: str, base: pathlib.Path) -> list[str]:
tracked = git("-C", str(base), "ls-files")
if isinstance(tracked, Failure):
return [f"- The files the item names: cannot be listed: {tracked.reason}"]
paths = named_paths(text, tracked.splitlines())
if not paths:
return ["- The item names no file or folder git tracks."]
return ["- The files and folders the item names:", *(f" - `{span}`: {size(base / span, count)}" for span, count in paths)]
def size(path: pathlib.Path, files: int) -> str:
if not path.is_file():
return counted(files, "file", "files")
try:
return counted(len(path.read_text(encoding="utf-8").splitlines()), "line", "lines")
except (OSError, UnicodeDecodeError) as failure:
return f"cannot be read: {failure}"
def ran(command: list[str], cwd: pathlib.Path) -> subprocess.CompletedProcess[str] | Failure:
try:
return subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT)
except (OSError, subprocess.TimeoutExpired) as failure:
return Failure(f"could not finish: {failure}")
def printed(shown: tuple[str, ...], command: list[str], cwd: pathlib.Path) -> str:
"""What command printed, run in cwd, and its exit code, under its name as shown."""
name = f"`{' '.join(shown)}`"
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}"