Keep the history's writer beside its reader, read plan rows with rank_todo, and fetch only for commands that read the default branch

This commit is contained in:
2026-10-09 01:10:01 +02:00
parent 77fef49fce
commit 53ed5150be
8 changed files with 189 additions and 162 deletions
+73 -79
View File
@@ -2,9 +2,10 @@
usage: larv-review ruling-base | round-count | needs-scoring-run <item ID>... | record-ruling <seats file> | record-scoring <seats file>
Run it inside a project checkout or one of its worktrees. It first fetches origin, when the checkout
has that remote, and takes origin's default branch, or else the local main or master, as the
default branch. The history is docs/comprehension-history.md in the checkout.
Run it inside a project checkout or one of its worktrees. ruling-base, round-count and
needs-scoring-run first fetch origin, when the checkout has that remote, and take origin's default
branch, or else the local main or master, as the default branch. The history is
docs/comprehension-history.md in the checkout.
ruling-base prints the commit a paired ruling reads against, then how it was found: the default
branch's newest merged change that adds a scoring run to the history, or whose last added paired
@@ -14,7 +15,7 @@ of HEAD and the default branch.
round-count prints, for each pass, the highest <n> among this branch's commit titles opening
`Answer <pass> round <n>:`, counting commits the default branch does not hold, and marks a pass at
the cap of 3 rounds.
the cap of 3 rounds, and a name in such a title that is no pass.
needs-scoring-run prints why the chunk shipping the given todo.md item IDs takes a scoring run, or
`No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension
@@ -57,14 +58,14 @@ history or todo.md cannot be read or written.
import pathlib
import sys
import time
import typing
from larv_review.history import appended, entry_text, HEADING
from larv_review.rules import CAP, first_ruling, means, measured_commit, plan_items, round_counts, scoring_run_due, under_floor
from larv_review.seats import DIMENSIONS, Report, report, ruling, scores, votes
from larv_review.history import appended, HEADING, heading, ruling_entry, scoring_entry
from larv_review.rules import CAP, first_ruling, means, measured_commit, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes
from larv_review.git import default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top
from larv_review.seats import DIMENSIONS, report, scores
from failure import Failure
from larv_review.git import file_at, git, HISTORY, history_changes, landed_since_release, Repository, repository
from file_writes import replace_file
from loop_claude.transcript_archive import utc
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run <item ID>... | record-ruling <seats file> | record-scoring <seats file>"
@@ -74,59 +75,64 @@ def main(argv: list[str]) -> int:
print(__doc__.strip())
return 0
command, *given = argv or [""]
valid = {"ruling-base": not given, "round-count": not given, "needs-scoring-run": bool(given) and all(id_.isdigit() for id_ in given), "record-ruling": len(given) == 1, "record-scoring": len(given) == 1}
if not valid.get(command):
if command in ("ruling-base", "round-count") and not given:
done = with_default_branch(ruling_base if command == "ruling-base" else round_count)
elif command == "needs-scoring-run" and given and all(id_.isdigit() for id_ in given):
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]))
elif command in ("record-ruling", "record-scoring") and len(given) == 1:
done = record(pathlib.Path(given[0]), command == "record-ruling")
else:
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
return 1
repo = repository()
if isinstance(repo, Failure):
return failed(repo)
if command == "ruling-base":
done = ruling_base(repo)
elif command == "round-count":
done = round_count(repo)
elif command == "needs-scoring-run":
done = needs_scoring_run(repo, [int(id_) for id_ in given])
else:
done = record(repo, pathlib.Path(given[0]), command == "record-ruling", utc(time.time()))
return failed(done) if isinstance(done, Failure) else 0
if isinstance(done, Failure):
print(done.reason, file=sys.stderr)
return 1
return 0
def ruling_base(repo: Repository) -> Failure | None:
changes = history_changes(repo.default)
def with_default_branch(command: typing.Callable[[str], Failure | None]) -> Failure | None:
default = default_branch()
return default if isinstance(default, Failure) else command(default)
def ruling_base(default: str) -> Failure | None:
changes = history_changes(default)
if isinstance(changes, Failure):
return changes
if found := measured_commit(changes):
print(f"{found}\nThe newest merged change on {repo.default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.")
print(f"{found}\nThe newest merged change on {default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.")
return None
history = file_at(repo.default, HISTORY)
history = file_at(default, HISTORY)
if isinstance(history, Failure):
return history
if (first := first_ruling(history)) and first.against:
print(f"{first.against}\nNo merged change on {repo.default} adds a scoring run or a better ruling; the base its first paired ruling names.")
print(f"{first.against}\nNo merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names.")
return None
merge_base = git("merge-base", "HEAD", repo.default)
merge_base = git("merge-base", "HEAD", default)
if isinstance(merge_base, Failure):
return merge_base
print(f"{merge_base.strip()}\nNo merged change on {repo.default} adds a scoring run or a paired ruling; the merge base of HEAD and {repo.default}.")
print(f"{merge_base.strip()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.")
return None
def round_count(repo: Repository) -> Failure | None:
titles = git("log", "--format=%s", f"{repo.default}..HEAD")
def round_count(default: str) -> Failure | None:
titles = git("log", "--format=%s", f"{default}..HEAD")
if isinstance(titles, Failure):
return titles
for name, count in round_counts(titles.splitlines()).items():
print(f"{name}: {count}{', at the cap' if count >= CAP else ''}")
print(f"{name}: {count}{', at the cap' if count >= CAP else ''}{'' if name in PASSES else ', not a pass: check the commit title'}")
return None
def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None:
before = file_at(repo.default, "todo.md")
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
checkout = top()
if isinstance(checkout, Failure):
return checkout
before = file_at(default, "todo.md")
if isinstance(before, Failure):
return before
try:
after = pathlib.Path(repo.top, "todo.md").read_text(encoding="utf-8")
after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")
except FileNotFoundError:
after = ""
except (OSError, UnicodeDecodeError) as failure:
@@ -138,8 +144,8 @@ def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None:
if isinstance(chunk, Failure):
return chunk
if unknown := sorted(set(ids) - {item.id for item in planned + chunk}):
return Failure(f"neither {repo.default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}")
landed = landed_since_release(repo.default)
return Failure(f"neither {default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}")
landed = landed_since_release(default)
if isinstance(landed, Failure):
return landed
reasons = scoring_run_due(planned, chunk, ids, landed)
@@ -147,59 +153,47 @@ def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None:
return None
def record(repo: Repository, seats_file: pathlib.Path, paired: bool, now: str) -> Failure | None:
def record(seats_file: pathlib.Path, paired: bool) -> Failure | None:
try:
given = report(seats_file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {seats_file}: {failure}")
if isinstance(given, Failure):
return given
heading = f"{now}, {given.read}"
if not (named := HEADING.match(heading)) or bool(named.group(4)) != paired:
title = heading(time.time(), given.read)
if not (named := HEADING.match(title)) or bool(named.group(4)) != paired:
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {given.read}")
entry = ruling_entry(heading, given) if paired else scoring_entry(heading, given)
if isinstance(entry, Failure) or entry is None:
return entry
history = pathlib.Path(repo.top, HISTORY)
try:
text = history.read_text(encoding="utf-8") if history.exists() else ""
history.parent.mkdir(parents=True, exist_ok=True)
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
unwritten = replace_file(history, appended(text, entry).encode())
if unwritten:
return Failure(f"could not write {history}: {unwritten.reason}")
print(f"Appended to {history}.")
return None
def ruling_entry(heading: str, given: Report) -> str | Failure | None:
"""The ruling's entry, or None, after saying which seats to add, when the first two counted votes differ."""
counted = votes(given.seats)
if isinstance(counted, Failure):
return counted
tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items())
result = ruling(list(counted.values()))
if result is None:
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.")
return None
print(f"Ruling: {result}. Votes as counted: {tally}.")
cells = [[seat.name, counted[seat.name] if counted[seat.name] == seat.said else f"same (voted {seat.said}, naming no place)"] for seat in given.seats]
return entry_text(heading, [f"Ruling: {result}"], [["Seat", "Vote"], *cells], [(f"{seat.name}, decided by:", seat.places) for seat in given.seats])
def scoring_entry(heading: str, given: Report) -> str | Failure:
if paired:
counted = votes(given.seats)
if isinstance(counted, Failure):
return counted
tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items())
ruled = ruling(list(counted.values()))
if ruled is None:
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.")
return None
print(f"Ruling: {ruled}. Votes as counted: {tally}.")
return append(ruling_entry(title, given.seats, counted, ruled))
found = scores(given.seats)
if isinstance(found, Failure):
return found
mean = means(found)
under = under_floor(mean)
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {'Under the floor of 7.0: ' + ', '.join(under) if under else 'None under the floor of 7.0'}.")
rows = [[seat, *values] for seat, values in found.items()] + [["Mean", *map(str, mean)]]
labels = [(f"{seat.name}, {'would restructure first' if seat.name == 'Inherited architect' else 'hardest first'}:", seat.places) for seat in given.seats]
return entry_text(heading, [], [["Seat", *DIMENSIONS], *rows], labels)
return append(scoring_entry(title, given.seats, found, [str(value) for value in mean]))
def failed(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
def append(entry: str) -> Failure | None:
checkout = top()
if isinstance(checkout, Failure):
return checkout
history = pathlib.Path(checkout, HISTORY)
try:
text = history.read_text(encoding="utf-8") if history.exists() else ""
history.parent.mkdir(parents=True, exist_ok=True)
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {history}: {failure}")
if unwritten := replace_file(history, appended(text, entry).encode()):
return Failure(f"could not write {history}: {unwritten.reason}")
print(f"Appended to {history}.")
return None