Files

170 lines
10 KiB
Python

"""The lines the preflight prints, stated from what it gathered."""
from plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
from touch_predictions.beside import chunks_beside
from release_plan.next_chunk import cut_name, NextChunk, NoItem
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
from failure import Failure
from forge.commands import Forge
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran
from text_files.markdown_text import listed, quoted
from chunk_preflight.choices import PULLS_LIST
from plan.release import version
# CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt.
JOINING_DETAILS = 10
def render(found: Gathered) -> list[str]:
"""One `- ` line per fact, then the item's tagline and detail, the detail of each item that may join its chunk, and what each tool printed."""
note = [f"- {found.note}"] if found.note else []
unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else []
head = [*note, f"- {last_release(found.default, found.cut)}", *unseen, *merge_lines(found)]
paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}."
texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}."
if isinstance(found.item, NoItem):
return [*head, f"- No plan item: {found.item.why} No worktree was made.", paths, texts]
lines = item_lines(found.plan, found.item)
return [*head, *lines[:2], paths, texts, *lines[2:]]
def merge_lines(found: Gathered) -> list[str]:
"""What `merge = "human"` leaves for the worker to know: each worktree a merged pull request left, the items passed over since their pull request awaits a person's merge, or why those pull requests could not be read."""
left = [f"- The worktree {worktree.path}, on the branch {worktree.branch}, is left from pull request #{worktree.pull}, which has merged: run `~/.claude/bin/chunk-pr clean` in it as this chunk's first step." for worktree in found.left]
items = found.item.plan.items if isinstance(found.item, ItemFacts) else []
passed = [f"item {item.id}, by pull request {item.awaits_merge}" for item in items if item.awaits_merge]
over = [f"- Items passed over, each finished on a branch whose ready pull request awaits a person's merge: {'; '.join(passed)}. No chunk takes one."] if passed else []
unread = [f"- The pull requests that await a person's merge cannot be read, so no item is passed over for one: {found.merges_unread.reason}"] if found.merges_unread else []
return [*left, *over, *unread]
def last_release(default: str, release: LastCut) -> str:
if isinstance(release.tag, Failure):
return f"Last version cut: cannot be read: {release.tag.reason}"
named = cut_name(release)
cut = f"Last version cut: {named 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."
headed = dated_cut(release.tag, release.changelog)
since = f"since {release.tag}" if release.tag else f"since CHANGELOG.md dated {version(headed)}" if headed else f"on {default}"
commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}"
changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md"
return f"{cut} Unreleased: {commits}; {changelog}."
def item_lines(plan: str, 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"- The {'next release, after the last cut, that ' + plan + ' names' if item.plan.carried else 'earliest release in ' + plan}: {version(first.release)}. {'The item this chunk starts from, named with --item' if item.plan.named else 'Its first item that does not wait'}: item {first.id}, {levels(first)}.",
*carried_lines(item.plan),
f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
*bundled(item.plan),
*beside(item.plan),
*named_lines(item.named),
f"\nItem {first.id}'s tagline and detail:\n\n{quoted(item.plan.text)}",
*joining_details(item.plan),
*(f"\n{printed(shown, done)}" for shown, done in item.tools),
]
def carried_lines(plan: NextChunk) -> list[str]:
"""What the worker does about the items of a release someone cut while it held them."""
over = plan.carried
if over is None:
return []
items, count, them = (f"Items {listed([str(id_) for id_ in over.ids], 'and')} are", "they count", "them") if len(over.ids) > 1 else (f"Item {over.ids[0]} is", "it counts", "it")
return [f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."]
def joining_details(plan: NextChunk) -> list[str]:
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
joining = bundle_candidates(plan.items, plan.first)
if not joining:
return []
shown, left = joining[:JOINING_DETAILS], joining[JOINING_DETAILS:]
lines = [f"\nItem {item.id}'s detail:\n\n{quoted(detail)}" if (detail := item.detail) else f"\nItem {item.id} has no detail." for item in shown]
if left:
lines.append(f"\nThe details of items {listed([str(item.id) for item in left], 'and')} are not quoted: only the first {JOINING_DETAILS} are. Run `~/.claude/bin/todo-item show <ID>` for each.")
return lines
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_LIST[forge])
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 prints only branch's pull requests, as number and URL; tea prints every pull request, as 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: NextChunk) -> list[str]:
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
if ships_alone(first):
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
if not candidates:
return [f"- No other item of release {version(first.release)} 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 {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
def beside(plan: NextChunk) -> list[str]:
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
first = plan.first
found = chunks_beside(plan.items, first)
if found is None:
return []
none = f"- No item of release {version(first.release)} may start a chunk beside item {first.id}'s"
if isinstance(found, str):
return [f"{none}: {found}."]
refused = f" Not beside it: {'; '.join(found.refused)}." if found.refused else ""
if not found.picked:
return [f"{none}.{refused}"]
return [f"- The items of release {version(first.release)} that may start chunks beside item {first.id}'s: {', '.join(map(str, found.picked))}. None is predicted to touch a part that item {first.id} touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own.{refused}"]
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 no output."
def levels(item: Item) -> str:
return f"L {item.likelihood or 'unscored'}, E + I {item.escape_and_impact or 'unscored'}"
def counted(count: int, one: str, many: str) -> str:
return f"{count} {one if count == 1 else many}"