Read the plan and the records where the config puts them in chunk-preflight and larv-review

This commit is contained in:
2026-11-13 00:42:17 +01:00
parent 0a47b55c93
commit 4f5a7aa411
14 changed files with 201 additions and 96 deletions
+8 -3
View File
@@ -19,9 +19,14 @@ def cut_name(cut: LastCut) -> str | None:
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: def plan_name(default: str, outside: pathlib.Path | None) -> str:
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none.""" """How the preflight names the plan it read: the default branch's todo.md, or the file, where the project's config puts it outside the checkout."""
where = f"{default}'s todo.md" return str(outside) if outside else f"{default}'s todo.md"
def planned(todo: str | Failure, cut: LastCut, default: str, outside: pathlib.Path | None = None) -> Plan | NoItem:
"""The plan in todo, the text of the todo.md plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none."""
where = plan_name(default, outside)
if isinstance(todo, Failure): if isinstance(todo, Failure):
return NoItem(f"{where} cannot be read: {todo.reason}.") return NoItem(f"{where} cannot be read: {todo.reason}.")
found = items(todo) found = items(todo)
+6 -4
View File
@@ -16,9 +16,11 @@ 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.""" """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 [] note = [f"- {found.note}"] if found.note else []
head = [*note, f"- {last_release(found.default, found.cut)}"] head = [*note, f"- {last_release(found.default, found.cut)}"]
paths = f"- The project's config puts its files at: {'; '.join(f'{setting} {path}' for setting, path in found.paths.items())}."
if isinstance(found.item, NoItem): if isinstance(found.item, NoItem):
return [*head, f"- No plan item: {found.item.why} No worktree was made."] return [*head, f"- No plan item: {found.item.why} No worktree was made.", paths]
return [*head, *item_lines(found.default, found.item)] lines = item_lines(found.plan, found.item)
return [*head, *lines[:2], paths, *lines[2:]]
def last_release(default: str, release: LastCut) -> str: def last_release(default: str, release: LastCut) -> str:
@@ -36,11 +38,11 @@ def last_release(default: str, release: LastCut) -> str:
return f"{cut} Unreleased: {commits}; {changelog}." return f"{cut} Unreleased: {commits}; {changelog}."
def item_lines(default: str, item: ItemFacts) -> list[str]: def item_lines(plan: str, item: ItemFacts) -> list[str]:
first = item.plan.first first = item.plan.first
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}" worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
return [ return [
f"- The earliest release in {default}'s todo.md: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.", f"- The earliest release in {plan}: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
f"- Worktree: {worktree}", f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}", f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
*bundled(item.plan), *bundled(item.plan),
+4
View File
@@ -79,3 +79,7 @@ class Gathered:
cut: LastCut cut: LastCut
# What was found or made for the plan's first item; else why the plan names none. # What was found or made for the plan's first item; else why the plan names none.
item: ItemFacts | NoItem item: ItemFacts | NoItem
# The plan that was read, as choices.plan_name names it.
plan: str
# Each path the project's config sets, by its setting: in the item's worktree where one was made or continued, else in the checkout.
paths: dict[str, pathlib.Path]
+20 -9
View File
@@ -7,7 +7,9 @@ origin's default branch, or else the local main or master. Without --worktree, i
but it doesn't make a worktree or a branch, and doesn't run any tool in one. loop-claude runs it but it doesn't make a worktree or a branch, and doesn't run any tool in one. loop-claude runs it
with --worktree at the checkout root before each chunk's first worker, before it routes the chunk, with --worktree 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 leaves the checkout as it is, and reads and quotes what it prints in the worker's prompt. It leaves the checkout as it is, and reads
todo.md as the default branch holds it, the plan loop-claude routes on. It prints: todo.md as the default branch holds it, the plan loop-claude routes on. Where the project's config
puts todo.md or CHANGELOG.md outside the checkout, it reads that file as it stands, and counts
only the releases it names now. It prints:
- the last version cut: the newest v* tag on the default branch, or on a branch with no tag the - the last version cut: the newest v* tag on the default branch, or on a branch with no tag the
newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count. newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count.
@@ -30,6 +32,8 @@ todo.md as the default branch holds it, the plan loop-claude routes on. It print
the branch item-<ID>. It continues a worktree already on that branch; else it adds one on the 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 local branch, else on a new branch tracking origin's, else on a new branch off the default
branch. Without --worktree, it prints that none was made; branch. Without --worktree, it prints that none was made;
- each path the project's config sets, as `project-config` prints them in that worktree, or else
in the checkout;
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists - 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; them on a github.com origin, and else as tea does. No title reaches the output;
- the items of that release that a chunk taking the item may take too, each with its L, E + I, - the items of that release that a chunk taking the item may take too, each with its L, E + I,
@@ -38,7 +42,7 @@ todo.md as the default branch holds it, the plan loop-claude routes on. It print
- each file or folder git tracks that the item's tagline or detail names in backticks, with a - 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, then the item's tagline and detail, then the detail of each file's lines or a folder's files, then the item's tagline and detail, then the detail of each
of the first {JOINING_DETAILS} items that may join, or that one has none; of the first {JOINING_DETAILS} items that may join, or that one has none;
- where it made or continued the worktree, what `rank_todo.py --check todo.md`, - where it made or continued the worktree, what `rank_todo.py --check`,
`larv-review needs-scoring-run <ID>`, `reading-cost` and `larv-review places` print in it, each `larv-review needs-scoring-run <ID>`, `reading-cost` and `larv-review places` print in it, each
with its exit code. reading-cost appends to the worktree's docs/reading-cost.md, for the chunk to with its exit code. reading-cost appends to the worktree's docs/reading-cost.md, for the chunk to
commit. commit.
@@ -49,8 +53,8 @@ stopped fetch reads origin as last fetched. With no item, it makes no worktree a
those four tools, --worktree or not. those four tools, --worktree or not.
Exit 1, saying why, on any argument other than --worktree, -h or --help, on a Exit 1, saying why, on any argument other than --worktree, -h or --help, on a
CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, or when git cannot start or finds no CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, when git cannot start or finds no
checkout or no default branch. checkout or no default branch, or when no config names the checkout or its config cannot be read.
""" """
import pathlib import pathlib
import re import re
@@ -61,14 +65,15 @@ import typing
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
from release_plan.release_standing import default_plan from release_plan.release_standing import default_plan
from failure import Failure from failure import Failure
from project_config.main import located
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
from chunk_preflight.choices import forge_of, planned, pulls_command, worktree_add, worktree_on from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command, worktree_add, worktree_on
from chunk_preflight.facts import JOINING_DETAILS, render from chunk_preflight.facts import JOINING_DETAILS, render
from release_plan.named_code import named_paths from release_plan.named_code import named_paths
BIN = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(__file__).resolve().parents[1]
# Each tool run in the item's worktree, {item} standing for the item's ID. # 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")) TOOLS = (("rank_todo.py", "--check"), ("larv-review", "needs-scoring-run", "{item}"), ("reading-cost",), ("larv-review", "places"))
# Seconds before a fetch, forge CLI or tool is stopped, so a hung one cannot keep the rest from printing; TIMEOUT_SETTING overrides it. # Seconds before a fetch, forge CLI or tool is stopped, so a hung one cannot keep the rest from printing; TIMEOUT_SETTING overrides it.
TIMEOUT = 60 TIMEOUT = 60
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT" TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
@@ -115,10 +120,16 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
if isinstance(default, Failure): if isinstance(default, Failure):
return default return default
ref, note = default ref, note = default
held = default_plan(str(root), ref) config = located(str(root), pathlib.Path.home())
plan = planned(held.todo, held.cut, ref) if isinstance(config, Failure):
return config
outside = None if config.tracked("plan") else config.paths["plan"]
held = default_plan(str(root), ref, config.place("plan"), config.place("changelog"))
plan = planned(held.todo, held.cut, ref, outside)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
return render(Gathered(ref, note, held.cut, item)) # A `checkout:` path lands in the worktree the chunk works in.
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).paths))
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts: def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
+4 -4
View File
@@ -145,7 +145,7 @@ class ChunkPreflightTool(unittest.TestCase):
"#12 https://forge/pulls/12", "#12 https://forge/pulls/12",
"`src/app.py`: 3 lines", "`src/app.py`: 3 lines",
"`src`: 1 file", "`src`: 1 file",
"`rank_todo.py --check todo.md` exited 0", "`rank_todo.py --check` exited 0",
"`larv-review needs-scoring-run 7` exited 0", "`larv-review needs-scoring-run 7` exited 0",
"`reading-cost` exited 0", "`reading-cost` exited 0",
"`larv-review places` exited 0", "`larv-review places` exited 0",
@@ -330,7 +330,7 @@ def item_facts(todo=TODO, **fields):
def rendered(item, release=CUT, note=None): def rendered(item, release=CUT, note=None):
return "\n".join(render(Gathered("origin/main", note, release, item))) return "\n".join(render(Gathered("origin/main", note, release, item, "origin/main's todo.md", {"plan": pathlib.Path("/c/proj-item-3/todo.md"), "changelog": pathlib.Path("/c/proj-item-3/CHANGELOG.md")})))
class Render(unittest.TestCase): class Render(unittest.TestCase):
@@ -442,8 +442,8 @@ class Render(unittest.TestCase):
self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke")))) self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke"))))
def test_states_what_each_tool_printed_and_its_exit_code(self): 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 needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))])) said = rendered(item_facts(tools=[("rank_todo.py --check", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))]))
self.assertIn("`rank_todo.py --check todo.md` exited 0", said) self.assertIn("`rank_todo.py --check` exited 0", said)
self.assertIn("> ranked", said) self.assertIn("> ranked", said)
self.assertIn("`reading-cost` exited 1, printing no output", said) self.assertIn("`reading-cost` exited 1, printing no output", said)
self.assertIn("> out\n> err", said) self.assertIn("> out\n> err", said)
+18 -13
View File
@@ -1,34 +1,39 @@
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, full_history, git, top from git_cli.git_repo import file_at, full_history, git
from review_rules.comprehension_history import HISTORY, HistoryChange from project_config.main import project
from review_rules.comprehension_history import HistoryChange
def history_changes(default: str) -> list[HistoryChange] | Failure: def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first.""" """Each merged change on the default branch that touched the history, newest first. A Failure where the project's config puts the history outside the checkout, where no commit holds it."""
if partial := full_history(): if partial := full_history():
return partial return partial
# HISTORY names the file from the checkout's top, and git reads a path from the directory it runs in. config = project()
root = top() if isinstance(config, Failure):
if isinstance(root, Failure): return config
return root history = config.tracked("comprehension-history")
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY, cwd=root) if history is None:
return Failure(f"larv-review doesn't support a comprehension history outside the checkout: no commit holds {config.paths['comprehension-history']}, so it cannot tell which commit was last measured")
# history names the file from the checkout's top, and git reads a path from the directory it runs in.
root = str(config.top)
commits = git("log", "--first-parent", "--format=%H", default, "--", history, cwd=root)
if isinstance(commits, Failure): if isinstance(commits, Failure):
return commits return commits
changes = [] changes = []
for commit in commits.split(): for commit in commits.split():
change = history_change(commit, root) change = history_change(commit, history, root)
if isinstance(change, Failure): if isinstance(change, Failure):
return change return change
changes.append(change) changes.append(change)
return changes return changes
def history_change(commit: str, root: str) -> HistoryChange | Failure: def history_change(commit: str, history: str, root: str) -> HistoryChange | Failure:
"""The history before and after commit, read in the checkout at root. A merge commit counts as one change, against its first parent.""" """The history, the file git names history, before and after commit, read in the checkout at root. A merge commit counts as one change, against its first parent."""
before = file_at(f"{commit}^1", HISTORY, root) before = file_at(f"{commit}^1", history, root)
if isinstance(before, Failure): if isinstance(before, Failure):
return before return before
after = file_at(commit, HISTORY, root) after = file_at(commit, history, root)
if isinstance(after, Failure): if isinstance(after, Failure):
return after return after
return HistoryChange(commit, before, after) return HistoryChange(commit, before, after)
+19 -17
View File
@@ -3,9 +3,10 @@ import time
import typing import typing
from larv_review.agreement import agreement_report from larv_review.agreement import agreement_report
from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from larv_review.plan import checkout_plan, plan_reasons from larv_review.plan import checkout_plan, plan_reasons
from git_cli.git_repo import commit_exists, top from git_cli.git_repo import commit_exists
from project_config.main import project
from larv_review.ruling import counted, overall, ruling, split, surplus, votes from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure from failure import Failure
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
@@ -49,10 +50,11 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
return reasons return reasons
if not reasons: if not reasons:
return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them") return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them")
checkout = top() config = project()
if isinstance(checkout, Failure): if isinstance(config, Failure):
return checkout return config
todo = checkout_plan(checkout) checkout = str(config.top)
todo = checkout_plan(config.paths["plan"])
if isinstance(todo, Failure): if isinstance(todo, Failure):
return todo return todo
_, plan = todo _, plan = todo
@@ -68,12 +70,12 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
def rerank() -> Failure | None: def rerank() -> Failure | None:
"""Rank the checkout's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again.""" """Rank the project's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again."""
checkout = top() config = project()
if isinstance(checkout, Failure): if isinstance(config, Failure):
return checkout return config
todo = pathlib.Path(checkout, "todo.md") todo = config.paths["plan"]
ranked = plan_file.rank_file(todo) ranked = plan_file.rank_file(todo, config)
if isinstance(ranked, Failure): if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again") return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
if ranked.under_bar: if ranked.under_bar:
@@ -137,11 +139,11 @@ def show_agreement() -> Failure | None:
def history_file() -> tuple[pathlib.Path, str] | Failure: def history_file() -> tuple[pathlib.Path, str] | Failure:
"""The checkout's history and its text, empty when the file is missing.""" """The project's comprehension history, where its config puts it, and its text, empty when the file is missing."""
checkout = top() config = project()
if isinstance(checkout, Failure): if isinstance(config, Failure):
return checkout return config
history = pathlib.Path(checkout, HISTORY) history = config.paths["comprehension-history"]
try: try:
return history, history.read_text(encoding="utf-8") if history.exists() else "" return history, history.read_text(encoding="utf-8") if history.exists() else ""
except (OSError, UnicodeDecodeError) as failure: except (OSError, UnicodeDecodeError) as failure:
+19 -11
View File
@@ -1,9 +1,11 @@
import pathlib import pathlib
import sys
from larv_review.plan import EMPTIED_WORDS, plan_reasons from larv_review.plan import EMPTIED_WORDS, plan_reasons
from review_rules.comprehension_history import entries, HISTORY from project_config.main import project
from review_rules.comprehension_history import entries
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, git, top from git_cli.git_repo import file_at, git
from release_plan.todo_table import items, NoItemsTable from release_plan.todo_table import items, NoItemsTable
@@ -12,10 +14,16 @@ def owed_scoring_run(default: str) -> Failure | None:
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking. The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
""" """
checkout = top() config = project()
if isinstance(checkout, Failure): if isinstance(config, Failure):
return checkout return config
if not has_plan(checkout): checkout = str(config.top)
if not has_plan(config.paths["plan"]):
return None
history = config.tracked("comprehension-history")
if history is None:
# No commit holds a history outside the checkout, so the runs the branch recorded cannot be counted; the merge goes on, as `docs/decisions.md` → "project config: a tool that reads a file's commits …" says.
print(f"larv-review doesn't support a comprehension history outside the checkout, so it cannot tell whether the chunk owes a scoring run: {config.paths['comprehension-history']}", file=sys.stderr)
return None return None
base = git("merge-base", default, "HEAD", cwd=checkout) base = git("merge-base", default, "HEAD", cwd=checkout)
if isinstance(base, Failure): if isinstance(base, Failure):
@@ -25,10 +33,10 @@ def owed_scoring_run(default: str) -> Failure | None:
return reasons return reasons
if not reasons: if not reasons:
return None return None
before = file_at(base.strip(), HISTORY, checkout) before = file_at(base.strip(), history, checkout)
if isinstance(before, Failure): if isinstance(before, Failure):
return before return before
after = file_at("HEAD", HISTORY, checkout) after = file_at("HEAD", history, checkout)
if isinstance(after, Failure): if isinstance(after, Failure):
return after return after
return shortfall(reasons, len(scoring_runs(after)) - len(scoring_runs(before))) return shortfall(reasons, len(scoring_runs(after)) - len(scoring_runs(before)))
@@ -42,10 +50,10 @@ def shortfall(reasons: list[str], recorded: int) -> Failure | None:
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}") return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
def has_plan(checkout: str) -> bool: def has_plan(todo: pathlib.Path) -> bool:
"""Whether the checkout has a todo.md holding an items table. A file that can't be read counts, so `plan_reasons` reports it.""" """Whether todo, the project's plan, exists and holds an items table. A file that can't be read counts, so `plan_reasons` reports it."""
try: try:
return not isinstance(items(pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")), NoItemsTable) return not isinstance(items(todo.read_text(encoding="utf-8")), NoItemsTable)
except FileNotFoundError: except FileNotFoundError:
return False return False
except (OSError, UnicodeDecodeError): except (OSError, UnicodeDecodeError):
+15 -14
View File
@@ -1,8 +1,8 @@
import pathlib import pathlib
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown from release_plan.release_standing import Cut, default_plan, held_at, LastCut, next_release, Unknown
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, top from project_config.main import project
from larv_review.scoring import is_floor_item from larv_review.scoring import is_floor_item
from release_plan.todo_table import Item, items, NoItemsTable, renames from release_plan.todo_table import Item, items, NoItemsTable, renames
from release_plan.ranking import OPTED_OUT from release_plan.ranking import OPTED_OUT
@@ -64,20 +64,21 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure: def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure:
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not.""" """Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
checkout = top() config = project()
if isinstance(checkout, Failure): if isinstance(config, Failure):
return checkout return config
decisions = file_at(ref, "docs/decisions.md", checkout) checkout = str(config.top)
decisions = held_at(ref, config.place("decisions"), checkout)
if isinstance(decisions, Failure): if isinstance(decisions, Failure):
return decisions return decisions
if OPTED_OUT.search(decisions): if OPTED_OUT.search(decisions):
return [] return []
held = default_plan(checkout, ref) held = default_plan(checkout, ref, config.place("plan"), config.place("changelog"))
before = held.todo before = held.todo
if isinstance(before, Failure): if isinstance(before, Failure):
return before return before
read = checkout_plan(checkout) read = checkout_plan(config.paths["plan"])
if isinstance(read, Failure): if isinstance(read, Failure):
return read return read
after, chunk = read after, chunk = read
@@ -93,7 +94,7 @@ def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure:
landed_release = landed_towards(planned, held.cut) landed_release = landed_towards(planned, held.cut)
if isinstance(landed_release, Failure): if isinstance(landed_release, Failure):
return landed_release return landed_release
unmeasured = unmeasured_cut(ref, checkout) unmeasured = unmeasured_cut(ref, config.place("comprehension-history"), checkout)
if isinstance(unmeasured, Failure): if isinstance(unmeasured, Failure):
return unmeasured return unmeasured
if ids is None: if ids is None:
@@ -101,12 +102,12 @@ def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure:
return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured) return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
def checkout_plan(checkout: str) -> tuple[str, list[Item]] | Failure: def checkout_plan(todo: pathlib.Path) -> tuple[str, list[Item]] | Failure:
"""The checkout's todo.md, as its text and its items.""" """The checkout's plan, the todo.md the project's config names, as its text and its items."""
try: try:
text = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8") text = todo.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure: except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}") return Failure(f"could not read {todo}: {failure}")
found = items(text) found = items(text)
if isinstance(found, NoItemsTable): if isinstance(found, NoItemsTable):
return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one") return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one")
+20 -7
View File
@@ -8,6 +8,8 @@ from review_rules.comprehension_history import DIMENSIONS
from failure import Failure from failure import Failure
from records.markdown_text import FENCE, listed, section from records.markdown_text import FENCE, listed, section
from git_cli.git_repo import git from git_cli.git_repo import git
from project_config.main import located
from project_config.settings import ProjectConfig
from review_rules.review_folder import made_review_folder, review_folder from review_rules.review_folder import made_review_folder, review_folder
CLAUDE_MD = "CLAUDE.md" CLAUDE_MD = "CLAUDE.md"
@@ -22,8 +24,8 @@ SEATS = (
# The dimensions a seat scores beside the overall, which comes last in DIMENSIONS. # The dimensions a seat scores beside the overall, which comes last in DIMENSIONS.
PANEL_DIMENSIONS = DIMENSIONS[:-1] PANEL_DIMENSIONS = DIMENSIONS[:-1]
VALUE_NAMES = ("language", "kind", "domain", "domain docs", "3am question") VALUE_NAMES = ("language", "kind", "domain", "domain docs", "3am question")
FORBIDDEN_FILES = ("todo.md", "docs/decisions.md", "docs/comprehension-history.md", "docs/reading-cost.md") # The files no seat may open, by the setting that places each, and what each is.
FORBIDDEN = "todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' records and past chunks' reading cost)" FORBIDDEN = (("plan", "the plan"), ("decisions", "the decision log"), ("comprehension-history", "past panels' records"), ("reading-cost", "past chunks' reading cost"))
TEST_FILE = re.compile(r"(^|/)(tests?/|test_[^/]*$|[^/]*_test\.[^/]*$|[^/]*\.(test|spec)\.[^/]*$)") TEST_FILE = re.compile(r"(^|/)(tests?/|test_[^/]*$|[^/]*_test\.[^/]*$|[^/]*\.(test|spec)\.[^/]*$)")
TEST_FILES = "test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder" TEST_FILES = "test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder"
@@ -76,9 +78,16 @@ def project_values(text: str, source: str) -> dict[str, str] | Failure:
return {name: values[name] for name in VALUE_NAMES} return {name: values[name] for name in VALUE_NAMES}
def file_globs(paths: list[str]) -> str: def forbidden(config: ProjectConfig) -> tuple[list[str], str]:
"""The files no seat may open, as git names them, and the words that tell a seat so. A file the project's config puts outside the checkout is in neither: the scoring worktree doesn't hold it."""
held = [(path, what) for setting, what in FORBIDDEN if (path := config.tracked(setting))]
files = [path for path, _ in held]
return files, f"{listed(files, 'or')} ({listed([what for _, what in held], 'and')})" if held else "any record of a past panel"
def file_globs(paths: list[str], forbidden_files: list[str]) -> str:
"""Every tracked file of paths a seat reads, as one glob per top-level folder and each top-level file, with the test files the globs leave out.""" """Every tracked file of paths a seat reads, as one glob per top-level folder and each top-level file, with the test files the globs leave out."""
read = [path for path in paths if path not in FORBIDDEN_FILES and not TEST_FILE.search(path)] read = [path for path in paths if path not in forbidden_files and not TEST_FILE.search(path)]
folders = sorted({path.split("/")[0] for path in read if "/" in path}) folders = sorted({path.split("/")[0] for path in read if "/" in path})
tested = {path.split("/")[0] for path in paths if "/" in path and TEST_FILE.search(path)} tested = {path.split("/")[0] for path in paths if "/" in path and TEST_FILE.search(path)}
globs = [f"`{folder}/**`" + (" except test files" if folder in tested else "") for folder in folders] globs = [f"`{folder}/**`" + (" except test files" if folder in tested else "") for folder in folders]
@@ -150,8 +159,11 @@ def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
replaced = folder.exists() replaced = folder.exists()
if replaced and isinstance(removed := removed_setup(worktree), Failure): if replaced and isinstance(removed := removed_setup(worktree), Failure):
return removed return removed
config = located(worktree, home)
if isinstance(config, Failure):
return config
# Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md. # Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md.
source = pathlib.Path(worktree) / "AGENTS.md" source = config.paths["working-rules"]
if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file(): if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file():
source = own source = own
values = project_values(source.read_text() if source.is_file() else "", source.name) values = project_values(source.read_text() if source.is_file() else "", source.name)
@@ -181,14 +193,15 @@ def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
if isinstance(tracked, Failure): if isinstance(tracked, Failure):
shutil.rmtree(folder, ignore_errors=True) shutil.rmtree(folder, ignore_errors=True)
return tracked return tracked
forbidden_files, forbidden_words = forbidden(config)
filled = { filled = {
**values, **values,
"checkout": str(checkout), "checkout": str(checkout),
"branch": head.strip() if isinstance(branch, Failure) else branch.strip(), "branch": head.strip() if isinstance(branch, Failure) else branch.strip(),
"main": main, "main": main,
"forbidden": FORBIDDEN, "forbidden": forbidden_words,
"git": f"`git -C {checkout} ls-files`", "git": f"`git -C {checkout} ls-files`",
"files": file_globs(tracked.splitlines()), "files": file_globs(tracked.splitlines(), forbidden_files),
"preloaded": preloaded if preloaded is not None else preloaded_files(pathlib.Path(main), home), "preloaded": preloaded if preloaded is not None else preloaded_files(pathlib.Path(main), home),
"anchors": "\n".join(score[0]), "anchors": "\n".join(score[0]),
"dimensions": "\n".join(score[1]), "dimensions": "\n".join(score[1]),
+27 -3
View File
@@ -148,13 +148,13 @@ class Seats(unittest.TestCase):
def test_checkout_plan_fails_on_a_missing_or_tableless_todo(self): def test_checkout_plan_fails_on_a_missing_or_tableless_todo(self):
with tempfile.TemporaryDirectory() as checkout: with tempfile.TemporaryDirectory() as checkout:
with self.subTest("missing"): with self.subTest("missing"):
self.assertIsInstance(checkout_plan(checkout), Failure) self.assertIsInstance(checkout_plan(pathlib.Path(checkout, "todo.md")), Failure)
with self.subTest("no items table"): with self.subTest("no items table"):
pathlib.Path(checkout, "todo.md").write_text("# todo\n", encoding="utf-8") pathlib.Path(checkout, "todo.md").write_text("# todo\n", encoding="utf-8")
self.assertIn("no items table", checkout_plan(checkout).reason) self.assertIn("no items table", checkout_plan(pathlib.Path(checkout, "todo.md")).reason)
with self.subTest("a malformed row"): with self.subTest("a malformed row"):
pathlib.Path(checkout, "todo.md").write_text(todo("| x | 0.1.0 |"), encoding="utf-8") pathlib.Path(checkout, "todo.md").write_text(todo("| x | 0.1.0 |"), encoding="utf-8")
self.assertIn("the checkout's todo.md:", checkout_plan(checkout).reason) self.assertIn("the checkout's todo.md:", checkout_plan(pathlib.Path(checkout, "todo.md")).reason)
class History(unittest.TestCase): class History(unittest.TestCase):
@@ -599,6 +599,30 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n") self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "No scoring run due.\n") self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "No scoring run due.\n")
def test_reads_the_plan_and_the_history_from_the_folders_of_the_checkout_the_config_names(self):
self.config.write_text(PROJECT_CONFIG.replace("checkout:todo.md", "checkout:plan/todo.md").replace("checkout:docs/comprehension-history.md", "checkout:records/comprehension-history.md"))
rest = ("| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
self.commit("Move the plan", {"plan/todo.md": (self.checkout / "todo.md").read_text()})
self.git("push", "-q", "origin", "HEAD:main")
self.git("fetch", "-q", "origin")
self.commit("Ship item 1", {"plan/todo.md": todo(*rest), "todo.md": "the owners' own notes\n"})
self.assertIn("records 0:", self.run_tool("scoring-run-owed").stderr)
history = "# Comprehension history\n\n" + SCORING
self.commit("Record both runs", {"records/comprehension-history.md": history + "\n" + SCORING.replace("PR #1 at", "PR #1 rerun at")})
done = self.run_tool("scoring-run-owed")
self.assertEqual((done.returncode, done.stdout), (0, "No scoring run owed.\n"), done.stderr)
def test_a_history_outside_the_checkout_owes_none_and_has_no_ruling_base_each_saying_it_is_not_supported(self):
self.config.write_text(PROJECT_CONFIG.replace("checkout:docs/comprehension-history.md", "folder:comprehension-history.md"))
self.ship_item_1()
outside = self.config.parent / "comprehension-history.md"
owed = self.run_tool("scoring-run-owed")
self.assertEqual((owed.returncode, owed.stdout), (0, "No scoring run owed.\n"))
self.assertEqual(owed.stderr, f"larv-review doesn't support a comprehension history outside the checkout, so it cannot tell whether the chunk owes a scoring run: {outside}\n")
base = self.run_tool("ruling-base")
self.assertEqual((base.returncode, base.stdout), (1, ""))
self.assertIn(f"larv-review doesn't support a comprehension history outside the checkout: no commit holds {outside}", base.stderr)
def test_a_project_with_no_plan_or_no_items_table_owes_none(self): def test_a_project_with_no_plan_or_no_items_table_owes_none(self):
self.ship_item_1() self.ship_item_1()
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1) self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
+26 -3
View File
@@ -9,6 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import write_config
from larv_review.scoring_setup import bullets, CLAUDE_MD, file_globs, preloaded_files, prepare_scoring, project_values, removed_setup, score_bullets from larv_review.scoring_setup import bullets, CLAUDE_MD, file_globs, preloaded_files, prepare_scoring, project_values, removed_setup, score_bullets
from failure import Failure from failure import Failure
from test_env import isolated_env from test_env import isolated_env
@@ -64,11 +65,11 @@ class ProjectValues(unittest.TestCase):
class FileGlobs(unittest.TestCase): class FileGlobs(unittest.TestCase):
def test_names_no_test_files_where_every_glob_holds_none(self): def test_names_no_test_files_where_every_glob_holds_none(self):
self.assertEqual(file_globs(["bin/a.py", "tests/x.py", "README.md"]), "`bin/**` and `README.md`") self.assertEqual(file_globs(["bin/a.py", "tests/x.py", "README.md"], []), "`bin/**` and `README.md`")
def test_gives_one_glob_per_directory_and_each_top_level_file_leaving_out_tests_and_the_forbidden_files(self): def test_gives_one_glob_per_directory_and_each_top_level_file_leaving_out_tests_and_the_forbidden_files(self):
paths = ["README.md", "ci.sh", "bin/run", "bin/a/main.py", "bin/a/test_main.py", "docs/decisions.md", "docs/guide.md", "todo.md", "tests/x.py", "web/app.test.ts"] paths = ["README.md", "ci.sh", "bin/run", "bin/a/main.py", "bin/a/test_main.py", "docs/decisions.md", "docs/guide.md", "plan/todo.md", "tests/x.py", "web/app.test.ts"]
self.assertEqual(file_globs(paths), "`bin/**` except test files, `docs/**`, `README.md` and `ci.sh`, test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder") self.assertEqual(file_globs(paths, ["plan/todo.md", "docs/decisions.md"]), "`bin/**` except test files, `docs/**`, `README.md` and `ci.sh`, test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder")
class Bullets(unittest.TestCase): class Bullets(unittest.TestCase):
@@ -89,6 +90,7 @@ class PrepareScoring(unittest.TestCase):
(self.checkout / "README.md").write_text("# P\n") (self.checkout / "README.md").write_text("# P\n")
(self.checkout / "bin").mkdir() (self.checkout / "bin").mkdir()
(self.checkout / "bin" / "tool.py").write_text("") (self.checkout / "bin" / "tool.py").write_text("")
self.config = write_config(self.root, self.checkout) / "config.toml"
def git(self, *args): def git(self, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
@@ -144,6 +146,27 @@ class PrepareScoring(unittest.TestCase):
self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason)
self.assertTrue(checkout.exists()) self.assertTrue(checkout.exists())
def test_reads_the_values_and_forbids_the_records_where_the_config_puts_them(self):
values = "# A\n\n## Scoring run\n\n- Language: Go\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n"
self.config.write_text(self.config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:todo.md"', '"checkout:plan/todo.md"').replace('"checkout:docs/comprehension-history.md"', '"folder:comprehension-history.md"'))
(self.config.parent / "AGENTS.md").write_text(values)
(self.checkout / "plan").mkdir()
(self.checkout / "plan" / "todo.md").write_text("# todo\n")
self.commit("# The owners' own AGENTS.md, with no values\n")
ran = self.prepare("`README.md`")
assert isinstance(ran, str), ran
junior = pathlib.Path(ran.splitlines()[2]).read_text()
self.assertIn("Your background: ~2 years in Go,", junior)
self.assertIn("every non-test tracked file: `bin/**`, `AGENTS.md` and `README.md`. Do NOT open plan/todo.md, docs/decisions.md or docs/reading-cost.md (the plan, the decision log and past chunks' reading cost), nor any review output.", junior)
def test_forbids_any_record_of_a_past_panel_where_the_config_puts_every_record_outside_the_checkout(self):
self.config.write_text(self.config.read_text().replace('"checkout:', '"folder:').replace('"folder:README.md"', '"checkout:README.md"'))
(self.config.parent / "AGENTS.md").write_text("# A\n\n## Scoring run\n\n- Language: Go\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
self.commit()
ran = self.prepare("`README.md`")
assert isinstance(ran, str), ran
self.assertIn("every non-test tracked file: `bin/**` and `README.md`. Do NOT open any record of a past panel, nor any review output.", pathlib.Path(ran.splitlines()[2]).read_text())
def test_refuses_writing_nothing_where_the_project_gives_no_values(self): def test_refuses_writing_nothing_where_the_project_gives_no_values(self):
self.commit() self.commit()
ran = self.run_tool("prepare-scoring") ran = self.run_tool("prepare-scoring")
+10 -8
View File
@@ -1,12 +1,14 @@
import datetime import datetime
from review_rules.comprehension_history import entries, HISTORY from project_config.settings import Place
from release_plan.release_standing import held_at
from review_rules.comprehension_history import entries
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, git from git_cli.git_repo import git
def unmeasured_cut(default: str, checkout: str) -> str | None | Failure: def unmeasured_cut(default: str, history: Place, checkout: str) -> str | None | Failure:
"""Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's history is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one. """Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's history, the file at history, is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one.
The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run. The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run.
@@ -20,10 +22,10 @@ def unmeasured_cut(default: str, checkout: str) -> str | None | Failure:
if earlier is None: if earlier is None:
return None return None
since = git("log", "-1", "--format=%ct", earlier, cwd=checkout) since = git("log", "-1", "--format=%ct", earlier, cwd=checkout)
history = file_at(default, HISTORY, checkout) text = held_at(default, history, checkout)
if isinstance(since, Failure) or isinstance(history, Failure): if isinstance(since, Failure) or isinstance(text, Failure):
return since if isinstance(since, Failure) else history return since if isinstance(since, Failure) else text
if any(at > int(since) for at in (seconds(entry.time) for entry in entries(history) if not entry.paired)): if any(at > int(since) for at in (seconds(entry.time) for entry in entries(text) if not entry.paired)):
return None return None
return f"{newest}, cut with no scoring run since {earlier}" return f"{newest}, cut with no scoring run since {earlier}"
+5
View File
@@ -58,6 +58,11 @@ def located(directory: str | None, home: pathlib.Path) -> ProjectConfig | Failur
return load(pathlib.Path(lines[0]), pathlib.Path(lines[1]).parent, home) return load(pathlib.Path(lines[0]), pathlib.Path(lines[1]).parent, home)
def project() -> ProjectConfig | Failure:
"""The config of the project whose checkout holds the current directory, under the user's home."""
return located(None, pathlib.Path.home())
def goals_file(directory: str, home: pathlib.Path) -> pathlib.Path | Failure: def goals_file(directory: str, home: pathlib.Path) -> pathlib.Path | Failure:
"""The file holding the premises, `## Goals` and `## Audience`, of the project whose checkout holds directory, as its config under home names it.""" """The file holding the premises, `## Goals` and `## Audience`, of the project whose checkout holds directory, as its config under home names it."""
config = located(directory, home) config = located(directory, home)