Move larv-review's mechanical rules into a tested bin/larv-review, so the skill says only when to run it and what each answer means

This commit is contained in:
2026-10-09 01:02:48 +02:00
parent c7f6099945
commit 77fef49fce
18 changed files with 851 additions and 90 deletions
View File
+73
View File
@@ -0,0 +1,73 @@
import dataclasses
import subprocess
from failure import Failure
from larv_review.rules import HistoryChange
HISTORY = "docs/comprehension-history.md"
@dataclasses.dataclass(frozen=True)
class Repository:
"""The checkout the tool runs in: its top folder, and the default branch's ref after a fetch, `origin/<branch>` with a remote."""
top: str
default: str
def git(*args: str) -> str | Failure:
try:
ran = subprocess.run(["git", *args], capture_output=True, text=True)
except (OSError, ValueError) as failure:
return Failure(f"git could not start: {failure}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def repository() -> Repository | Failure:
top = git("rev-parse", "--show-toplevel")
if isinstance(top, Failure):
return top
remotes = git("remote")
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure):
return fetched
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
if isinstance(default, Failure):
return Failure(f"origin names no default branch; set it with `git remote set-head origin --auto`: {default.reason}")
return Repository(top.strip(), default.strip())
for branch in ("main", "master"):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
return Repository(top.strip(), branch)
return Failure("no origin remote, and no main or master branch to take as the default branch")
def file_at(revision: str, path: str) -> str | Failure:
"""A file's text at a revision, empty where the revision does not hold it."""
if isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}:{path}"), Failure):
return ""
return git("show", f"{revision}:{path}")
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
changes = []
for commit in commits.split():
before = file_at(f"{commit}^1", HISTORY)
after = file_at(commit, HISTORY)
if isinstance(before, Failure):
return before
if isinstance(after, Failure):
return after
changes.append(HistoryChange(commit, before, after))
return changes
def landed_since_release(default: str) -> bool | Failure:
"""Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none."""
tag = git("describe", "--tags", "--abbrev=0", "--match", "v*", default)
count = git("rev-list", "--count", default if isinstance(tag, Failure) else f"{tag.strip()}..{default}")
return count if isinstance(count, Failure) else int(count) > 0
+110
View File
@@ -0,0 +1,110 @@
import dataclasses
import os
import re
from markdown_sections import sections
TITLE = "# Comprehension history\n"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
SEAT_PLACES = re.compile(r"^.+, (decided by|hardest first|would restructure first):$")
# `path:line` or `:line`, then the unit's name where one follows.
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
@dataclasses.dataclass(frozen=True)
class Place:
path: str
name: str | None
@dataclasses.dataclass(frozen=True)
class Entry:
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither."""
heading: str
time: str
commit: str
against: str | None
ruling: str | None
places: list[Place]
@dataclasses.dataclass(frozen=True)
class ScoringRun:
heading: str
commit: str
places: list[Place]
def entries(history: str) -> list[Entry]:
"""Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out."""
found = []
for heading, bodies in sections(history).items():
if named := HEADING.match(heading):
body = "\n".join(bodies)
ruling = RULING.search(body)
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body)))
return found
def scoring_runs(history: str) -> list[ScoringRun]:
"""Each scoring run, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out."""
return [ScoringRun(entry.heading, entry.commit, entry.places) for entry in entries(history) if entry.against is None]
def seat_places(body: str) -> list[Place]:
places = []
listing = False
for line in body.splitlines():
if SEAT_PLACES.match(line):
listing = True
elif listing and line.startswith("- "):
places += bullet_places(line)
elif not line.startswith(" "):
listing = False
return places
def bullet_places(bullet: str) -> list[Place]:
"""A `:line` with no path is in the file named before it in the bullet."""
places = []
path = ""
for match in PLACE.finditer(bullet):
path = match.group(1) or path
if path:
places.append(Place(path, match.group(2)))
return places
def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]:
"""Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
found = []
dropped = []
before = ""
for place in places:
candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)]
nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates
if len(nearest) == 1:
before = nearest[0]
found.append(Place(before, place.name))
else:
dropped.append(place)
return found, dropped
def appended(history: str, entry: str) -> str:
"""The history with entry added last; an empty history gets the file's title first."""
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
return f"{text}\n{entry}"
def entry_text(heading: str, lines: list[str], table: list[list[str]], seats: list[tuple[str, list[str]]]) -> str:
"""An entry in the history's format: the heading, any lines such as `Ruling: same`, a table whose first row is its header, and under each seat's label its places, one bullet each."""
header, *rows = table
parts = [f"## {heading}", *lines, "\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)])]
parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places]
return "\n\n".join(parts) + "\n"
def row_text(cells: list[str]) -> str:
return "| " + " | ".join(cells) + " |"
+205
View File
@@ -0,0 +1,205 @@
"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format.
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.
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
ruling, by its heading's time, is better; a merge commit is one change against its first parent.
With none, the base the history's first paired ruling names; with no ruling either, the merge base
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.
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
floor, or when a release the default branch's todo.md names has no item left in the checkout's
todo.md, less the items shipped, and work has landed towards it: the chunk ships one of its items,
or it is the earliest release the default branch's todo.md names and the default branch has a
commit after its newest v* tag, or has no such tag.
record-ruling and record-scoring read a seats file: a first line naming what the seats read, then
each seat's line, each followed by its places, one `- ` bullet each, as the history writes them:
PR #231 at abc1234, against def5678
Mid A: worse
- `bin/x.py:12` `run`: three branches to hold at once
Inherited architect: worse
- `bin/x.py:12` `run`: ...
record-ruling takes Mid A's and the inherited architect's votes, better, same or worse; a better or
worse vote naming no `path:line` place counts as same. When the two counted votes differ, it
appends nothing and says to add the maintainability senior's and Junior A's lines. Otherwise the
ruling is the vote that leads each other vote by two or more, else same, and it appends the ruling.
record-scoring takes Junior A's, Mid A's, the maintainability senior's and the inherited
architect's lines in that order, each `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency
<n>, Overall <n>`, each score from 1 to 10 and the overall at most 1 above the seat's lowest
dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded
half up to two decimals, and prints the means and each one under the floor of 7.0.
Each record is appended to the history, created when missing, under a heading of the current UTC
time and the seats file's first line.
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
breaks the shape above, or when git cannot start, finds no checkout or no default branch, or the
history or todo.md cannot be read or written.
"""
import pathlib
import sys
import time
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 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>"
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
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):
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
def ruling_base(repo: Repository) -> Failure | None:
changes = history_changes(repo.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.")
return None
history = file_at(repo.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.")
return None
merge_base = git("merge-base", "HEAD", repo.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}.")
return None
def round_count(repo: Repository) -> Failure | None:
titles = git("log", "--format=%s", f"{repo.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 ''}")
return None
def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None:
before = file_at(repo.default, "todo.md")
if isinstance(before, Failure):
return before
try:
after = pathlib.Path(repo.top, "todo.md").read_text(encoding="utf-8")
except FileNotFoundError:
after = ""
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
planned = plan_items(before)
if isinstance(planned, Failure):
return planned
chunk = plan_items(after)
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)
if isinstance(landed, Failure):
return landed
reasons = scoring_run_due(planned, chunk, ids, landed)
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
return None
def record(repo: Repository, seats_file: pathlib.Path, paired: bool, now: str) -> 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:
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:
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)
def failed(failure: Failure) -> int:
print(failure.reason, file=sys.stderr)
return 1
+97
View File
@@ -0,0 +1,97 @@
import dataclasses
import decimal
import re
from rank_todo import cells, ITEMS_HEADER, table_rows
from larv_review.seats import DIMENSIONS
from larv_review.history import entries, Entry
from failure import Failure
CAP = 3
FLOOR = decimal.Decimal("7.0")
PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+) round ([0-9]+):")
@dataclasses.dataclass(frozen=True)
class HistoryChange:
"""A merged change on the default branch that touched the history, and the history before and after it."""
commit: str
before: str
after: str
@dataclasses.dataclass(frozen=True)
class PlanItem:
id: int
release: tuple[int, int, int]
tagline: str
def means(scores: dict[str, list[str]]) -> list[decimal.Decimal]:
"""The seats' mean of each score, in DIMENSIONS' order, rounded half up to two decimals."""
return [(sum((decimal.Decimal(seat[index]) for seat in scores.values()), decimal.Decimal(0)) / len(scores)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP) for index in range(len(DIMENSIONS))]
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {mean}" for name, mean in zip(DIMENSIONS, found) if mean < FLOOR]
def round_counts(titles: list[str]) -> dict[str, int]:
"""Each pass's highest round among the branch's `Answer <pass> round <n>:` commit titles; a pass with none has 0."""
counts = dict.fromkeys(PASSES, 0)
for title in titles:
if named := ROUND.match(title):
counts[named.group(1)] = max(counts.get(named.group(1), 0), int(named.group(2)))
return counts
def measured_commit(changes: list[HistoryChange]) -> str | None:
"""The newest change, of changes given newest first, that adds a scoring run to the history, or whose last added paired ruling is better."""
for change in changes:
held = {entry.heading for entry in entries(change.before)}
added = [entry for entry in entries(change.after) if entry.heading not in held]
rulings = sorted((entry for entry in added if entry.against), key=lambda entry: entry.time)
if any(entry.against is None for entry in added) or rulings and rulings[-1].ruling == "better":
return change.commit
return None
def first_ruling(history: str) -> Entry | None:
rulings = sorted((entry for entry in entries(history) if entry.against), key=lambda entry: entry.time)
return rulings[0] if rulings else None
def plan_items(todo: str) -> list[PlanItem] | Failure:
"""The ID, release and tagline of each row in a todo.md's items table, in the shape `rank_todo.py --help` shows; a plan with no table has no items."""
lines = todo.splitlines()
if ITEMS_HEADER not in lines:
return []
table = table_rows(lines, ITEMS_HEADER)
if isinstance(table, Failure):
return table
items = []
for row in table.rows:
found = cells(row, 10)
if isinstance(found, Failure):
return found
id_, release, _, tagline, *_ = found
if not re.fullmatch(r"[0-9]+", id_) or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
return Failure(f"a todo.md row has no whole-number ID or no semver release: {row}")
major, minor, patch = (int(part) for part in release.split("."))
items.append(PlanItem(int(id_), (major, minor, patch), tagline))
return items
def scoring_run_due(before: list[PlanItem], after: list[PlanItem], ships: list[int], landed: bool) -> list[str]:
"""Why the chunk takes a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release before names and landed holds."""
plan = {item.id: item for item in before + after}
shipped = [plan[id_] for id_ in ships]
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
left = {item.release for item in after if item.id not in ships}
named = {item.release for item in before} | {item.release for item in shipped}
earliest = min((item.release for item in before), default=None)
for release in sorted(named - left):
if any(item.release == release for item in shipped) or release == earliest and landed:
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
return reasons
+82
View File
@@ -0,0 +1,82 @@
import dataclasses
import re
from failure import Failure
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
FIRST_SEATS = ("Mid A", "Inherited architect")
SPLIT_SEATS = ("Maintainability senior", "Junior A")
SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", "Inherited architect")
SEAT_LINE = re.compile(r"^(Junior A|Mid A|Maintainability senior|Inherited architect): (.+)$")
SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS))
VOTES = ("better", "same", "worse")
@dataclasses.dataclass(frozen=True)
class Seat:
name: str
said: str
places: list[str]
@dataclasses.dataclass(frozen=True)
class Report:
"""A seats file: what the seats read, `<PR or branch> at <commit>`, with `, against <base>` for a paired ruling, then each seat's line and its places."""
read: str
seats: list[Seat]
def report(text: str) -> Report | Failure:
lines = [line for line in text.splitlines() if line.strip()]
if not lines:
return Failure("the seats file is empty; its first line names what the seats read: <PR or branch> at <commit>")
seats: list[Seat] = []
for line in lines[1:]:
if seat := SEAT_LINE.match(line):
if seat.group(1) in [known.name for known in seats]:
return Failure(f"{seat.group(1)} appears twice in the seats file")
seats.append(Seat(seat.group(1), seat.group(2).strip(), []))
elif seats and line.startswith("- "):
seats[-1].places.append(line[2:].strip())
elif seats and seats[-1].places and line.startswith(" "):
seats[-1].places[-1] += " " + line.strip()
else:
return Failure(f"the seats file has a line that is neither a seat's line nor one of its places: {line}")
return Report(lines[0].strip(), seats)
def votes(seats: list[Seat]) -> dict[str, str] | Failure:
"""Each seat's vote as it counts: a better or worse vote naming no `path:line` place counts as same."""
names = [seat.name for seat in seats]
if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)):
return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
if unknown := [seat for seat in seats if seat.said not in VOTES]:
return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse")
return {seat.name: seat.said if seat.said == "same" or any(re.search(r"`[^`\s]*:\d+`", place) for place in seat.places) else "same" for seat in seats}
def ruling(counted: list[str]) -> str | None:
"""The vote that leads each other vote by two or more, else same; None when only the first two seats voted and they differ, so two more must vote."""
if len(counted) == 2 and counted[0] != counted[1]:
return None
for vote in VOTES:
if all(counted.count(vote) >= counted.count(other) + 2 for other in VOTES if other != vote):
return vote
return "same"
def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure:
"""Each seat's five scores as written, in DIMENSIONS' order."""
if [seat.name for seat in seats] != list(SCORING_SEATS):
return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order; the file has {', '.join(seat.name for seat in seats) or 'none'}")
found = {}
for seat in seats:
if not (written := SCORES.fullmatch(seat.said)):
return Failure(f"{seat.name}'s line is not {', '.join(name + ' <score>' for name in DIMENSIONS)}: {seat.said}")
values = [float(value) for value in written.groups()]
if not all(1 <= value <= 10 for value in values):
return Failure(f"{seat.name}'s scores are not each from 1 to 10: {seat.said}")
if values[-1] > min(values[:-1]) + 1:
return Failure(f"{seat.name}'s overall exceeds their lowest dimension by more than 1; ask the seat to rescore: {seat.said}")
found[seat.name] = list(written.groups())
return found