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
+101 -15
View File
@@ -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 `#<number> <URL>`: 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}"
+158
View File
@@ -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]
+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)
+138 -40
View File
@@ -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__":