Compare commits

..

22 Commits

Author SHA1 Message Date
lilleman dd56ad8fdd Answer stability round 3: no finding 2026-10-09 01:50:13 +02:00
lilleman 28d027ffef Rescore: the paired ruling at c1133ed against 12d6d75 is same, 2 votes to 2 2026-10-09 01:48:44 +02:00
lilleman c1133edf39 Answer architecture round 5: return the heading as a dataclass, read the Mean line as its own field, mark an entry paired explicitly, move metric-bench's path resolution back to metric_bench, and split the scoring trigger into named steps 2026-10-09 01:44:53 +02:00
lilleman efed78bf5e Answer prose round 1: move the tool paragraph below the reviewer prompt rule, name the commands its and it pointed at, state the seats file's first line and the migration's two lines, and rewrite four --help paragraphs 2026-10-09 01:37:56 +02:00
lilleman 642a8bc80b Answer product-owner round 2: rewrap the needs-scoring-run help paragraph; fix in the stability round's commit 2026-10-09 01:34:17 +02:00
lilleman 8da25d8c55 Answer stability round 2: no finding; also rewraps a --help paragraph for product-owner round 2 2026-10-09 01:34:17 +02:00
lilleman acbe3ec8b5 Answer architecture round 4: no finding; the architect and principles audit confirm round 3's fixes 2026-10-09 01:33:12 +02:00
lilleman 1c5551a145 Answer product-owner round 1: show a vote counted as same in the printed tally, list the seat labels, take no item ID for a chunk that ships none, say each record appends; fixes in the stability round's commit 2026-10-09 01:32:19 +02:00
lilleman 56ac929634 Answer stability round 1: refuse two more seats once the first two agree, compare scores as decimals, read only ASCII digits as item IDs, refuse a shallow clone's base search, and sort release candidates below their release; also holds product-owner round 1's fixes 2026-10-09 01:32:19 +02:00
lilleman e2cb4a26f8 Answer architecture round 3: name the fetch flag stale_ok, and say in --help which commands exit 1 when origin cannot be fetched 2026-10-09 01:26:30 +02:00
lilleman fb764a7549 Answer security round 1: no finding 2026-10-09 01:24:52 +02:00
lilleman 9c2f982741 Answer architecture round 2: split record into its two commands, accept a dated first line only with a Mean line alone, read a default branch without a plan table as empty, and fetch where an answer needs origin as it is 2026-10-09 01:24:48 +02:00
lilleman 05efbb1d8a Answer architecture round 1: move the base fallback, heading check and seat names into the pure modules, move legacy scores through record-scoring, and read origin as last fetched when a fetch fails 2026-10-09 01:18:57 +02:00
lilleman 53ed5150be Keep the history's writer beside its reader, read plan rows with rank_todo, and fetch only for commands that read the default branch 2026-10-09 01:10:01 +02:00
lilleman 77fef49fce 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 2026-10-09 01:02:48 +02:00
lilleman c7f6099945 Merge pull request 'Bench questions a script answers from the code against the panel's hardest places, and keep only the result' (#230) from item-78 into main 2026-10-09 00:48:47 +02:00
lilleman 45276fc3bf Answer prose round 1: give the answer score as the Jaccard index the bench computed 2026-10-09 00:47:50 +02:00
lilleman 243cd676f8 Answer prose round 1: split the question bench's paragraph, count its runs against the history's six, say what the answer score counts, and drop item 85's pointer to item 78 2026-10-09 00:47:44 +02:00
lilleman 0050cd6772 Answer architecture round 1: delete question-bench, keep its run's results in item 77 citing the commit that held it, and correct item 85's mention of item 78 2026-10-09 00:46:44 +02:00
lilleman a9ec529158 Record question-bench's run: its misses rank the panel's places at a coin toss, so no question enters review 2026-10-09 00:30:01 +02:00
lilleman 083cc782d0 Bench questions a script answers from the code against the panel's hardest places 2026-10-09 00:16:45 +02:00
lilleman 08c5625ac7 Merge pull request 'Measure what would lower review's token use: bench static metrics against the panel's hardest places, and rescore item 73 by its reports' measured cost' (#229) from item-77 into main 2026-10-08 23:15:11 +02:00
21 changed files with 1171 additions and 109 deletions
+3
View File
@@ -19,6 +19,9 @@
!bin/
!bin/failure.py
!bin/file_writes.py
!bin/larv-review
!bin/larv_review/
!bin/larv_review/*.py
!bin/loop-claude
!bin/loop_claude/
!bin/loop_claude/**/
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- larv-review's mechanical rules run in the new, tested `bin/larv-review`: the paired ruling's base (`ruling-base`), each pass's round count (`round-count`), the scoring run's trigger (`needs-scoring-run <item ID>...`), and the vote count, means and history format (`record-ruling` and `record-scoring`, which read a seats file and append to `docs/comprehension-history.md`). The skill says when to run each and what its answer means. A seats file line the tool cannot read fails the run, so a mistyped vote never counts as same. The base search compares the history before and after each merged change, so it no longer depends on how a line is worded, and orders a change's rulings by their headings' times. A release whose last plan item moves to another release is due a scoring run too, once work has landed towards it. A seats file must name commits the checkout holds. Scores a `comprehension floor:` decision entry still holds move into the history through `record-scoring`, as a `Mean:` line. When origin cannot be fetched, the tool reads it as last fetched and says so.
- The new `bin/metric-bench` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest: cognitive complexity, length, shared state and change spread, each scored by how well it ranks the named functions above the rest. No metric enters review yet.
- larv-review blocks a merge when simulated readers rule that the PR makes the project read worse than the last measured commit: the default branch's newest merged change that added a scoring run to `docs/comprehension-history.md`, or whose last ruling there is better. A ruling of same leaves that commit in place, so a worse ruling may name places earlier chunks wrote. In each architecture pass Mid A and the inherited architect vote better, same or worse; when they disagree, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same, and a vote that names no place counts as same. A worse ruling never ships: after three rounds larv-review asks you for another round, a no leaves the PR unmerged, and so does an unattended run. The four-seat scoring run checks the comprehension floor only when a chunk ships or removes a release's last plan item, or ships an item naming the floor; between those runs the floor blocks nothing. A score under the floor blocks the merge until fixed or until you decide to ship; a decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours.
- larv-review reruns fewer passes after a fix. A fix reruns the pass whose 🔴 or 🟡 it answers, plus stability when the fix changes behaviour, security when it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and architecture when it carries an architectural decision. A rerun reviews only what changed since that pass last reviewed. A fix for a 🟢, a ❓ or any prose finding reruns no pass, and prose takes one round.
+1
View File
@@ -67,6 +67,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
- `larv-review <command>` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format; `larv-review --help` states them.
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from larv_review import main
sys.exit(main.main(sys.argv[1:]))
View File
+96
View File
@@ -0,0 +1,96 @@
import re
import subprocess
from failure import Failure
from larv_review.history import HistoryChange
HISTORY = "docs/comprehension-history.md"
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 top() -> str | Failure:
found = git("rev-parse", "--show-toplevel")
return found if isinstance(found, Failure) else found.strip()
def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure:
"""The default branch's ref, `origin/<branch>` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so."""
remotes = git("remote")
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
fetch = git("fetch", "--quiet", "origin")
if isinstance(fetch, Failure) and not stale_ok:
return fetch
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
named = default.strip() if not isinstance(default, Failure) else origin_head()
return named if isinstance(named, Failure) else (named, note)
for branch in ("main", "master"):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
return branch, None
return Failure("no origin remote, and no main or master branch to take as the default branch")
def origin_head() -> str | Failure:
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
listed = git("ls-remote", "--symref", "origin", "HEAD")
if isinstance(listed, Failure):
return listed
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
return f"origin/{named.group(1)}"
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
def commit_exists(commit: str) -> bool:
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure)
def file_at(revision: str, path: str) -> str | Failure:
"""A file's text at a revision, empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
if not commit_exists(revision):
return ""
listed = git("ls-tree", "--name-only", revision, "--", path)
if isinstance(listed, Failure):
return listed
return git("show", f"{revision}:{path}") if listed.strip() else ""
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."""
shallow = git("rev-parse", "--is-shallow-repository")
if isinstance(shallow, Failure):
return shallow
if shallow.strip() == "true":
return Failure("a shallow clone lacks the commits the base search reads; run `git fetch --unshallow origin`")
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)
if isinstance(before, Failure):
return before
after = file_at(commit, HISTORY)
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."""
# Sorts v1.0.0-rc.1 below v1.0.0.
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname")
if isinstance(tags, Failure):
return tags
newest = tags.split()[:1]
count = git("rev-list", "--count", f"{newest[0]}..{default}" if newest else default)
return count if isinstance(count, Failure) else int(count) > 0
+137
View File
@@ -0,0 +1,137 @@
import dataclasses
import re
import time
from larv_review.seats import ARCHITECT, DIMENSIONS, MEAN, Seat
from failure import Failure
from markdown_sections import sections
DATED = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}(?:T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)?, ")
DECIDED_BY = "decided by"
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
# `path:line` or `:line`, then the unit's name where one follows.
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
RESTRUCTURE_FIRST = "would restructure first"
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
SEAT_PLACES = re.compile(rf"^.+, ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
STAMP = "%Y-%m-%dT%H:%M:%SZ"
TITLE = "# Comprehension history\n"
@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]
@property
def paired(self) -> bool:
return self.against is not None
@dataclasses.dataclass(frozen=True)
class Heading:
title: str
commit: str
against: str | None
@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
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 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 heading(at: float, read: str, paired: bool, moved: bool) -> Heading | Failure:
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read. A run moved from a decision entry opens instead with the date or time that entry gives."""
if moved and not DATED.match(read):
return Failure(f"a seats file holding a {MEAN} line alone opens with YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ, then `, `: {read}")
if DATED.match(read) and not moved:
return Failure(f"only a seats file holding a {MEAN} line alone opens with a date: {read}")
title = read if moved else f"{time.strftime(STAMP, time.gmtime(at))}, {read}"
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
return Heading(title, named.group(3), named.group(4))
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
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 ruling_entry(title: str, seats: list[Seat], counted: dict[str, str], ruled: str) -> str:
"""A paired ruling's entry; a seat's vote that counted as same for naming no place says so."""
votes = [[seat.name, vote_text(seat, counted[seat.name])] for seat in seats]
return entry_text(title, [f"Ruling: {ruled}"], [["Seat", "Vote"], *votes], [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats])
def vote_text(seat: Seat, counted: str) -> str:
return counted if counted == seat.said else f"same (voted {seat.said}, naming no place)"
def scoring_entry(title: str, seats: list[Seat], scores: dict[str, list[str]], means: list[str]) -> str:
"""A scoring run's entry; a run moved from a decision entry has its means alone."""
rows = [[seat, *values] for seat, values in scores.items()] + [[MEAN, *means]]
labels = [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
return entry_text(title, [], [["Seat", *DIMENSIONS], *rows], labels)
def entry_text(title: str, lines: list[str], table: list[list[str]], seats: list[tuple[str, list[str]]]) -> str:
"""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"## {title}", *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) + " |"
+241
View File
@@ -0,0 +1,241 @@
"""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. 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. When the fetch fails, round-count
reads origin as last fetched and says so on stderr; the other two exit 1. The history is
docs/comprehension-history.md in the checkout.
ruling-base prints the commit a paired ruling reads against, then which of these found it. The last
measured commit is the default branch's newest merged change that adds a scoring run to the
history, or whose last added paired ruling, by heading time, is better; a merge commit counts as
one change against its first parent. With none, the base is the one the history's first paired
ruling names; with no ruling either, it is the merge base of HEAD and the default branch.
round-count prints each pass's count: the highest <n> among the titles opening
`Answer <pass> round <n>:` of commits the default branch does not hold. It marks each pass at the
cap of {cap} rounds, and each name in such a title that is not a pass.
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
prints why the chunk is due 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 it leaves a release with no item in
the checkout's todo.md, less the shipped items, and work has landed towards that release. Work has
landed when the chunk ships one of the release's items, or when the release is the earliest the
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
no v* tag.
record-ruling and record-scoring read a seats file: a first line naming what the seats read,
`<PR or branch> at <commit>`, ending `, against <base>` for a paired ruling, then each seat's
line, each followed by its places, one `- ` bullet each, as the history writes them. A seat's line
opens with its label, written exactly: `Junior A:`, `Mid A:`, `Maintainability senior:` or
`Inherited architect:`.
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 place in backticks, `path:line`, counts as same, and the printed votes say so.
When the two counted votes differ, it appends nothing and prints `Split:`, saying 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; it prints `Ruling:` and 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, or a `Mean:` line alone for a run moved from a decision entry.
Each line is `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 line's lowest dimension. Its 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 {floor}.
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. A file holding a `Mean:` line alone opens with the date or
time its decision entry gives, and that line alone is the heading. Each commit the line names
must be in the checkout. Each run appends, so record a ruling or a run once.
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, cannot
fetch origin for ruling-base or needs-scoring-run, or cannot read or write the history or todo.md.
"""
import pathlib
import re
import sys
import time
import typing
from larv_review.history import appended, heading, ruling_entry, scoring_entry, vote_text
from larv_review.rules import base, CAP, FLOOR, means, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes
from larv_review.git import commit_exists, default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top
from larv_review.seats import DIMENSIONS, MEAN, Report, report, score_line, scores
from failure import Failure
from rank_todo import ITEMS_HEADER
from file_writes import replace_file
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().format(cap=CAP, floor=FLOOR))
return 0
command, *given = argv or [""]
if command == "ruling-base" and not given:
done = with_default_branch(ruling_base, stale_ok=False)
elif command == "round-count" and not given:
done = with_default_branch(round_count, stale_ok=True)
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
elif command == "record-ruling" and len(given) == 1:
done = record_ruling(pathlib.Path(given[0]))
elif command == "record-scoring" and len(given) == 1:
done = record_scoring(pathlib.Path(given[0]))
elif command == "needs-scoring-run":
print(f"needs-scoring-run takes item IDs, the numbers in todo.md's ID column: {' '.join(given)}", file=sys.stderr)
return 1
elif not argv:
print(USAGE, file=sys.stderr)
return 1
else:
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
return 1
if isinstance(done, Failure):
print(done.reason, file=sys.stderr)
return 1
return 0
def with_default_branch(command: typing.Callable[[str], Failure | None], stale_ok: bool) -> Failure | None:
default = default_branch(stale_ok)
if isinstance(default, Failure):
return default
branch, note = default
if note:
print(note, file=sys.stderr)
return command(branch)
def ruling_base(default: str) -> Failure | None:
changes = history_changes(default)
if isinstance(changes, Failure):
return changes
history = file_at(default, HISTORY)
if isinstance(history, Failure):
return history
if found := base(changes, history):
print("\n".join(found))
return None
merge_base = git("merge-base", "HEAD", default)
if isinstance(merge_base, Failure):
return merge_base
print(f"{merge_base.strip()}\nthe merge base of HEAD and {default}")
return None
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 ''}{'' if name in PASSES else ', not a pass: check the commit title'}")
return None
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(checkout, "todo.md").read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
planned = plan_items(before) if ITEMS_HEADER in before.splitlines() else []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
chunk = plan_items(after)
if isinstance(chunk, Failure):
return Failure(f"the checkout's todo.md: {chunk.reason}")
landed = landed_since_release(default)
if isinstance(landed, Failure):
return landed
reasons = scoring_run_due(planned, chunk, ids, landed)
if isinstance(reasons, Failure):
return reasons
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
return None
def record_ruling(seats_file: pathlib.Path) -> Failure | None:
read = read_seats(seats_file, paired=True)
if isinstance(read, Failure):
return read
title, given = read
counted = votes(given.seats)
if isinstance(counted, Failure):
return counted
tally = ", ".join(f"{seat.name} {vote_text(seat, counted[seat.name])}" for seat in given.seats)
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))
def record_scoring(seats_file: pathlib.Path) -> Failure | None:
read = read_seats(seats_file, paired=False)
if isinstance(read, Failure):
return read
title, given = read
found = scores(given.seats) if given.moved_mean is None else {}
if isinstance(found, Failure):
return found
moved = [] if given.moved_mean is None else score_line(MEAN, given.moved_mean)
if isinstance(moved, Failure):
return moved
mean = means(list(found.values()) or [moved])
under = under_floor(mean)
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {f'Under the floor of {FLOOR}: ' + ', '.join(under) if under else f'None under the floor of {FLOOR}'}.")
return append(scoring_entry(title, given.seats, found, [str(value) for value in mean]))
def read_seats(seats_file: pathlib.Path, paired: bool) -> tuple[str, Report] | Failure:
"""The seats file, and the heading its record goes under, once each commit it names is in the checkout."""
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
named = heading(time.time(), given.read, paired, given.moved_mean is not None)
if isinstance(named, Failure):
return named
if unknown := [commit for commit in (named.commit, named.against) if commit and not commit_exists(commit)]:
return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout")
return named.title, given
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
+123
View File
@@ -0,0 +1,123 @@
import decimal
import re
from larv_review.seats import DIMENSIONS, FIRST_SEATS, Seat, SPLIT_SEATS
from larv_review.history import entries, Entry, HistoryChange, PLACE
from failure import Failure
from rank_todo import Item, ITEMS_HEADER, parse_row, table_rows
CAP = 3
FLOOR = decimal.Decimal("7.0")
PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):")
VOTES = ("better", "same", "worse")
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")
counted = {seat.name: seat.said if names_a_place(seat) else "same" for seat in seats}
first, second, *more = counted.values()
if more and first == second:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first}, which settles the ruling; drop the other seats' lines")
return counted
def names_a_place(seat: Seat) -> bool:
return any(PLACE.search(place) for place in seat.places)
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 means(lines: list[list[str]]) -> list[decimal.Decimal]:
"""The mean of each score across the lines, in DIMENSIONS' order, rounded half up to two decimals."""
return [mean([decimal.Decimal(score) for score in column]) for column in zip(*lines)]
def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < 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, and a title naming no known pass adds its name."""
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.paired), key=lambda entry: entry.time)
if any(not entry.paired 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.paired), key=lambda entry: entry.time)
return rulings[0] if rulings else None
def base(changes: list[HistoryChange], history: str) -> tuple[str, str] | None:
"""The commit a paired ruling reads against, and which fallback found it; None leaves the merge base of HEAD and the default branch. history is the default branch's."""
if found := measured_commit(changes):
return found, "the last measured commit"
if (first := first_ruling(history)) and first.against:
return first.against, "the base the history's first paired ruling names"
return None
def plan_items(todo: str) -> list[Item] | Failure:
"""Each row of a todo.md's items table, read as `rank_todo.py` reads it."""
table = table_rows(todo.splitlines(), ITEMS_HEADER)
if isinstance(table, Failure):
return table
items = []
for row in table.rows:
item = parse_row(row)
if isinstance(item, Failure):
return item
items.append(item)
return items
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
"""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 its newest release tag. Work has landed towards an emptied release when the chunk ships one of its items, or when it is the next release, the earliest before names, and landed holds."""
plan = {item.id: item for item in before + after}
if unknown := sorted(set(ships) - set(plan)):
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
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()]
next_release = min((item.release for item in before), default=None)
for release in emptied(before, after, shipped):
if any(item.release == release for item in shipped) or (release == next_release and landed):
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
return reasons
def emptied(before: list[Item], after: list[Item], shipped: list[Item]) -> list[tuple[int, int, int]]:
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer."""
named = {item.release for item in before + shipped}
left = {item.release for item in after if item.id not in {ship.id for ship in shipped}}
return sorted(named - left)
+83
View File
@@ -0,0 +1,83 @@
import dataclasses
import decimal
import re
from failure import Failure
ARCHITECT = "Inherited architect"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
JUNIOR = "Junior A"
# A scoring run moved from a `comprehension floor:` decision entry kept only the seats' means.
MEAN = "Mean"
MID = "Mid A"
SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS))
SENIOR = "Maintainability senior"
FIRST_SEATS = (MID, ARCHITECT)
SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT)
SEAT_LINE = re.compile(rf"^({'|'.join(SCORING_SEATS)}): (.+)$")
SPLIT_SEATS = (SENIOR, JUNIOR)
@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, or, for a run moved from a decision entry, its Mean line alone."""
read: str
seats: list[Seat]
moved_mean: str | None
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] = []
moved_mean = None
for line in lines[1:]:
if line.startswith(f"{MEAN}: ") and not seats and moved_mean is None:
moved_mean = line[len(MEAN) + 2:].strip()
elif moved_mean is not None:
return Failure(f"a {MEAN} line stands alone in its seats file: {line}")
elif 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, opening with one of {', '.join(SCORING_SEATS)} and a colon, nor one of its places: {line}")
return Report(lines[0].strip(), seats, moved_mean)
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, or a {MEAN} line alone; the file has {', '.join(seat.name for seat in seats) or 'none'}")
found = {}
for seat in seats:
values = score_line(seat.name, seat.said)
if isinstance(values, Failure):
return values
found[seat.name] = values
return found
def score_line(name: str, said: str) -> list[str] | Failure:
"""A line's five scores as written, each from 1 to 10 and the overall at most 1 above the lowest dimension."""
if not (written := SCORES.fullmatch(said)):
return Failure(f"{name}'s line is not {', '.join(score + ' <score>' for score in DIMENSIONS)}: {said}")
values = [decimal.Decimal(value) for value in written.groups()]
if not all(1 <= value <= 10 for value in values):
return Failure(f"{name}'s scores are not each from 1 to 10: {said}")
if values[-1] > min(values[:-1]) + 1:
return Failure(f"{name}'s overall exceeds the lowest dimension by more than 1; ask the seat to rescore: {said}")
return list(written.groups())
+18 -1
View File
@@ -1,9 +1,10 @@
from typing import Callable
import collections
import dataclasses
import os
import statistics
from metric_bench.places import Place
from larv_review.history import Place
from metric_bench.python_units import Unit
METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
@@ -81,3 +82,19 @@ def top_k(named: list[int], rest: list[int]) -> float:
def medians(runs: list[RunScores]) -> dict[str, Score]:
return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs), all(run.scores[metric].constant for run in runs)) for metric in METRICS}
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
+5 -5
View File
@@ -34,10 +34,10 @@ import statistics
import subprocess
import sys
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score
from metric_bench.bench import bench, co_changed, medians, METRICS, resolved, RunScores, Score
from larv_review.history import entries, Entry
from failure import Failure
from metric_bench.python_units import measured, python_units, Unit
from metric_bench.places import resolved, scoring_runs, ScoringRun
def main(argv: list[str]) -> int:
@@ -56,7 +56,7 @@ def main(argv: list[str]) -> int:
return failed(benched)
rows, notes = benched
if not rows:
return failed(Failure(f"no scoring run in {history} could be scored; its format: ~/.claude/skills/larv-review/SKILL.md → \"History\"{noted(notes)}"))
return failed(Failure(f"no scoring run in {history} could be scored; its format is what ~/.claude/bin/larv-review writes{noted(notes)}"))
print(table(rows) + noted(notes))
return 0
@@ -81,7 +81,7 @@ def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[s
"""Each scored run's heading and scores, and a note for each run skipped or not scored and each file left out."""
rows = []
notes = []
for run in scoring_runs(text):
for run in [entry for entry in entries(text) if not entry.paired]:
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
continue
@@ -101,7 +101,7 @@ def noted(notes: list[str]) -> str:
return "\n\n" + "\n".join(notes) if notes else ""
def run_scores(run: ScoringRun, top: str) -> tuple[RunScores | None, list[str]] | Failure:
def run_scores(run: Entry, top: str) -> tuple[RunScores | None, list[str]] | Failure:
"""The run's scores, and why each file that does not parse was left out."""
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
if isinstance(listed, Failure):
-73
View File
@@ -1,73 +0,0 @@
import dataclasses
import os
import re
from markdown_sections import sections
# The format: skills/larv-review/SKILL.md §3 → "History", which names this reader.
RUN = re.compile(r"^(.+), (.+) at ([0-9a-f]{7,40})$")
SEAT_PLACES = re.compile(r"^.+, (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 ScoringRun:
heading: str
commit: str
places: list[Place]
def scoring_runs(history: str) -> list[ScoringRun]:
"""Each scoring run in a comprehension history, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out."""
runs = []
for heading, bodies in sections(history).items():
if (named := RUN.match(heading)) and ", against " not in heading:
runs.append(ScoringRun(heading, named.group(3), [place for body in bodies for place in seat_places(body)]))
return runs
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
+10 -2
View File
@@ -375,6 +375,16 @@ def cells(row: str, count: int) -> list[str] | Failure:
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
item = parse_row(row)
if isinstance(item, Failure):
return item
if unknown := [goal for goal in item.goals if goal not in weights]:
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
return item
def parse_row(row: str) -> Item | Failure:
"""An item row, every cell checked but the goals it cites."""
found = cells(row, 10)
if isinstance(found, Failure):
return found
@@ -393,8 +403,6 @@ def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
if unknown := [goal for goal in cited if goal not in weights]:
return Failure(f"item {id_} cites goal {', '.join(unknown)}, which the goal weights do not list")
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
+305
View File
@@ -0,0 +1,305 @@
import decimal
import os
import pathlib
import subprocess
import sys
import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from larv_review.history import appended, entries, HistoryChange, Place, ruling_entry
from larv_review.rules import base, first_ruling, means, measured_commit, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes
from failure import Failure
from test_loop_claude_black_box import host_env
from rank_todo import Item
from larv_review.seats import report, score_line, scores, Seat
TOOL = pathlib.Path(__file__).resolve().parent / "larv-review"
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
def paired(time: str, verdict: str, commit: str = "bbbbbbb") -> str:
return f"## {time}, PR #2 at {commit}, against aaaaaaa\n\nRuling: {verdict}\n"
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "A": 1, "G": 1}, ("1",))
def todo(*rows: str) -> str:
return "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n" + "".join(f"{row}\n" for row in rows)
class Seats(unittest.TestCase):
def test_reads_each_seats_line_and_places_and_joins_a_wrapped_place(self):
given = report("PR #2 at abc1234, against def5678\n\nMid A: worse\n\n- `a.py:1` `f`: hard\n to read\n\nInherited architect: same\n")
self.assertEqual(given.read, "PR #2 at abc1234, against def5678")
self.assertEqual(given.seats, [Seat("Mid A", "worse", ["`a.py:1` `f`: hard to read"]), Seat("Inherited architect", "same", [])])
def test_refuses_a_line_that_is_neither_a_seat_nor_a_place_and_a_seat_twice(self):
self.assertIsInstance(report("PR #2 at abc1234\n\nMid A worse\n"), Failure)
self.assertIsInstance(report("PR #2 at abc1234\n\nMid A: worse\n\nMid A: same\n"), Failure)
self.assertIsInstance(report(""), Failure)
def test_counts_a_vote_naming_no_place_as_same(self):
seats = [Seat("Mid A", "worse", ["the whole skill"]), Seat("Inherited architect", "better", ["`a.py:3` `f`: shorter"])]
self.assertEqual(votes(seats), {"Mid A": "same", "Inherited architect": "better"})
def test_refuses_two_more_seats_once_the_first_two_agree(self):
seats = [Seat(name, vote, ["`f.py:1` `f`: x"]) for name, vote in (("Mid A", "worse"), ("Inherited architect", "worse"), ("Maintainability senior", "better"), ("Junior A", "better"))]
self.assertIsInstance(votes(seats), Failure)
def test_takes_the_first_two_seats_then_the_other_two_in_order(self):
first = [Seat("Mid A", "same", []), Seat("Inherited architect", "same", [])]
self.assertIsInstance(votes(first[::-1]), Failure)
self.assertIsInstance(votes(first + [Seat("Junior A", "same", [])]), Failure)
self.assertIsInstance(votes([first[0], Seat("Inherited architect", "worst", [])]), Failure)
def test_rules_by_a_lead_of_two_and_splits_two_seats_that_differ(self):
cases = [
(["worse", "worse"], "worse"),
(["same", "same"], "same"),
(["worse", "same"], None),
(["worse", "better", "worse", "worse"], "worse"),
(["worse", "same", "worse", "same"], "same"),
(["worse", "same", "worse", "better"], "same"),
(["better", "same", "better", "better"], "better"),
]
for counted, expected in cases:
with self.subTest(counted):
self.assertEqual(ruling(counted), expected)
def test_reads_four_seats_scores_and_refuses_an_overall_above_the_lowest_by_more_than_one(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = [Seat(name, line, []) for name in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect")]
self.assertEqual(scores(seats)["Mid A"], ["7", "6.5", "7", "6.5", "7"])
self.assertIsInstance(scores(seats[:3]), Failure)
self.assertIsInstance(scores([*seats[:3], Seat("Inherited architect", line.replace("Overall 7", "Overall 8"), [])]), Failure)
self.assertIsInstance(scores([*seats[:3], Seat("Inherited architect", line.replace("Shape 7", "Shape 11"), [])]), Failure)
self.assertEqual(score_line("Mean", "Navigation 7.38, Locality 7.38, Shape 8, Self-sufficiency 8, Overall 8.38")[-1], "8.38")
def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self):
found = means([["7.5", "6.5", "7", "7", "7"], ["7.5", "7", "7", "6.5", "7"], ["7", "6.5", "7", "6.5", "6.5"], ["7.5", "6.5", "7", "6.5", "7"]])
self.assertEqual([str(mean) for mean in found], ["7.38", "6.63", "7.00", "6.63", "6.88"])
self.assertEqual(under_floor(found), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5), [])
class History(unittest.TestCase):
def test_reads_back_what_it_writes(self):
seats = [Seat("Mid A", "worse", ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", "worse", [])]
ruled = ruling_entry("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", seats, {"Mid A": "worse", "Inherited architect": "same"}, "worse")
history = appended(appended("", SCORING), ruled)
self.assertTrue(history.startswith("# Comprehension history\n\n## 2026-10-08T12:00:00Z"))
self.assertNotIn("Inherited architect, decided by:", history)
self.assertIn("| Inherited architect | same (voted worse, naming no place) |", history)
found = entries(history)
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in found], [("aaaaaaa", None, None), ("bbbbbbb", "aaaaaaa", "worse")])
self.assertEqual(found[1].places, [Place("bin/a.py", "f"), Place("bin/a.py", "g")])
self.assertEqual([entry.paired for entry in found], [False, True])
class Base(unittest.TestCase):
def test_takes_the_newest_change_adding_a_scoring_run_or_ending_on_a_better_ruling(self):
older = HistoryChange("old", "", SCORING)
same = HistoryChange("same", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "same"))
self.assertEqual(measured_commit([same, older]), "old")
# The file holds the later ruling first, as a merge conflict resolved the other way would.
better = HistoryChange("better", SCORING, SCORING + paired("2026-10-08T14:00:00Z", "better") + paired("2026-10-08T13:00:00Z", "worse"))
self.assertEqual(measured_commit([better, older]), "better")
worse_last = HistoryChange("worse", SCORING, SCORING + paired("2026-10-08T13:00:00Z", "better") + paired("2026-10-08T14:00:00Z", "worse"))
self.assertEqual(measured_commit([worse_last, older]), "old")
self.assertIsNone(measured_commit([same]))
def test_falls_back_to_the_first_rulings_base_then_to_none(self):
ruled = paired("2026-10-08T13:00:00Z", "worse")
self.assertEqual(base([HistoryChange("c", "", ruled)], ruled), ("aaaaaaa", "the base the history's first paired ruling names"))
self.assertIsNone(base([], ""))
self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING), ("c", "the last measured commit"))
def test_finds_the_earliest_ruling_by_its_time(self):
ruled = first_ruling(paired("2026-10-08T14:00:00Z", "same", "ccccccc") + paired("2026-10-08T13:00:00Z", "worse"))
self.assertEqual(ruled and ruled.commit, "bbbbbbb")
self.assertIsNone(first_ruling(SCORING))
class Rounds(unittest.TestCase):
def test_counts_each_passs_highest_round(self):
counts = round_counts(["Answer prose round 1: x", "Answer full scan round 2: y", "Answer full scan round 1: z", "Answer stability: no round", "Answer stabilty round 1: typo", "Answer security round 1: rename round 2: x", "Rescore: w"])
self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"], counts["security"]), (1, 2, 0, 0, 1, 1))
class ScoringRunDue(unittest.TestCase):
def test_reads_each_rows_id_release_and_tagline(self):
self.assertEqual(plan_items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
self.assertIsInstance(plan_items("# todo\n"), Failure)
self.assertIsInstance(plan_items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), Failure)
def test_is_due_for_an_item_naming_the_floor(self):
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
self.assertEqual(scoring_run_due(plan, plan, [1], True), ["ships item 1, which names the comprehension floor"])
self.assertIsInstance(scoring_run_due(plan, plan, [9], True), Failure)
def test_is_due_when_the_chunk_ships_a_releases_last_item(self):
plan = [item(1, (0, 1, 0)), item(2, (0, 2, 0))]
self.assertEqual(scoring_run_due(plan, plan, [1], False), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], True), [])
def test_is_due_when_the_chunk_removes_the_next_releases_last_item_after_work_landed(self):
before = [item(1, (0, 1, 0)), item(2, (0, 1, 0)), item(3, (0, 2, 0))]
after = [item(2, (0, 1, 0)), item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, after, [2], True), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, after, [], True), [])
emptied = [item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, emptied, [2], False), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], True), ["leaves release 0.1.0 with no plan item"])
self.assertEqual(scoring_run_due(before, emptied, [], False), [])
def test_is_not_due_when_a_later_release_loses_its_last_item_unshipped(self):
before = [item(1, (0, 1, 0)), item(3, (0, 2, 0))]
self.assertEqual(scoring_run_due(before, before[:1], [], True), [])
class LarvReviewTool(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = pathlib.Path(os.path.realpath(temp.name))
self.env = {**host_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(root)}
self.checkout = root / "proj"
subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(root / "origin.git")], check=True, env=self.env)
subprocess.run(["git", "clone", "-q", str(root / "origin.git"), str(self.checkout)], check=True, env=self.env, capture_output=True)
self.commit("start", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")})
self.git("push", "-q", "origin", "HEAD:main")
self.git("remote", "set-head", "origin", "main")
self.git("switch", "-q", "-c", "chunk")
self.start = self.git("rev-parse", "--short", "HEAD").strip()
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
def commit(self, title, files=None):
for name, text in (files or {}).items():
(self.checkout / name).parent.mkdir(parents=True, exist_ok=True)
(self.checkout / name).write_text(text)
self.git("add", name)
self.git("commit", "-q", "--allow-empty", "-m", title)
def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
def seats_file(self, text):
path = self.checkout.parent / "seats.md"
path.write_text(textwrap.dedent(text))
return str(path)
def test_takes_the_merge_base_until_a_merged_change_records_a_scoring_run(self):
start = self.git("rev-parse", "HEAD").strip()
self.commit("work")
ran = self.run_tool("ruling-base")
self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, start), ran.stderr)
self.git("switch", "-q", "-c", "measured", "main")
self.commit("Merge a scoring run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
self.git("push", "-q", "origin", "HEAD:main")
measured = self.git("rev-parse", "HEAD").strip()
self.git("switch", "-q", "chunk")
self.assertEqual(self.run_tool("ruling-base").stdout.splitlines()[0], measured)
def test_counts_rounds_on_this_branch_alone(self):
self.commit("Answer stability round 1: a")
self.commit("Answer stability round 2: b")
self.commit("Answer prose round 1: c")
self.commit("Answer stability round 3: d")
ran = self.run_tool("round-count")
self.assertIn("stability: 3, at the cap\n", ran.stdout)
self.assertIn("prose: 1\n", ran.stdout)
self.assertIn("architecture: 0\n", ran.stdout)
def test_says_whether_a_scoring_run_is_due_and_refuses_an_unknown_item(self):
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
unknown = self.run_tool("needs-scoring-run", "9")
self.assertEqual(unknown.returncode, 1)
self.assertIn("item 9", unknown.stderr)
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
def test_records_a_ruling_once_four_seats_settle_a_split(self):
lines = """\
PR #2 at {start}, against {start}
Mid A: worse
- `bin/a.py:3` `f`: three branches
Inherited architect: same
"""
lines = lines.replace("{start}", self.start)
split = self.run_tool("record-ruling", self.seats_file(lines))
self.assertEqual(split.returncode, 0, split.stderr)
self.assertTrue(split.stdout.startswith("Split: Mid A worse, Inherited architect same."))
history = self.checkout / "docs" / "comprehension-history.md"
self.assertFalse(history.exists())
lines += "\n\t\t\tMaintainability senior: worse\n\n\t\t\t- `bin/a.py:3` `f`: hard\n\n\t\t\tJunior A: worse\n"
ran = self.run_tool("record-ruling", self.seats_file(lines))
self.assertEqual(ran.stdout.splitlines()[0], "Ruling: same. Votes as counted: Mid A worse, Inherited architect same, Maintainability senior worse, Junior A same (voted worse, naming no place).")
recorded = entries(history.read_text())
self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [(self.start, self.start, "same")])
self.assertEqual(recorded[0].places, [Place("bin/a.py", "f")] * 2)
self.assertIn("| Junior A | same (voted worse, naming no place) |", history.read_text())
def test_records_a_scoring_run_with_its_means(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("Under the floor of 7.0: Locality 6.50, Self-sufficiency 6.50.", ran.stdout)
text = (self.checkout / "docs" / "comprehension-history.md").read_text()
self.assertIn("| Mean | 7.00 | 6.50 | 7.00 | 6.50 | 7.00 |", text)
self.assertIn("Inherited architect, would restructure first:", text)
self.assertEqual([entry.places for entry in entries(text)], [[Place("bin/a.py", "f")] * 4])
def test_refuses_a_ruling_file_that_names_no_base_or_a_commit_the_checkout_lacks(self):
ran = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}\n\nMid A: same\n\nInherited architect: same\n"))
self.assertEqual(ran.returncode, 1)
self.assertIn("against <base>", ran.stderr)
lacking = self.run_tool("record-ruling", self.seats_file(f"PR #2 at {self.start}, against abcdef1\n\nMid A: same\n\nInherited architect: same\n"))
self.assertEqual(lacking.returncode, 1)
self.assertIn("abcdef1, which is no commit", lacking.stderr)
def test_moves_a_dated_mean_from_a_decision_entry_as_a_scoring_run(self):
mean = "Mean: Navigation 7.38, Locality 6.63, Shape 7.0, Self-sufficiency 6.88, Overall 6.88\n"
ran = self.run_tool("record-scoring", self.seats_file(f"2026-10-04, PR #1 merged at {self.start}\n\n{mean}"))
self.assertEqual(ran.returncode, 0, ran.stderr)
text = (self.checkout / "docs" / "comprehension-history.md").read_text()
self.assertIn(f"## 2026-10-04, PR #1 merged at {self.start}\n\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mean | 7.38 | 6.63 | 7.00 | 6.88 | 6.88 |\n", text)
def test_states_its_rules_and_finds_origins_default_branch_where_the_clone_recorded_none(self):
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0, helped.stderr)
self.assertIn("cap of 3 rounds", helped.stdout)
self.git("remote", "set-head", "origin", "--delete")
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
def test_refuses_a_dated_first_line_except_for_a_mean_alone_and_a_mean_without_one(self):
mean = "Mean: Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7\n"
self.assertEqual(self.run_tool("record-scoring", self.seats_file(f"PR #1 at {self.start}\n\n{mean}")).returncode, 1)
ruled = self.run_tool("record-ruling", self.seats_file(f"2026-10-08, PR #2 at {self.start}, against {self.start}\n\nMid A: same\n\nInherited architect: same\n"))
self.assertEqual(ruled.returncode, 1)
self.assertIn("only a seats file holding a Mean line alone", ruled.stderr)
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
self.commit("Answer prose round 1: a")
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
offline = self.run_tool("round-count")
self.assertEqual(offline.returncode, 0, offline.stderr)
self.assertIn("reading origin as last fetched", offline.stderr)
self.assertIn("prose: 1\n", offline.stdout)
self.git("remote", "remove", "origin")
self.assertIn("prose: 1\n", self.run_tool("round-count").stdout)
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -9,11 +9,11 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from metric_bench.bench import auc, bench, co_changed, top_k
from metric_bench.bench import auc, bench, co_changed, resolved, top_k
from metric_bench.python_units import cognitive, measured, python_units, Unit
from larv_review.history import entries, Place
from failure import Failure
from test_loop_claude_black_box import host_env
from metric_bench.places import Place, resolved, scoring_runs
TOOL = pathlib.Path(__file__).resolve().parent / "metric-bench"
@@ -142,7 +142,7 @@ class Places(unittest.TestCase):
""")
def test_reads_each_scoring_runs_places_and_leaves_paired_rulings_out(self):
runs = scoring_runs(self.HISTORY)
runs = [entry for entry in entries(self.HISTORY) if not entry.paired]
self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")])
self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")])
+1 -1
View File
@@ -11,5 +11,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "larv_review", "-p", "loop_claude", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+106
View File
@@ -422,3 +422,109 @@ Inherited architect, decided by:
- `bin/metric_bench/places.py:7` `RUN`, `SEAT_PLACES`, `PLACE` and `:60` `resolved`: a regex reader of a prose format, and a historical quirk to know first
- `AGENTS.md:35` "Scoring run": the section's name no longer covers its use by paired rulings
- `skills/larv-review/SKILL.md:64` "Re-entry", better: which passes a fix reruns is explicit
## 2026-10-08T23:12:17Z, PR #231 at 53ed515, against 12d6d75
Ruling: better
| Seat | Vote |
|---|---|
| Mid A | better |
| Inherited architect | better |
Mid A, decided by:
- `bin/larv_review/rules.py:64` `round_counts`, with `:10` `CAP` and `bin/larv_review/main.py:118` `round_count`, better: a fourth round leads cold to one named function, where the base had only `skills/larv-review/SKILL.md:58` "Count" to carry out by hand
- `bin/larv_review/main.py:1` the module docstring, better: the base, round count, trigger, vote rule and seats file are written beside the code that carries them out
- `bin/larv_review/rules.py:41` `ruling` and `:27` `votes`, better: the vote rule is a short pure function, changeable without the skill text in mind
- `bin/larv_review/git.py:4` the import of `HistoryChange` from rules, with `:50` `history_changes`: the git layer takes its result type from the rules module, so the direction among the three modules is not obvious
- `bin/larv_review/history.py:85` `resolved` and `:56` `scoring_runs`: they serve only metric-bench, so old-history path logic sits in the review tool's module
- `bin/metric_bench/main.py:143` `git` against `bin/larv_review/git.py:9` `git`: two private git runners with different error handling
- `bin/larv_review/rules.py:106` `scoring_run_due`: the densest new unit, two plans, shipped IDs and a flag held at once
- `skills/larv-review/SKILL.md:93` "Paired ruling" and `:100` "Scoring run": more vocabulary, though each mechanical step now names a subcommand
Inherited architect, decided by:
- `bin/larv_review/rules.py:64` `round_counts`, with `bin/larv_review/main.py:118` `round_count`, better: the 3am question leads to `round-count` and one pure function, where the base's `skills/larv-review/SKILL.md:58` "Count" was prose to carry out against `git log`
- `bin/larv_review/rules.py:106` `scoring_run_due`, better: the trigger is a checkable function that prints its reason, though dense in its `and`/`or` binding and set arithmetic
- `bin/larv_review/main.py:1` the module docstring, better: the history format and ratchet have one tested home; `skills/larv-review/SKILL.md:42` now points at `--help` for the rules
- `bin/larv_review/history.py:85` `resolved`, `:56` `scoring_runs` and `:61` `seat_places`: a parser only metric-bench uses, under the review tool's name; where it rots first
- `bin/larv_review/git.py:4` the import of `HistoryChange` from rules, and `bin/metric_bench/main.py:143` `git`: a reversed dependency and two git runners
- `bin/larv_review/seats.py:7` `SCORING_SEATS` and `SEAT_LINE`, with `bin/larv_review/rules.py:11` `FIRST_SEATS`: seat names spelled in four places
- `bin/larv_review/main.py:164` `record` and `bin/larv_review/history.py:52` `entries`: positional regex groups that need `HEADING` open beside them
## 2026-10-08T23:40:09Z, PR #231 at efed78b, against 12d6d75
Ruling: worse
| Seat | Vote |
|---|---|
| Mid A | worse |
| Inherited architect | worse |
Mid A, decided by:
- `bin/larv_review/rules.py:105` `scoring_run_due`: set arithmetic over two plans, an `earliest` release and a `landed` flag built in `git.py`, with `or` and `and` unparenthesised, where the base's trigger was one clause at `skills/larv-review/SKILL.md:35`
- `bin/larv_review/rules.py:66` `measured_commit` and `:82` `base`: the base comes from diffing the history around each merged change, held with `history.py` `entries` and `git.py` `history_changes` at once
- `bin/larv_review/rules.py:16` `votes` and `:34` `ruling`, with `bin/larv_review/seats.py:16` `FIRST_SEATS`: fixed seat order, a split, a lead of two and a placeless vote stacked, where `skills/larv-review/SKILL.md:93` only points at `--help`
- `bin/larv_review/main.py:220` `read_seats`: `named.group(3, 4)` depends on `HEADING`'s group positions in `bin/larv_review/history.py:13`
- `bin/larv_review/history.py:95` `resolved` and `:66` `scoring_runs`: used only by `bin/metric_bench/main.py:40`, so metric-bench reaches into another tool's package
- `bin/larv_review/rules.py:57` `round_counts`, better: the round count is a small named function where the base had prose at `skills/larv-review/SKILL.md:58`
- `bin/larv_review/history.py:129` `ruling_entry`, better: the history's format has one owner in code
Inherited architect, decided by:
- `bin/larv_review/rules.py:105` `scoring_run_due`: set arithmetic whose inputs are built in three other files, where the base's trigger was one table cell at `skills/larv-review/SKILL.md:35`
- `bin/larv_review/rules.py:66` `measured_commit` and `:82` `base`: `against is None` doubles as the type tag of `bin/larv_review/history.py:30` `Entry`; the hardest unit at 3am
- `bin/larv_review/main.py:220` `read_seats`, with `bin/larv_review/history.py:111` `heading`: a raw `re.Match` whose groups another file reads by position
- `bin/larv_review/seats.py:10` `MEAN`, with `bin/larv_review/history.py:111` `heading`: a fake seat standing for a legacy import, threaded through every scoring path
- `bin/larv_review/history.py:95` `resolved` and `:66` `scoring_runs`: metric-bench's legacy path rules inside larv-review's package, and two `git` helpers at `bin/metric_bench/main.py:143` and `bin/larv_review/git.py:10`
- `bin/larv_review/main.py:1` the module docstring, with `bin/larv_review/rules.py:83` `base`: the base rule stated in several places in different words
- `bin/larv_review/rules.py:57` `round_counts`, better: the fourth-round symptom leads to a tested function
## 2026-10-08T23:48:44Z, PR #231 at c1133ed, against 12d6d75
Ruling: same
| Seat | Vote |
|---|---|
| Mid A | better |
| Inherited architect | worse |
| Maintainability senior | better |
| Junior A | worse |
Mid A, decided by:
- `bin/larv_review/rules.py:57` `round_counts`, with `bin/larv_review/main.py:141` `round_count`, better: the fourth-round symptom leads to a short function, where the base had only `skills/larv-review/SKILL.md:58` "Count"
- `bin/larv_review/main.py:1` the module docstring, better: each rule stated once beside the code that enforces it, where the base had `skills/larv-review/SKILL.md:92` "History"
- `bin/larv_review/history.py:12` `HEADING`, `:58` `entries` and `:128` `entry_text`, better: the history is read and written in one module
- `bin/larv_review/main.py:195` `record_scoring`, with `bin/larv_review/seats.py:37` `report` and `bin/larv_review/history.py:93` `heading`: the moved Mean path threads through three files
- `bin/larv_review/rules.py:105` `scoring_run_due`, `:119` `emptied` and `:66` `measured_commit`: dense rules that lean on long docstrings
- `bin/metric_bench/main.py:38` and `bin/larv_review/git.py:5`: imports across packages
Inherited architect, decided by:
- `bin/metric_bench/main.py:38` and `bin/metric_bench/bench.py:7`, with `bin/larv_review/history.py:22` `Place` and `:69` `seat_places`: metric-bench reads its input through larv-review's history module
- `bin/larv_review/rules.py:66` `measured_commit`, `:82` `base` and `bin/larv_review/main.py:124` `ruling_base`: three fallbacks to hold at once, where the base's ratchet was one sentence at `skills/larv-review/SKILL.md:100`
- `bin/larv_review/rules.py:105` `scoring_run_due` and `:119` `emptied`, with `bin/larv_review/git.py:88` `landed_since_release`: the trigger spread over three files and the help
- `bin/larv_review/rules.py:7` the imports, with `bin/rank_todo.py:386` `parse_row`: rank_todo is now a library for larv-review too
- `bin/larv_review/seats.py:30` `Report` and `:37` `report`, and `bin/metric_bench/python_units.py:20` `measured`: names that cost a re-read
- `bin/larv_review/rules.py:57` `round_counts`, better: the 3am question answerable in code
Maintainability senior, decided by:
- `bin/larv_review/rules.py:57` `round_counts`, with `bin/larv_review/main.py:141` `round_count`, better: the 3am symptom lands on a tested unit, where the base had `skills/larv-review/SKILL.md:58` "Count"
- `bin/larv_review/main.py:1` the module docstring, better: the base search, round count, trigger and seats file stated once, where the base had `skills/larv-review/SKILL.md:92` "History" and `:100` "Ratchet"
- `bin/larv_review/rules.py:66` `measured_commit`, with `bin/larv_review/git.py:66` `history_changes`: the costliest new unit to hold
- `bin/larv_review/rules.py:105` `scoring_run_due` and `:119` `emptied`: exact and checkable, but read twice
- `bin/larv_review/rules.py:1` the module: six concerns, and `votes` depends on `PLACE` from `bin/larv_review/history.py:14`
- `bin/larv_review/main.py:195` `record_scoring`: two inputs threaded through sentinels
Junior A, decided by:
- `bin/larv_review/main.py:195` `record_scoring`, with `bin/larv_review/seats.py:44` `report` and `bin/larv_review/history.py:93` `heading`: two modes woven through one function and three files
- `bin/larv_review/rules.py:105` `scoring_run_due`, with `:119` `emptied`: needs the release rules from `CLAUDE.md` and `bin/larv_review/git.py:88` `landed_since_release`
- `bin/larv_review/rules.py:66` `measured_commit`: `or` and `and` mixed without parentheses, and a new concept to learn first
- `bin/larv_review/git.py:5` and `bin/metric_bench/main.py:38`: the git layer depends on the history type, and metric-bench on larv-review's package
- `bin/larv_review/main.py:1` the module docstring: one home, but a wall of rules leaning on terms defined elsewhere
- `bin/larv_review/rules.py:16` `votes`: a seat protocol reconstructed only from `skills/larv-review/SKILL.md:97`
+2 -2
View File
@@ -50,8 +50,8 @@ lilleman decided to ship each of these under the floor on the day listed. Each l
- 2026-10-04, PR #215: 7.38, 6.63, 7.0, 6.88, 6.88.
- 2026-10-08, PR #224: 7.00, 6.50, 7.00, 6.50, 6.75. lilleman shipped it below the ratchet as well: its 20 lines of skill prose left the code as it was, so the fall is the panel's noise between runs, which the paired ruling cancels.
- 2026-10-08, PR #225: 7.25, 6.75, 7.00, 6.88, 6.88. Above PR #224's run on every score but Shape, which held.
- 2026-10-08, PR #228: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet: the seats blamed the new ratchet's own rules, which `todo.md` item 85 moves into a tested tool.
- 2026-10-08, PR #229: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet for PR #228's reason: the seats' decisive places were still PR #228's rules, which item 85 moves into a tested tool.
- 2026-10-08, PR #228: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet: the seats blamed the new ratchet's own rules, since moved into the tested `bin/larv-review`.
- 2026-10-08, PR #229: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet for PR #228's reason: the seats' decisive places were still PR #228's rules, since moved into `bin/larv-review`.
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
+13 -11
View File
@@ -32,7 +32,7 @@ A pass is one kind of review, a row of the table, named by its first column. Its
| Pass | Reviewer | Trigger |
|------|----------|----------------------------------------|
| Architecture | systems-architect, then principles-auditor and the comprehension check | ships or removes the last plan item of a release that has work landed towards it, or ships an item naming the comprehension floor; or carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats, CLI flags and exit codes); a schema change beyond an additive column; a fix, only where it carries an architectural decision |
| Architecture | systems-architect, then principles-auditor and the comprehension check | is due a scoring run ("Architecture" → "Scoring run"); or carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats, CLI flags and exit codes); a schema change beyond an additive column; a fix, only where it carries an architectural decision |
| Full scan | the `claude-security` plugin at high effort: `/claude-security scan this branch's changes at high` | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface |
| Security | `/security-review` | changes code or config, unless the full scan runs on the same change; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and the full scan does not rerun on it |
| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do |
@@ -43,6 +43,8 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod
Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone.
`~/.claude/bin/larv-review` holds this section's mechanical rules: the round count, the paired ruling's base and vote count, the scoring run's trigger and the history's format. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
**Precedent, then ask** — for the architecture pass and the full scan:
- **Skip.** A precedent is a `docs/decisions.md` entry, or a plan item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite that entry or item.
@@ -55,7 +57,7 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
- **Round.** A round is one launch of a pass's reviewer: the first, each re-entry, and the rerun after the architect returns Stage 0 questions ("Architecture" below). A rescore is a round only as "Architecture" → "Fresh" says.
- **Architecture round.** The architecture pass's first round is the architect (unless skipped), the principles audit and the comprehension check, which "Architecture" → "Suspended" may skip. A later round relaunches each reviewer whose 🔴 or 🟡 the previous round's fixes answer, the comprehension check only as "Architecture" → "Fresh" says. Where those fixes carry an architectural decision, the architect and the principles audit run again.
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts a round.
- **Count.** Close each round with one commit that holds the round's fixes and is titled `Answer <pass> round <n>: …`, `<pass>` being the pass's name in lower case, such as `full scan`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. A pass's count is the highest `<n>` among titles holding `Answer <pass> round <n>:` in `git log origin/<default branch>..HEAD` after a `git fetch`, or in `git log <default branch>..HEAD` with no remote. The auto-reviewer's count is the number of its reviews on the PR, less its reviews of a `Rescore:` commit.
- **Count.** Close each round with one commit that holds the round's fixes and is titled `Answer <pass> round <n>: …`, `<pass>` being the pass's name in lower case, such as `full scan`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap. The auto-reviewer's count is the number of its reviews on the PR, less its reviews of a `Rescore:` commit.
- **Later rounds.** A rerun pass reviews only what changed since it last reviewed: `git diff <the commit it last reviewed, or else the commit before this round's fixes> HEAD`, since the fixes may be unpushed. The comprehension check's seats still read the whole project. From round 2, prompt an agent under `~/.claude/agents/` with its own last round's findings verbatim too.
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or, for the prose pass, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
- **Cap.** A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer.
@@ -90,17 +92,17 @@ Then the comprehension check: simulated readers, launched per `~/.claude/skills/
**Paired ruling**, in every architecture pass. Each seat votes whether the project reads better, the same or worse at this branch's head than at the base.
- **Base.** The last measured commit: the newest commit on `origin/<default branch>`, after a `git fetch`, whose change to the history (below) adds a scoring run, or whose last added paired ruling is better. Read each merged change whole, a merge commit as one change: `git log --first-parent --diff-merges=first-parent -p origin/<default branch> -- docs/comprehension-history.md`; with no remote, use `<default branch>`. No such commit → the base the first paired ruling in that history names; no ruling either → the merge base of the head and the default branch.
- **Base.** The last measured commit, which `~/.claude/bin/larv-review ruling-base` prints.
- **Head.** Before each ruling, merge `origin/<default branch>` into this branch unless the head already holds it, so the seats see only this branch's change on top of the base.
- **Seats.** Mid A and the inherited architect. When their votes differ, the maintainability senior and Junior A vote too, launched together.
- **Ruling.** The vote that leads each other vote by two or more; without one, same. A better or worse vote that names no place counts as same.
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a seats file in your scratchpad, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
- **Ruling.** The `Ruling:` line `record-ruling` prints and appends to the history.
**Scoring run**, when the chunk ships or removes the last plan item of a release that has work landed towards it, or ships an item naming the comprehension floor. Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. A seat's overall may not exceed its lowest dimension by more than 1. Each score is the mean of the four seats, to two decimals.
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Write their lines into a seats file and run `~/.claude/bin/larv-review record-scoring <file>`, which appends the run to the history and prints the four seats' means.
The chunk does not merge while either holds:
- **Ratchet.** The paired ruling is worse.
- **Floor.** The scoring run puts any dimension or the overall below 7.0.
- **Floor.** `record-scoring` names a mean under the floor of 7.0.
Each is a 🔴 of the comprehension check. It is never filed, and stands until a later run clears it or, for the floor, a decision to ship answers it.
@@ -108,16 +110,16 @@ Fix a worse ruling at the places the seats voting worse name, and the floor at t
Two files of the project keep the records:
- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## <UTC time, ISO 8601>, <PR or branch> at <commit>` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against <base>`. A paired ruling holds a `Ruling: <better, same or worse>` line, a table of each seat's vote, and under each seat, labelled `<seat>, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`, its places. A place is `path:line` and the unit's name, the path written from the repository's root. A bare `:line` is in the path named before it in the same bullet. `bin/metric_bench/places.py` reads this format: change both together. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first.
- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first.
- **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores.
A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run: a heading of the date or time the entry gives and whatever it names the run by, its commit included where named, and a table with the mean alone. The rest of the entry stays.
A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run. Write a seats file of two lines and run `~/.claude/bin/larv-review record-scoring` on it. The first line is `<the date or time the entry gives>, <what the entry names the run by> at <commit>`, the commit being the one the entry names, or else the one that wrote those scores into it. The second is `Mean:` and the five scores, in the shape `--help` shows. The rest of the entry stays.
Put each ruling with its base and votes, and each run's five scores, in the summary, and append them to the history on this branch. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`).
Put each ruling with its base and votes, and each run's five scores, in the summary. List in the entry each decision to ship under the floor, and file its places in `todo.md` per `~/.claude/CLAUDE.md` → "Todo items". A project without the entry gets it at its first scoring run, titled `comprehension floor: every dimension and the overall at 7.0 or above` and applying KISS (`~/.claude/principles/technical-principles.md`).
**Fresh.** Where the chunk ran a comprehension check, the architecture pass is done only once its last paired ruling, and its last scoring run where it ran one, read the commit to merge. They may predate commits that change only `docs/decisions.md`, `docs/comprehension-history.md`, `docs/reading-cost.md`, `todo.md` or `CHANGELOG.md`. Any other commit after them, a prose fix included, because the seats read the docs, calls for a rescore: the comprehension check again, once every other pass is done, the auto-reviewer included. A rescore reporting a 🔴 that no decision to ship answers is an architecture round. Any other rescore is not a round: append only its results to the history, in a commit titled `Rescore: …`. A `Rescore:` commit re-enters no pass: push it and wait for the forge's checks (§4 step 3), not for an auto-review.
**Suspended.** A decision in the project's `docs/decisions.md`, held before the chunk began, may name plan items to ship without a comprehension check. A named item counts as `todo.md` worded it before the chunk began. The decision must name the later plan item whose chunk ends the suspension with a comprehension check. A chunk may ship named items only with each other. Such a chunk skips the comprehension check, so neither the ratchet nor the floor can block it, and its summary cites the decision. A chunk that meets the scoring run's trigger runs it, even when every item it ships is named.
**Suspended.** A decision in the project's `docs/decisions.md`, held before the chunk began, may name plan items to ship without a comprehension check. A named item counts as `todo.md` worded it before the chunk began. The decision must name the later plan item whose chunk ends the suspension with a comprehension check. A chunk may ship named items only with each other. Such a chunk skips the comprehension check, so neither the ratchet nor the floor can block it, and its summary cites the decision. A chunk due a scoring run runs it, even when every item it ships is named.
### Security
+14 -11
View File
@@ -24,8 +24,6 @@
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 78 | 0.1.0 | | **Generate comprehension questions with deterministic scripts — from symbols, the call graph and the tests, each answer checkable by a tool — and bench the scores an agent gets on them against the panel, reading cost and static metrics.** | 3 | 7 | 9 | 8 | 1.1, 1.4 | 29.1 |
| 85 | 0.1.0 | decision | **Move larv-review's mechanical rules — the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format — into one tested tool under `bin/`, so the skill says only when to run it and what each answer means.** | 4 | 7 | 8 | 9 | 1.1 | 28.1 |
| 1 | 0.1.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 3, 4 | 27.0 |
| 62 | 0.1.0 | defect | **Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.** | 4 | 6 | 6 | 8 | 1.1 | 22.3 |
| 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 1.3 | 21.8 |
@@ -54,14 +52,6 @@
## Details
### 78. Generate comprehension questions with deterministic scripts — from symbols, the call graph and the tests, each answer checkable by a tool — and bench the scores an agent gets on them against the panel, reading cost and static metrics.
A hand-written question bank goes stale as the project grows and leaves everything it does not ask about unmeasured. A script that samples symbols at random each run ("what calls X?", "where is Y validated?", "which test fails if Z changes?") covers the whole project over time, and the call graph, grep and the tests hold the answers, so no judge is needed. Each answer names the code it rests on, so a question whose code changed is regenerated. Keep the method only where the bench shows it tracks the panel at a lower cost.
### 85. Move larv-review's mechanical rules — the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format — into one tested tool under `bin/`, so the skill says only when to run it and what each answer means.
2026-10-08, lilleman: next after item 78, which lowers token use. Every comprehension run since PR #224 named `skills/larv-review/SKILL.md` §3 "Architecture" the hardest place, and PR #228's paired ruling ruled worse on rules a program should hold: the base's `git log` search and fallbacks, the vote arithmetic, a trigger written out three times, and the round count PR #225's seats said only prose enforces. PR #228's reviewers found about twenty edge cases in that text, among them squash against merge commits, entry order, a vote with no place, and a trigger judged before items are removed; tests can hold each, prose could not. Keep the skill's judgement calls in prose, and give the tool the history's format, so the base search does not hang on the wording of a line. The history's reader in `bin/metric_bench/places.py` moves into that tool, so the format has one reader.
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
@@ -144,7 +134,7 @@ Goal 3, raised by the principles audit of PR #215: the judge runs with `--no-ses
2026-10-08, lilleman: rescored from A10/G8 to A4/G4 on the measurement below, so other items that lower token use go first.
Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matching each Agent call to its tool result and to any `<task-notification>` naming its tool-use id. No report reached the worker twice: 813 arrived once as the hand-back, and 363 once as a notification after Claude Code ran the agent in the background. Reports took a median 19k tokens per chunk, 8% of the worker's peak context (24% at most). Lines carrying a severity mark are 9–24% of a reviewer's report, and the worker would still open the file for each 🔴 or 🟡 it fixes. A third of the report volume is the comprehension seats', whose votes and places the worker copies into the history. File reads fill more of the worker's context: `sed -n` output is 30% of its Bash results and `grep` output 11%, which item 78 and `reading-cost` target.
Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matching each Agent call to its tool result and to any `<task-notification>` naming its tool-use id. No report reached the worker twice: 813 arrived once as the hand-back, and 363 once as a notification after Claude Code ran the agent in the background. Reports took a median 19k tokens per chunk, 8% of the worker's peak context (24% at most). Lines carrying a severity mark are 9–24% of a reviewer's report, and the worker would still open the file for each 🔴 or 🟡 it fixes. A third of the report volume is the comprehension seats', whose votes and places the worker copies into the history. File reads fill more of the worker's context: `sed -n` output is 30% of its Bash results and `grep` output 11%, which `reading-cost` targets.
The reports would live in the session's scratchpad, such as `<scratchpad>/larv-review/prose-round-1.md`, so no project's checkout sees them. A later round gets the path of that pass's earlier report in place of the findings pasted in. How a report reaches the file:
@@ -193,3 +183,16 @@ On 2026-10-08 only this repo's history named places: five scoring runs, all that
| Change spread | 0.67 | 0.18 |
AUC is 0.5 for a coin toss, and top k scores 0.10 by chance. Shared state cannot be judged here: every unit in `bin/` scores 0 on it. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees.
On 2026-10-09 a question bench asked a headless claude, allowed only Read, Grep and Glob, three questions a script answers from the syntax tree: which units call a unit, which units it calls, and which test files refer to it. It asked them about every unit the history names whose name is unique, plus as many units the history does not name. Five of the history's six scoring runs named such a unit. The tool is in commit 083cc78; it was deleted after the run.
Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chance on these units:
| Metric | AUC | Top k |
|---|---|---|
| Question misses | 0.49 | 0.50 |
| Cognitive complexity | 0.66 | 0.59 |
| Length | 0.75 | 0.69 |
| Change spread | 0.57 | 0.54 |
Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it.