Run a preflight before each fresh worker and put its facts in the worker's prompt

This commit is contained in:
2026-10-17 00:29:24 +02:00
parent 46b79e7803
commit f9615cb3b0
22 changed files with 532 additions and 76 deletions
View File
+26
View File
@@ -0,0 +1,26 @@
import re
from markdown_text import sections
from todo_table import Item
def unreleased_entries(changelog: str) -> int | None:
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
found = sections(changelog).get("Unreleased")
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
def bundle_candidates(found: list[Item], first: Item) -> list[Item]:
"""The items of first's release, in the table's order, that a chunk taking first may take too: no question, and none blocked by an item outside first and these."""
candidates = {item.id for item in found if item.release == first.release and item.id != first.id and item.exempt != "question"}
held = {item.id for item in found}
while blocked := {item.id for item in found if item.id in candidates and (held & set(item.blocked_by)) - candidates - {first.id}}:
candidates -= blocked
return [item for item in found if item.id in candidates]
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
spans = dict.fromkeys(span.rstrip("/") for span in re.findall(r"`([^`\s]+)`", text))
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
return [(span, count) for span, count in held if count]
+179
View File
@@ -0,0 +1,179 @@
"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker reads them rather than finding them.
usage: chunk-preflight
Run it inside a project checkout. loop-claude runs it at the checkout root before each fresh worker,
and quotes what it prints in the worker's prompt. It fetches origin, when the checkout has that
remote, and reads origin's default branch, or else the local main or master, as larv-review does.
It then prints:
- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md
holds under ## Unreleased, or else how many commits followed the tag;
- the next release in the default branch's todo.md, and that release's first item that does not
wait, as loop-claude routes on, with its L and E + I;
- the item's worktree: a sibling of the checkout named <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, as gh lists them on a github.com origin, and else as tea does;
- the items of that release that a chunk taking the item may take too: none is a question, and no
item outside them and the item blocks one;
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
file's lines or a folder's files, and the item's tagline and detail;
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <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}", *pull_requests(root)]
first = next_item(planned or [])
if first is None:
why = f"every item of {default}'s next release waits" if planned else f"{default} holds no todo.md items table"
return [*found, f"- No plan item: {why}, so no worktree was made.", *pull_requests(root)]
assert isinstance(todo, str) and planned
found.append(f"- Next release: {release_name(first)}. Its first item that does not wait: item {first.id}, L {first.likelihood or 'unscored'}, E + I {first.escape_and_impact or 'unscored'}.")
worktree = item_worktree(root, f"item-{first.id}", default)
found.append(f"- Worktree: {worktree.reason}" if isinstance(worktree, Failure) else f"- Worktree: {worktree[0]}, {worktree[1]}")
found += pull_requests(root)
found += bundled(planned, first)
details = item_details(todo)
detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})"
text = f"{first.tagline}\n\n{detail}".strip()
found += named(text, worktree[0] if isinstance(worktree, tuple) else root)
found.append(f"\nItem {first.id}'s tagline and detail:\n\n{quoted(text)}")
if isinstance(worktree, tuple):
for args in (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-run", str(first.id)), ("reading-cost",), ("larv-review", "places")):
found.append(f"\n{printed(args, [sys.executable, str(BIN / args[0]), *args[1:]], worktree[0])}")
return found
def last_release(default: str) -> str:
tag = newest_release_tag(default)
if isinstance(tag, Failure):
return f"Last version cut: cannot be read: {tag.reason}"
changelog = file_at(default, "CHANGELOG.md")
entries = unreleased_entries(changelog) if isinstance(changelog, str) else None
if entries is not None:
return f"Last version cut: {tag or 'none'}. Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased."
commits = git("rev-list", "--count", f"{tag}..{default}" if tag else default)
since = f"since {tag}" if tag else f"on {default}"
return f"Last version cut: {tag or 'none'}. Unreleased: {commits.reason if isinstance(commits, Failure) else counted(int(commits), 'commit', 'commits')} {since}, and no ## Unreleased in CHANGELOG.md."
def item_worktree(root: pathlib.Path, branch: str, default: str) -> tuple[pathlib.Path, str] | Failure:
"""The worktree on branch, and how it came to be; a Failure where git cannot make it, or its path holds something else."""
held = git("worktree", "list", "--porcelain")
if isinstance(held, Failure):
return held
for block in held.split("\n\n"):
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
if fields.get("branch") == f"refs/heads/{branch}":
return pathlib.Path(fields["worktree"]), f"on the branch {branch}, which it already held."
path = root.parent / f"{root.name}-{branch}"
if path.exists():
return Failure(f"none made, since {path} exists and holds no worktree on the branch {branch}")
if commit_exists(f"refs/heads/{branch}"):
added, how = git("worktree", "add", "--quiet", str(path), branch), f"on the branch {branch}, which existed already."
elif commit_exists(f"refs/remotes/origin/{branch}"):
added, how = git("worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"), f"on the new branch {branch}, made off origin/{branch}."
else:
# --no-track: tracking the default branch would point a bare `git push` at it.
added, how = git("worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default), f"on the new branch {branch}, made off {default}."
return Failure(f"none made: {added.reason}") if isinstance(added, Failure) else (path, how)
def pull_requests(root: pathlib.Path) -> list[str]:
url = git("remote", "get-url", "origin")
if isinstance(url, Failure):
return ["- Open pull requests: none, as the checkout has no origin remote."]
command = ["gh", "pr", "list"] if "github.com" in url else ["tea", "pulls", "list", "--fields", "index,title,head,state", "--output", "tsv"]
return [f"- Open pull requests: {printed(tuple(command), command, root)}"]
def bundled(planned: list[Item], first: Item) -> list[str]:
candidates = bundle_candidates(planned, first)
if not candidates:
return [f"- No other item of release {release_name(first)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates]
return [f"- The items of release {release_name(first)} that item {first.id}'s chunk may take too, where `~/.claude/CLAUDE.md` → \"Working loop\" lets them share it:", *listed]
def named(text: str, base: pathlib.Path) -> list[str]:
tracked = git("-C", str(base), "ls-files")
if isinstance(tracked, Failure):
return [f"- The files the item names: cannot be listed: {tracked.reason}"]
paths = named_paths(text, tracked.splitlines())
if not paths:
return ["- The item names no file or folder git tracks."]
return ["- The files and folders the item names:", *(f" - `{span}`: {size(base / span, count)}" for span, count in paths)]
def size(path: pathlib.Path, files: int) -> str:
if not path.is_file():
return counted(files, "file", "files")
try:
return counted(len(path.read_text(encoding="utf-8").splitlines()), "line", "lines")
except (OSError, UnicodeDecodeError) as failure:
return f"cannot be read: {failure}"
def printed(shown: tuple[str, ...], command: list[str], cwd: pathlib.Path) -> str:
"""What command printed, run in cwd, and its exit code, under its name as shown."""
name = f"`{' '.join(shown)}`"
try:
done = subprocess.run(command, capture_output=True, cwd=cwd, stdin=subprocess.DEVNULL, text=True, timeout=TIMEOUT)
except (OSError, subprocess.TimeoutExpired) as failure:
return f"{name} could not finish: {failure}"
output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip())
return f"{name} exited {done.returncode}, printing:\n\n{quoted(output)}" if output else f"{name} exited {done.returncode}, printing nothing."
def release_name(item: Item) -> str:
return ".".join(map(str, item.release))
def counted(count: int, one: str, many: str) -> str:
return f"{count} {one if count == 1 else many}"
+162
View File
@@ -0,0 +1,162 @@
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from chunk_preflight import facts
from test_env import isolated_env
from todo_table import items
BIN = pathlib.Path(__file__).resolve().parents[1]
README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
TODO = """# todo
## Scoring
`Score = 100 * V / (2**S + 8)`
`Bar = 0.1`
`Next ID = 10`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 56.2 |
| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
## Details
### 3. Do the next thing.
Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
"""
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
# Prints its arguments, then two open pull requests, as `tea pulls list --output tsv` does.
FAKE_TEA = "#!/bin/sh\necho \"tea $*\"\nprintf 'index\\ttitle\\thead\\tstate\\n12\\tWIP: the next thing\\titem-3\\topen\\n'\n"
class Repo:
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea on PATH."""
def __init__(self, test, todo=TODO):
temp = tempfile.TemporaryDirectory()
test.addCleanup(temp.cleanup)
self.temp = pathlib.Path(os.path.realpath(temp.name))
self.origin = self.temp / "origin.git"
self.root = self.temp / "proj"
fake = self.temp / "fake-bin"
fake.mkdir()
(fake / "tea").write_text(FAKE_TEA)
(fake / "tea").chmod(0o755)
(fake / "git").symlink_to(shutil.which("git"))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root))
self.write("README.md", README)
self.write("src/app.py", "def run():\n\treturn 1\n\n")
self.commit("start")
self.git(self.root, "tag", "v0.1.0")
self.write("CHANGELOG.md", CHANGELOG)
if todo:
self.write("todo.md", todo)
self.commit("plan")
self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0")
def git(self, cwd, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
def write(self, path, text):
(self.root / path).parent.mkdir(parents=True, exist_ok=True)
(self.root / path).write_text(text)
def commit(self, title):
self.git(self.root, "add", "-A")
self.git(self.root, "commit", "--quiet", "-m", title)
def preflight(self):
return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env=self.env, text=True, timeout=120)
class ChunkPreflightTool(unittest.TestCase):
def test_makes_the_items_worktree_off_the_fetched_default_branch_and_states_the_chunks_facts(self):
repo = Repo(self)
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
worktree = repo.temp / "proj-item-3"
self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-3")
self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main"))
for fact in (
"Last version cut: v0.1.0. Unreleased: 2 entries under CHANGELOG.md → ## Unreleased.",
"Next release: 0.2.0. Its first item that does not wait: item 3, L 4, E + I 5.",
f"Worktree: {worktree}, on the new branch item-3, made off origin/main.",
"- item 7, L 1, E + I 2, S 1: **Do the thing after.**",
"- `src/app.py`: 3 lines",
"- `src`: 1 file",
"Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.",
"tea pulls list --fields index,title,head,state --output tsv",
"12\tWIP: the next thing\titem-3\topen",
"`rank_todo.py --check todo.md` exited 0",
"`larv-review needs-scoring-run 3` exited 0",
"`reading-cost` exited 0",
"`larv-review places` exited 0",
):
self.assertIn(fact, done.stdout)
self.assertNotIn("item 5,", done.stdout)
self.assertNotIn("item 8,", done.stdout)
self.assertNotIn("item 9,", done.stdout)
self.assertNotIn("`gone.py`:", done.stdout)
self.assertIn(f"to {worktree}/docs/reading-cost.md", done.stdout)
def test_continues_the_items_worktree_and_else_its_pushed_branch(self):
repo = Repo(self)
repo.preflight()
worktree = repo.temp / "proj-item-3"
self.assertIn(f"Worktree: {worktree}, on the branch item-3, which it already held.", repo.preflight().stdout)
(worktree / "work.txt").write_text("work\n")
repo.git(worktree, "add", "work.txt")
repo.git(worktree, "commit", "--quiet", "-m", "work")
repo.git(worktree, "push", "--quiet", "origin", "item-3")
repo.git(repo.root, "worktree", "remove", "--force", str(worktree))
repo.git(repo.root, "branch", "--quiet", "-D", "item-3")
self.assertIn(f"Worktree: {worktree}, on the new branch item-3, made off origin/item-3.", repo.preflight().stdout)
self.assertTrue((worktree / "work.txt").exists())
def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self):
repo = Repo(self, todo="")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("Last version cut: v0.1.0.", done.stdout)
self.assertIn("No plan item: origin/main holds no todo.md items table, so no worktree was made.", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_exits_1_outside_a_checkout(self):
with tempfile.TemporaryDirectory() as temp:
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True)
self.assertEqual(done.returncode, 1)
self.assertIn("git rev-parse --show-toplevel", done.stderr)
class Facts(unittest.TestCase):
def test_counts_the_top_level_entries_under_unreleased(self):
self.assertEqual(facts.unreleased_entries(CHANGELOG), 2)
self.assertEqual(facts.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
self.assertIsNone(facts.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
def test_bundles_an_item_blocked_only_by_items_the_chunk_may_take(self):
found = items(TODO.replace("| 9 | 0.3.0 | |", "| 9 | 0.2.0 | 7 |"))
self.assertEqual([item.id for item in facts.bundle_candidates(found, found[1])], [7, 9])
if __name__ == "__main__":
unittest.main()