From 77fef49fce968a134e68d7d14814f8e0af21c852 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:02:48 +0200 Subject: [PATCH 01/15] 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 --- .gitignore | 3 + CHANGELOG.md | 1 + README.md | 1 + bin/larv-review | 9 ++ bin/larv_review/__init__.py | 0 bin/larv_review/git.py | 73 +++++++++++ bin/larv_review/history.py | 110 ++++++++++++++++ bin/larv_review/main.py | 205 +++++++++++++++++++++++++++++ bin/larv_review/rules.py | 97 ++++++++++++++ bin/larv_review/seats.py | 82 ++++++++++++ bin/metric_bench/bench.py | 2 +- bin/metric_bench/main.py | 4 +- bin/metric_bench/places.py | 73 ----------- bin/test_larv_review.py | 251 ++++++++++++++++++++++++++++++++++++ bin/test_metric_bench.py | 2 +- bin/test_types.py | 2 +- docs/decisions.md | 4 +- skills/larv-review/SKILL.md | 22 ++-- 18 files changed, 851 insertions(+), 90 deletions(-) create mode 100755 bin/larv-review create mode 100644 bin/larv_review/__init__.py create mode 100644 bin/larv_review/git.py create mode 100644 bin/larv_review/history.py create mode 100644 bin/larv_review/main.py create mode 100644 bin/larv_review/rules.py create mode 100644 bin/larv_review/seats.py delete mode 100644 bin/metric_bench/places.py create mode 100644 bin/test_larv_review.py diff --git a/.gitignore b/.gitignore index a4eb7472..a2ded1f1 100644 --- a/.gitignore +++ b/.gitignore @@ -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/**/ diff --git a/CHANGELOG.md b/CHANGELOG.md index da92a9ae..6be4974c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ...`), 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 left with no plan item is due a scoring run however its items left, moved to another release included. - 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. diff --git a/README.md b/README.md index 674e4751..7a0f65a6 100644 --- a/README.md +++ b/README.md @@ -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 ` 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 ` 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. diff --git a/bin/larv-review b/bin/larv-review new file mode 100755 index 00000000..694c9522 --- /dev/null +++ b/bin/larv-review @@ -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:])) diff --git a/bin/larv_review/__init__.py b/bin/larv_review/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py new file mode 100644 index 00000000..92d03ad9 --- /dev/null +++ b/bin/larv_review/git.py @@ -0,0 +1,73 @@ +import dataclasses +import subprocess + +from failure import Failure +from larv_review.rules import HistoryChange + +HISTORY = "docs/comprehension-history.md" + + +@dataclasses.dataclass(frozen=True) +class Repository: + """The checkout the tool runs in: its top folder, and the default branch's ref after a fetch, `origin/` with a remote.""" + top: str + default: str + + +def git(*args: str) -> str | Failure: + try: + ran = subprocess.run(["git", *args], capture_output=True, text=True) + except (OSError, ValueError) as failure: + return Failure(f"git could not start: {failure}") + return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") + + +def repository() -> Repository | Failure: + top = git("rev-parse", "--show-toplevel") + if isinstance(top, Failure): + return top + remotes = git("remote") + if isinstance(remotes, Failure): + return remotes + if "origin" in remotes.split(): + if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure): + return fetched + default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") + if isinstance(default, Failure): + return Failure(f"origin names no default branch; set it with `git remote set-head origin --auto`: {default.reason}") + return Repository(top.strip(), default.strip()) + for branch in ("main", "master"): + if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): + return Repository(top.strip(), branch) + return Failure("no origin remote, and no main or master branch to take as the default branch") + + +def file_at(revision: str, path: str) -> str | Failure: + """A file's text at a revision, empty where the revision does not hold it.""" + if isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}:{path}"), Failure): + return "" + return git("show", f"{revision}:{path}") + + +def history_changes(default: str) -> list[HistoryChange] | Failure: + """Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent.""" + commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY) + if isinstance(commits, Failure): + return commits + changes = [] + for commit in commits.split(): + before = file_at(f"{commit}^1", HISTORY) + after = file_at(commit, HISTORY) + if isinstance(before, Failure): + return before + if isinstance(after, Failure): + return after + changes.append(HistoryChange(commit, before, after)) + return changes + + +def landed_since_release(default: str) -> bool | Failure: + """Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none.""" + tag = git("describe", "--tags", "--abbrev=0", "--match", "v*", default) + count = git("rev-list", "--count", default if isinstance(tag, Failure) else f"{tag.strip()}..{default}") + return count if isinstance(count, Failure) else int(count) > 0 diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py new file mode 100644 index 00000000..feeaabdb --- /dev/null +++ b/bin/larv_review/history.py @@ -0,0 +1,110 @@ +import dataclasses +import os +import re + +from markdown_sections import sections + +TITLE = "# Comprehension history\n" +HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$") +RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M) +SEAT_PLACES = re.compile(r"^.+, (decided by|hardest first|would restructure first):$") +# `path:line` or `:line`, then the unit's name where one follows. +PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?") + + +@dataclasses.dataclass(frozen=True) +class Place: + path: str + name: str | None + + +@dataclasses.dataclass(frozen=True) +class Entry: + """One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither.""" + heading: str + time: str + commit: str + against: str | None + ruling: str | None + places: list[Place] + + +@dataclasses.dataclass(frozen=True) +class ScoringRun: + heading: str + commit: str + places: list[Place] + + +def entries(history: str) -> list[Entry]: + """Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out.""" + found = [] + for heading, bodies in sections(history).items(): + if named := HEADING.match(heading): + body = "\n".join(bodies) + ruling = RULING.search(body) + found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body))) + return found + + +def scoring_runs(history: str) -> list[ScoringRun]: + """Each scoring run, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out.""" + return [ScoringRun(entry.heading, entry.commit, entry.places) for entry in entries(history) if entry.against is None] + + +def seat_places(body: str) -> list[Place]: + places = [] + listing = False + for line in body.splitlines(): + if SEAT_PLACES.match(line): + listing = True + elif listing and line.startswith("- "): + places += bullet_places(line) + elif not line.startswith(" "): + listing = False + return places + + +def bullet_places(bullet: str) -> list[Place]: + """A `:line` with no path is in the file named before it in the bullet.""" + places = [] + path = "" + for match in PLACE.finditer(bullet): + path = match.group(1) or path + if path: + places.append(Place(path, match.group(2))) + return places + + +def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]: + """Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones.""" + found = [] + dropped = [] + before = "" + for place in places: + candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)] + nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates + if len(nearest) == 1: + before = nearest[0] + found.append(Place(before, place.name)) + else: + dropped.append(place) + return found, dropped + + +def appended(history: str, entry: str) -> str: + """The history with entry added last; an empty history gets the file's title first.""" + text = history.rstrip("\n") + "\n" if history.strip() else TITLE + return f"{text}\n{entry}" + + +def entry_text(heading: str, lines: list[str], table: list[list[str]], seats: list[tuple[str, list[str]]]) -> str: + """An entry in the history's format: the heading, any lines such as `Ruling: same`, a table whose first row is its header, and under each seat's label its places, one bullet each.""" + header, *rows = table + parts = [f"## {heading}", *lines, "\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)])] + parts += [f"{label}\n\n" + "\n".join(f"- {place}" for place in places) for label, places in seats if places] + return "\n\n".join(parts) + "\n" + + +def row_text(cells: list[str]) -> str: + return "| " + " | ".join(cells) + " |" diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py new file mode 100644 index 00000000..f59bf17e --- /dev/null +++ b/bin/larv_review/main.py @@ -0,0 +1,205 @@ +"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format. + +usage: larv-review ruling-base | round-count | needs-scoring-run ... | record-ruling | record-scoring + +Run it inside a project checkout or one of its worktrees. It first fetches origin, when the checkout +has that remote, and takes origin's default branch, or else the local main or master, as the +default branch. The history is docs/comprehension-history.md in the checkout. + +ruling-base prints the commit a paired ruling reads against, then how it was found: the default +branch's newest merged change that adds a scoring run to the history, or whose last added paired +ruling, by its heading's time, is better; a merge commit is one change against its first parent. +With none, the base the history's first paired ruling names; with no ruling either, the merge base +of HEAD and the default branch. + +round-count prints, for each pass, the highest among this branch's commit titles opening +`Answer round :`, counting commits the default branch does not hold, and marks a pass at +the cap of 3 rounds. + +needs-scoring-run prints why the chunk shipping the given todo.md item IDs takes a scoring run, or +`No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension +floor, or when a release the default branch's todo.md names has no item left in the checkout's +todo.md, less the items shipped, and work has landed towards it: the chunk ships one of its items, +or it is the earliest release the default branch's todo.md names and the default branch has a +commit after its newest v* tag, or has no such tag. + +record-ruling and record-scoring read a seats file: a first line naming what the seats read, then +each seat's line, each followed by its places, one `- ` bullet each, as the history writes them: + + PR #231 at abc1234, against def5678 + + Mid A: worse + + - `bin/x.py:12` `run`: three branches to hold at once + + Inherited architect: worse + + - `bin/x.py:12` `run`: ... + +record-ruling takes Mid A's and the inherited architect's votes, better, same or worse; a better or +worse vote naming no `path:line` place counts as same. When the two counted votes differ, it +appends nothing and says to add the maintainability senior's and Junior A's lines. Otherwise the +ruling is the vote that leads each other vote by two or more, else same, and it appends the ruling. + +record-scoring takes Junior A's, Mid A's, the maintainability senior's and the inherited +architect's lines in that order, each `Navigation , Locality , Shape , Self-sufficiency +, Overall `, each score from 1 to 10 and the overall at most 1 above the seat's lowest +dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded +half up to two decimals, and prints the means and each one under the floor of 7.0. + +Each record is appended to the history, created when missing, under a heading of the current UTC +time and the seats file's first line. + +Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that +breaks the shape above, or when git cannot start, finds no checkout or no default branch, or the +history or todo.md cannot be read or written. +""" +import pathlib +import sys +import time + +from larv_review.history import appended, entry_text, HEADING +from larv_review.rules import CAP, first_ruling, means, measured_commit, plan_items, round_counts, scoring_run_due, under_floor +from larv_review.seats import DIMENSIONS, Report, report, ruling, scores, votes +from failure import Failure +from larv_review.git import file_at, git, HISTORY, history_changes, landed_since_release, Repository, repository +from file_writes import replace_file +from loop_claude.transcript_archive import utc + +USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run ... | record-ruling | record-scoring " + + +def main(argv: list[str]) -> int: + if argv in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + command, *given = argv or [""] + valid = {"ruling-base": not given, "round-count": not given, "needs-scoring-run": bool(given) and all(id_.isdigit() for id_ in given), "record-ruling": len(given) == 1, "record-scoring": len(given) == 1} + if not valid.get(command): + print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) + return 1 + repo = repository() + if isinstance(repo, Failure): + return failed(repo) + if command == "ruling-base": + done = ruling_base(repo) + elif command == "round-count": + done = round_count(repo) + elif command == "needs-scoring-run": + done = needs_scoring_run(repo, [int(id_) for id_ in given]) + else: + done = record(repo, pathlib.Path(given[0]), command == "record-ruling", utc(time.time())) + return failed(done) if isinstance(done, Failure) else 0 + + +def ruling_base(repo: Repository) -> Failure | None: + changes = history_changes(repo.default) + if isinstance(changes, Failure): + return changes + if found := measured_commit(changes): + print(f"{found}\nThe newest merged change on {repo.default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.") + return None + history = file_at(repo.default, HISTORY) + if isinstance(history, Failure): + return history + if (first := first_ruling(history)) and first.against: + print(f"{first.against}\nNo merged change on {repo.default} adds a scoring run or a better ruling; the base its first paired ruling names.") + return None + merge_base = git("merge-base", "HEAD", repo.default) + if isinstance(merge_base, Failure): + return merge_base + print(f"{merge_base.strip()}\nNo merged change on {repo.default} adds a scoring run or a paired ruling; the merge base of HEAD and {repo.default}.") + return None + + +def round_count(repo: Repository) -> Failure | None: + titles = git("log", "--format=%s", f"{repo.default}..HEAD") + if isinstance(titles, Failure): + return titles + for name, count in round_counts(titles.splitlines()).items(): + print(f"{name}: {count}{', at the cap' if count >= CAP else ''}") + return None + + +def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None: + before = file_at(repo.default, "todo.md") + if isinstance(before, Failure): + return before + try: + after = pathlib.Path(repo.top, "todo.md").read_text(encoding="utf-8") + except FileNotFoundError: + after = "" + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read todo.md: {failure}") + planned = plan_items(before) + if isinstance(planned, Failure): + return planned + chunk = plan_items(after) + if isinstance(chunk, Failure): + return chunk + if unknown := sorted(set(ids) - {item.id for item in planned + chunk}): + return Failure(f"neither {repo.default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}") + landed = landed_since_release(repo.default) + if isinstance(landed, Failure): + return landed + reasons = scoring_run_due(planned, chunk, ids, landed) + print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.") + return None + + +def record(repo: Repository, seats_file: pathlib.Path, paired: bool, now: str) -> Failure | None: + try: + given = report(seats_file.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {seats_file}: {failure}") + if isinstance(given, Failure): + return given + heading = f"{now}, {given.read}" + if not (named := HEADING.match(heading)) or bool(named.group(4)) != paired: + return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {given.read}") + entry = ruling_entry(heading, given) if paired else scoring_entry(heading, given) + if isinstance(entry, Failure) or entry is None: + return entry + history = pathlib.Path(repo.top, HISTORY) + try: + text = history.read_text(encoding="utf-8") if history.exists() else "" + history.parent.mkdir(parents=True, exist_ok=True) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {history}: {failure}") + unwritten = replace_file(history, appended(text, entry).encode()) + if unwritten: + return Failure(f"could not write {history}: {unwritten.reason}") + print(f"Appended to {history}.") + return None + + +def ruling_entry(heading: str, given: Report) -> str | Failure | None: + """The ruling's entry, or None, after saying which seats to add, when the first two counted votes differ.""" + counted = votes(given.seats) + if isinstance(counted, Failure): + return counted + tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) + result = ruling(list(counted.values())) + if result is None: + print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") + return None + print(f"Ruling: {result}. Votes as counted: {tally}.") + cells = [[seat.name, counted[seat.name] if counted[seat.name] == seat.said else f"same (voted {seat.said}, naming no place)"] for seat in given.seats] + return entry_text(heading, [f"Ruling: {result}"], [["Seat", "Vote"], *cells], [(f"{seat.name}, decided by:", seat.places) for seat in given.seats]) + + +def scoring_entry(heading: str, given: Report) -> str | Failure: + found = scores(given.seats) + if isinstance(found, Failure): + return found + mean = means(found) + under = under_floor(mean) + print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {'Under the floor of 7.0: ' + ', '.join(under) if under else 'None under the floor of 7.0'}.") + rows = [[seat, *values] for seat, values in found.items()] + [["Mean", *map(str, mean)]] + labels = [(f"{seat.name}, {'would restructure first' if seat.name == 'Inherited architect' else 'hardest first'}:", seat.places) for seat in given.seats] + return entry_text(heading, [], [["Seat", *DIMENSIONS], *rows], labels) + + +def failed(failure: Failure) -> int: + print(failure.reason, file=sys.stderr) + return 1 diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py new file mode 100644 index 00000000..4acf3c4e --- /dev/null +++ b/bin/larv_review/rules.py @@ -0,0 +1,97 @@ +import dataclasses +import decimal +import re + +from rank_todo import cells, ITEMS_HEADER, table_rows +from larv_review.seats import DIMENSIONS +from larv_review.history import entries, Entry +from failure import Failure + +CAP = 3 +FLOOR = decimal.Decimal("7.0") +PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose") +ROUND = re.compile(r"^Answer (.+) round ([0-9]+):") + + +@dataclasses.dataclass(frozen=True) +class HistoryChange: + """A merged change on the default branch that touched the history, and the history before and after it.""" + commit: str + before: str + after: str + + +@dataclasses.dataclass(frozen=True) +class PlanItem: + id: int + release: tuple[int, int, int] + tagline: str + + +def means(scores: dict[str, list[str]]) -> list[decimal.Decimal]: + """The seats' mean of each score, in DIMENSIONS' order, rounded half up to two decimals.""" + return [(sum((decimal.Decimal(seat[index]) for seat in scores.values()), decimal.Decimal(0)) / len(scores)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP) for index in range(len(DIMENSIONS))] + + +def under_floor(found: list[decimal.Decimal]) -> list[str]: + return [f"{name} {mean}" for name, mean in zip(DIMENSIONS, found) if mean < FLOOR] + + +def round_counts(titles: list[str]) -> dict[str, int]: + """Each pass's highest round among the branch's `Answer round :` commit titles; a pass with none has 0.""" + counts = dict.fromkeys(PASSES, 0) + for title in titles: + if named := ROUND.match(title): + counts[named.group(1)] = max(counts.get(named.group(1), 0), int(named.group(2))) + return counts + + +def measured_commit(changes: list[HistoryChange]) -> str | None: + """The newest change, of changes given newest first, that adds a scoring run to the history, or whose last added paired ruling is better.""" + for change in changes: + held = {entry.heading for entry in entries(change.before)} + added = [entry for entry in entries(change.after) if entry.heading not in held] + rulings = sorted((entry for entry in added if entry.against), key=lambda entry: entry.time) + if any(entry.against is None for entry in added) or rulings and rulings[-1].ruling == "better": + return change.commit + return None + + +def first_ruling(history: str) -> Entry | None: + rulings = sorted((entry for entry in entries(history) if entry.against), key=lambda entry: entry.time) + return rulings[0] if rulings else None + + +def plan_items(todo: str) -> list[PlanItem] | Failure: + """The ID, release and tagline of each row in a todo.md's items table, in the shape `rank_todo.py --help` shows; a plan with no table has no items.""" + lines = todo.splitlines() + if ITEMS_HEADER not in lines: + return [] + table = table_rows(lines, ITEMS_HEADER) + if isinstance(table, Failure): + return table + items = [] + for row in table.rows: + found = cells(row, 10) + if isinstance(found, Failure): + return found + id_, release, _, tagline, *_ = found + if not re.fullmatch(r"[0-9]+", id_) or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release): + return Failure(f"a todo.md row has no whole-number ID or no semver release: {row}") + major, minor, patch = (int(part) for part in release.split(".")) + items.append(PlanItem(int(id_), (major, minor, patch), tagline)) + return items + + +def scoring_run_due(before: list[PlanItem], after: list[PlanItem], ships: list[int], landed: bool) -> list[str]: + """Why the chunk takes a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release before names and landed holds.""" + plan = {item.id: item for item in before + after} + shipped = [plan[id_] for id_ in ships] + reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()] + left = {item.release for item in after if item.id not in ships} + named = {item.release for item in before} | {item.release for item in shipped} + earliest = min((item.release for item in before), default=None) + for release in sorted(named - left): + if any(item.release == release for item in shipped) or release == earliest and landed: + reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item") + return reasons diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py new file mode 100644 index 00000000..a711d06b --- /dev/null +++ b/bin/larv_review/seats.py @@ -0,0 +1,82 @@ +import dataclasses +import re + +from failure import Failure + +DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") +FIRST_SEATS = ("Mid A", "Inherited architect") +SPLIT_SEATS = ("Maintainability senior", "Junior A") +SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", "Inherited architect") +SEAT_LINE = re.compile(r"^(Junior A|Mid A|Maintainability senior|Inherited architect): (.+)$") +SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS)) +VOTES = ("better", "same", "worse") + + +@dataclasses.dataclass(frozen=True) +class Seat: + name: str + said: str + places: list[str] + + +@dataclasses.dataclass(frozen=True) +class Report: + """A seats file: what the seats read, ` at `, with `, against ` for a paired ruling, then each seat's line and its places.""" + read: str + seats: list[Seat] + + +def report(text: str) -> Report | Failure: + lines = [line for line in text.splitlines() if line.strip()] + if not lines: + return Failure("the seats file is empty; its first line names what the seats read: at ") + seats: list[Seat] = [] + for line in lines[1:]: + if seat := SEAT_LINE.match(line): + if seat.group(1) in [known.name for known in seats]: + return Failure(f"{seat.group(1)} appears twice in the seats file") + seats.append(Seat(seat.group(1), seat.group(2).strip(), [])) + elif seats and line.startswith("- "): + seats[-1].places.append(line[2:].strip()) + elif seats and seats[-1].places and line.startswith(" "): + seats[-1].places[-1] += " " + line.strip() + else: + return Failure(f"the seats file has a line that is neither a seat's line nor one of its places: {line}") + return Report(lines[0].strip(), seats) + + +def votes(seats: list[Seat]) -> dict[str, str] | Failure: + """Each seat's vote as it counts: a better or worse vote naming no `path:line` place counts as same.""" + names = [seat.name for seat in seats] + if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)): + return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}") + if unknown := [seat for seat in seats if seat.said not in VOTES]: + return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse") + return {seat.name: seat.said if seat.said == "same" or any(re.search(r"`[^`\s]*:\d+`", place) for place in seat.places) else "same" for seat in seats} + + +def ruling(counted: list[str]) -> str | None: + """The vote that leads each other vote by two or more, else same; None when only the first two seats voted and they differ, so two more must vote.""" + if len(counted) == 2 and counted[0] != counted[1]: + return None + for vote in VOTES: + if all(counted.count(vote) >= counted.count(other) + 2 for other in VOTES if other != vote): + return vote + return "same" + + +def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure: + """Each seat's five scores as written, in DIMENSIONS' order.""" + if [seat.name for seat in seats] != list(SCORING_SEATS): + return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order; the file has {', '.join(seat.name for seat in seats) or 'none'}") + found = {} + for seat in seats: + if not (written := SCORES.fullmatch(seat.said)): + return Failure(f"{seat.name}'s line is not {', '.join(name + ' ' for name in DIMENSIONS)}: {seat.said}") + values = [float(value) for value in written.groups()] + if not all(1 <= value <= 10 for value in values): + return Failure(f"{seat.name}'s scores are not each from 1 to 10: {seat.said}") + if values[-1] > min(values[:-1]) + 1: + return Failure(f"{seat.name}'s overall exceeds their lowest dimension by more than 1; ask the seat to rescore: {seat.said}") + found[seat.name] = list(written.groups()) + return found diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index bcf67aec..f39ac536 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -3,7 +3,7 @@ import collections import dataclasses 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]] = { diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index e26712da..6efa65a3 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -37,7 +37,7 @@ import sys from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score from failure import Failure from metric_bench.python_units import measured, python_units, Unit -from metric_bench.places import resolved, scoring_runs, ScoringRun +from larv_review.history 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 diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py deleted file mode 100644 index 3d22fbc5..00000000 --- a/bin/metric_bench/places.py +++ /dev/null @@ -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 diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py new file mode 100644 index 00000000..648e5399 --- /dev/null +++ b/bin/test_larv_review.py @@ -0,0 +1,251 @@ +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, entry_text, Place, scoring_runs +from failure import Failure +from larv_review.rules import first_ruling, HistoryChange, means, measured_commit, plan_items, PlanItem, round_counts, scoring_run_due, under_floor +from test_loop_claude_black_box import host_env +from larv_review.seats import report, ruling, scores, Seat, votes + +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.**") -> PlanItem: + return PlanItem(id_, release, tagline) + + +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_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) + + def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self): + found = means({"a": ["7.5", "6.5", "7", "7", "7"], "b": ["7.5", "7", "7", "6.5", "7"], "c": ["7", "6.5", "7", "6.5", "6.5"], "d": ["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): + ruled = entry_text("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", ["Ruling: worse"], [["Seat", "Vote"], ["Mid A", "worse"]], [("Mid A, decided by:", ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), ("Inherited architect, decided by:", [])]) + 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) + 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([run.commit for run in scoring_runs(history)], ["aaaaaaa"]) + + +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_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", "Rescore: w"]) + self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"]), (1, 2, 0, 0)) + + +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.assertEqual(plan_items("# todo\n"), []) + self.assertIsInstance(plan_items(todo("| x | 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"]) + + 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") + + 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) + + def test_records_a_ruling_once_four_seats_settle_a_split(self): + lines = """\ + PR #2 at abc1234, against def5678 + + Mid A: worse + + - `bin/a.py:3` `f`: three branches + + Inherited architect: same + """ + 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.") + recorded = entries(history.read_text()) + self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [("abc1234", "def5678", "same")]) + 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("PR #2 at abc1234\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([run.places for run in scoring_runs(text)], [[Place("bin/a.py", "f")] * 4]) + + def test_refuses_a_ruling_file_that_names_no_base(self): + ran = self.run_tool("record-ruling", self.seats_file("PR #2 at abc1234\n\nMid A: same\n\nInherited architect: same\n")) + self.assertEqual(ran.returncode, 1) + self.assertIn("against ", ran.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index e922279c..9adbbe32 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -13,7 +13,7 @@ from metric_bench.bench import auc, bench, co_changed, top_k from metric_bench.python_units import cognitive, measured, python_units, Unit from failure import Failure from test_loop_claude_black_box import host_env -from metric_bench.places import Place, resolved, scoring_runs +from larv_review.history import Place, resolved, scoring_runs TOOL = pathlib.Path(__file__).resolve().parent / "metric-bench" diff --git a/bin/test_types.py b/bin/test_types.py index 25721a39..1a6b2c80 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -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) diff --git a/docs/decisions.md b/docs/decisions.md index e0146ca4..477b7ee8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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 diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 72bedbbc..09d565c1 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -32,13 +32,15 @@ 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 | | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk, one round | +`~/.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; `larv-review --help` states each rule. On exit 1, repair what its message names and run it again. + A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone. @@ -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 round : โ€ฆ`, `` 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 `` among titles holding `Answer round :` in `git log origin/..HEAD` after a `git fetch`, or in `git log ..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 round : โ€ฆ`, `` 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. `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 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/`, 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/ -- docs/comprehension-history.md`; with no remote, use ``. 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 `larv-review ruling-base` prints. - **Head.** Before each ruling, merge `origin/` 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 `larv-review --help` shows, and run `larv-review record-ruling `. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. +- **Ruling.** The `Ruling:` line it prints, which it 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 `larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `larv-review record-scoring `, 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 `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, 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 `, hardest first:` or, for the architect, `, 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; nothing edits them. 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. -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 -- 2.52.0 From 53ed5150bed80fcef695ee0494d29ab94c05b6dc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:10:01 +0200 Subject: [PATCH 02/15] Keep the history's writer beside its reader, read plan rows with rank_todo, and fetch only for commands that read the default branch --- bin/larv_review/git.py | 41 +++++----- bin/larv_review/history.py | 33 ++++++-- bin/larv_review/main.py | 152 ++++++++++++++++++------------------- bin/larv_review/rules.py | 66 ++++++++++------ bin/larv_review/seats.py | 23 ------ bin/rank_todo.py | 12 ++- bin/test_larv_review.py | 22 +++--- todo.md | 2 +- 8 files changed, 189 insertions(+), 162 deletions(-) diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 92d03ad9..960072b5 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,4 +1,3 @@ -import dataclasses import subprocess from failure import Failure @@ -7,13 +6,6 @@ from larv_review.rules import HistoryChange HISTORY = "docs/comprehension-history.md" -@dataclasses.dataclass(frozen=True) -class Repository: - """The checkout the tool runs in: its top folder, and the default branch's ref after a fetch, `origin/` with a remote.""" - top: str - default: str - - def git(*args: str) -> str | Failure: try: ran = subprocess.run(["git", *args], capture_output=True, text=True) @@ -22,10 +14,13 @@ def git(*args: str) -> str | Failure: return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") -def repository() -> Repository | Failure: - top = git("rev-parse", "--show-toplevel") - if isinstance(top, Failure): - return top +def top() -> str | Failure: + found = git("rev-parse", "--show-toplevel") + return found if isinstance(found, Failure) else found.strip() + + +def default_branch() -> str | Failure: + """The default branch's ref: `origin/` after a fetch, with that remote, else the local main or master.""" remotes = git("remote") if isinstance(remotes, Failure): return remotes @@ -35,18 +30,21 @@ def repository() -> Repository | Failure: default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") if isinstance(default, Failure): return Failure(f"origin names no default branch; set it with `git remote set-head origin --auto`: {default.reason}") - return Repository(top.strip(), default.strip()) + return default.strip() for branch in ("main", "master"): if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): - return Repository(top.strip(), branch) + return branch return Failure("no origin remote, and no main or master branch to take as the default branch") def file_at(revision: str, path: str) -> str | Failure: - """A file's text at a revision, empty where the revision does not hold it.""" - if isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}:{path}"), Failure): + """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 isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}^{{commit}}"), Failure): return "" - return git("show", f"{revision}:{path}") + 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: @@ -57,9 +55,9 @@ def history_changes(default: str) -> list[HistoryChange] | Failure: changes = [] for commit in commits.split(): before = file_at(f"{commit}^1", HISTORY) - after = file_at(commit, HISTORY) if isinstance(before, Failure): return before + after = file_at(commit, HISTORY) if isinstance(after, Failure): return after changes.append(HistoryChange(commit, before, after)) @@ -68,6 +66,9 @@ def history_changes(default: str) -> list[HistoryChange] | Failure: def landed_since_release(default: str) -> bool | Failure: """Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none.""" - tag = git("describe", "--tags", "--abbrev=0", "--match", "v*", default) - count = git("rev-list", "--count", default if isinstance(tag, Failure) else f"{tag.strip()}..{default}") + tags = git("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 diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index feeaabdb..92ae74a5 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -1,15 +1,21 @@ import dataclasses import os import re +import time +from larv_review.seats import DIMENSIONS, Seat from markdown_sections import sections -TITLE = "# Comprehension history\n" +DECIDED_BY = "decided by" +HARDEST_FIRST = "hardest first" +WOULD_RESTRUCTURE_FIRST = "would restructure first" HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$") RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M) -SEAT_PLACES = re.compile(r"^.+, (decided by|hardest first|would restructure first):$") +SEAT_PLACES = re.compile(rf"^.+, ({DECIDED_BY}|{HARDEST_FIRST}|{WOULD_RESTRUCTURE_FIRST}):$") # `path:line` or `:line`, then the unit's name where one follows. PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?") +STAMP = "%Y-%m-%dT%H:%M:%SZ" +TITLE = "# Comprehension history\n" @dataclasses.dataclass(frozen=True) @@ -92,16 +98,33 @@ def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list return found, dropped +def heading(at: float, read: str) -> str: + """An entry's heading: when the seats finished, in UTC, and what they read.""" + return f"{time.strftime(STAMP, time.gmtime(at))}, {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 entry_text(heading: str, lines: list[str], table: list[list[str]], seats: list[tuple[str, list[str]]]) -> str: - """An entry in the history's format: the heading, any lines such as `Ruling: same`, a table whose first row is its header, and under each seat's label its places, one bullet each.""" +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, counted[seat.name] if counted[seat.name] == seat.said else f"same (voted {seat.said}, naming no place)"] 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 scoring_entry(title: str, seats: list[Seat], scores: dict[str, list[str]], means: list[str]) -> str: + rows = [[seat, *values] for seat, values in scores.items()] + [["Mean", *means]] + labels = [(f"{seat.name}, {WOULD_RESTRUCTURE_FIRST if seat.name == 'Inherited 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"## {heading}", *lines, "\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)])] + 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" diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index f59bf17e..285e5102 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -2,9 +2,10 @@ usage: larv-review ruling-base | round-count | needs-scoring-run ... | record-ruling | record-scoring -Run it inside a project checkout or one of its worktrees. It first fetches origin, when the checkout -has that remote, and takes origin's default branch, or else the local main or master, as the -default branch. The history is docs/comprehension-history.md in the checkout. +Run it inside a project checkout or one of its worktrees. ruling-base, round-count and +needs-scoring-run first fetch origin, when the checkout has that remote, and take origin's default +branch, or else the local main or master, as the default branch. The history is +docs/comprehension-history.md in the checkout. ruling-base prints the commit a paired ruling reads against, then how it was found: the default branch's newest merged change that adds a scoring run to the history, or whose last added paired @@ -14,7 +15,7 @@ of HEAD and the default branch. round-count prints, for each pass, the highest among this branch's commit titles opening `Answer round :`, counting commits the default branch does not hold, and marks a pass at -the cap of 3 rounds. +the cap of 3 rounds, and a name in such a title that is no pass. needs-scoring-run prints why the chunk shipping the given todo.md item IDs takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension @@ -57,14 +58,14 @@ history or todo.md cannot be read or written. import pathlib import sys import time +import typing -from larv_review.history import appended, entry_text, HEADING -from larv_review.rules import CAP, first_ruling, means, measured_commit, plan_items, round_counts, scoring_run_due, under_floor -from larv_review.seats import DIMENSIONS, Report, report, ruling, scores, votes +from larv_review.history import appended, HEADING, heading, ruling_entry, scoring_entry +from larv_review.rules import CAP, first_ruling, means, measured_commit, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes +from larv_review.git import default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top +from larv_review.seats import DIMENSIONS, report, scores from failure import Failure -from larv_review.git import file_at, git, HISTORY, history_changes, landed_since_release, Repository, repository from file_writes import replace_file -from loop_claude.transcript_archive import utc USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run ... | record-ruling | record-scoring " @@ -74,59 +75,64 @@ def main(argv: list[str]) -> int: print(__doc__.strip()) return 0 command, *given = argv or [""] - valid = {"ruling-base": not given, "round-count": not given, "needs-scoring-run": bool(given) and all(id_.isdigit() for id_ in given), "record-ruling": len(given) == 1, "record-scoring": len(given) == 1} - if not valid.get(command): + if command in ("ruling-base", "round-count") and not given: + done = with_default_branch(ruling_base if command == "ruling-base" else round_count) + elif command == "needs-scoring-run" and given and all(id_.isdigit() for id_ in given): + done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given])) + elif command in ("record-ruling", "record-scoring") and len(given) == 1: + done = record(pathlib.Path(given[0]), command == "record-ruling") + else: print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) return 1 - repo = repository() - if isinstance(repo, Failure): - return failed(repo) - if command == "ruling-base": - done = ruling_base(repo) - elif command == "round-count": - done = round_count(repo) - elif command == "needs-scoring-run": - done = needs_scoring_run(repo, [int(id_) for id_ in given]) - else: - done = record(repo, pathlib.Path(given[0]), command == "record-ruling", utc(time.time())) - return failed(done) if isinstance(done, Failure) else 0 + if isinstance(done, Failure): + print(done.reason, file=sys.stderr) + return 1 + return 0 -def ruling_base(repo: Repository) -> Failure | None: - changes = history_changes(repo.default) +def with_default_branch(command: typing.Callable[[str], Failure | None]) -> Failure | None: + default = default_branch() + return default if isinstance(default, Failure) else command(default) + + +def ruling_base(default: str) -> Failure | None: + changes = history_changes(default) if isinstance(changes, Failure): return changes if found := measured_commit(changes): - print(f"{found}\nThe newest merged change on {repo.default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.") + print(f"{found}\nThe newest merged change on {default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.") return None - history = file_at(repo.default, HISTORY) + history = file_at(default, HISTORY) if isinstance(history, Failure): return history if (first := first_ruling(history)) and first.against: - print(f"{first.against}\nNo merged change on {repo.default} adds a scoring run or a better ruling; the base its first paired ruling names.") + print(f"{first.against}\nNo merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names.") return None - merge_base = git("merge-base", "HEAD", repo.default) + merge_base = git("merge-base", "HEAD", default) if isinstance(merge_base, Failure): return merge_base - print(f"{merge_base.strip()}\nNo merged change on {repo.default} adds a scoring run or a paired ruling; the merge base of HEAD and {repo.default}.") + print(f"{merge_base.strip()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.") return None -def round_count(repo: Repository) -> Failure | None: - titles = git("log", "--format=%s", f"{repo.default}..HEAD") +def round_count(default: str) -> Failure | None: + titles = git("log", "--format=%s", f"{default}..HEAD") if isinstance(titles, Failure): return titles for name, count in round_counts(titles.splitlines()).items(): - print(f"{name}: {count}{', at the cap' if count >= CAP else ''}") + print(f"{name}: {count}{', at the cap' if count >= CAP else ''}{'' if name in PASSES else ', not a pass: check the commit title'}") return None -def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None: - before = file_at(repo.default, "todo.md") +def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: + checkout = top() + if isinstance(checkout, Failure): + return checkout + before = file_at(default, "todo.md") if isinstance(before, Failure): return before try: - after = pathlib.Path(repo.top, "todo.md").read_text(encoding="utf-8") + after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8") except FileNotFoundError: after = "" except (OSError, UnicodeDecodeError) as failure: @@ -138,8 +144,8 @@ def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None: if isinstance(chunk, Failure): return chunk if unknown := sorted(set(ids) - {item.id for item in planned + chunk}): - return Failure(f"neither {repo.default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}") - landed = landed_since_release(repo.default) + return Failure(f"neither {default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}") + landed = landed_since_release(default) if isinstance(landed, Failure): return landed reasons = scoring_run_due(planned, chunk, ids, landed) @@ -147,59 +153,47 @@ def needs_scoring_run(repo: Repository, ids: list[int]) -> Failure | None: return None -def record(repo: Repository, seats_file: pathlib.Path, paired: bool, now: str) -> Failure | None: +def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: try: given = report(seats_file.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {seats_file}: {failure}") if isinstance(given, Failure): return given - heading = f"{now}, {given.read}" - if not (named := HEADING.match(heading)) or bool(named.group(4)) != paired: + title = heading(time.time(), given.read) + if not (named := HEADING.match(title)) or bool(named.group(4)) != paired: return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {given.read}") - entry = ruling_entry(heading, given) if paired else scoring_entry(heading, given) - if isinstance(entry, Failure) or entry is None: - return entry - history = pathlib.Path(repo.top, HISTORY) - try: - text = history.read_text(encoding="utf-8") if history.exists() else "" - history.parent.mkdir(parents=True, exist_ok=True) - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"could not read {history}: {failure}") - unwritten = replace_file(history, appended(text, entry).encode()) - if unwritten: - return Failure(f"could not write {history}: {unwritten.reason}") - print(f"Appended to {history}.") - return None - - -def ruling_entry(heading: str, given: Report) -> str | Failure | None: - """The ruling's entry, or None, after saying which seats to add, when the first two counted votes differ.""" - counted = votes(given.seats) - if isinstance(counted, Failure): - return counted - tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) - result = ruling(list(counted.values())) - if result is None: - print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") - return None - print(f"Ruling: {result}. Votes as counted: {tally}.") - cells = [[seat.name, counted[seat.name] if counted[seat.name] == seat.said else f"same (voted {seat.said}, naming no place)"] for seat in given.seats] - return entry_text(heading, [f"Ruling: {result}"], [["Seat", "Vote"], *cells], [(f"{seat.name}, decided by:", seat.places) for seat in given.seats]) - - -def scoring_entry(heading: str, given: Report) -> str | Failure: + if paired: + counted = votes(given.seats) + if isinstance(counted, Failure): + return counted + tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) + ruled = ruling(list(counted.values())) + if ruled is None: + print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") + return None + print(f"Ruling: {ruled}. Votes as counted: {tally}.") + return append(ruling_entry(title, given.seats, counted, ruled)) found = scores(given.seats) if isinstance(found, Failure): return found mean = means(found) under = under_floor(mean) print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {'Under the floor of 7.0: ' + ', '.join(under) if under else 'None under the floor of 7.0'}.") - rows = [[seat, *values] for seat, values in found.items()] + [["Mean", *map(str, mean)]] - labels = [(f"{seat.name}, {'would restructure first' if seat.name == 'Inherited architect' else 'hardest first'}:", seat.places) for seat in given.seats] - return entry_text(heading, [], [["Seat", *DIMENSIONS], *rows], labels) + return append(scoring_entry(title, given.seats, found, [str(value) for value in mean])) -def failed(failure: Failure) -> int: - print(failure.reason, file=sys.stderr) - return 1 +def append(entry: str) -> Failure | None: + checkout = top() + if isinstance(checkout, Failure): + return checkout + history = pathlib.Path(checkout, HISTORY) + try: + text = history.read_text(encoding="utf-8") if history.exists() else "" + history.parent.mkdir(parents=True, exist_ok=True) + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {history}: {failure}") + if unwritten := replace_file(history, appended(text, entry).encode()): + return Failure(f"could not write {history}: {unwritten.reason}") + print(f"Appended to {history}.") + return None diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index 4acf3c4e..e80e4fcd 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -2,15 +2,18 @@ import dataclasses import decimal import re -from rank_todo import cells, ITEMS_HEADER, table_rows -from larv_review.seats import DIMENSIONS -from larv_review.history import entries, Entry +from larv_review.seats import DIMENSIONS, Seat +from larv_review.history import entries, Entry, PLACE from failure import Failure +from rank_todo import Item, ITEMS_HEADER, parse_row, table_rows CAP = 3 +FIRST_SEATS = ("Mid A", "Inherited architect") FLOOR = decimal.Decimal("7.0") PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose") ROUND = re.compile(r"^Answer (.+) round ([0-9]+):") +SPLIT_SEATS = ("Maintainability senior", "Junior A") +VOTES = ("better", "same", "worse") @dataclasses.dataclass(frozen=True) @@ -21,24 +24,45 @@ class HistoryChange: after: str -@dataclasses.dataclass(frozen=True) -class PlanItem: - id: int - release: tuple[int, int, int] - tagline: str +def votes(seats: list[Seat]) -> dict[str, str] | Failure: + """Each seat's vote as it counts: a better or worse vote naming no `path:line` place counts as same.""" + names = [seat.name for seat in seats] + if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)): + return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}") + if unknown := [seat for seat in seats if seat.said not in VOTES]: + return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse") + return {seat.name: seat.said if names_a_place(seat) else "same" for seat in seats} + + +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(scores: dict[str, list[str]]) -> list[decimal.Decimal]: - """The seats' mean of each score, in DIMENSIONS' order, rounded half up to two decimals.""" - return [(sum((decimal.Decimal(seat[index]) for seat in scores.values()), decimal.Decimal(0)) / len(scores)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP) for index in range(len(DIMENSIONS))] + """The seats' mean of each score, in the order each seat's scores are, rounded half up to two decimals.""" + return [mean([decimal.Decimal(score) for score in column]) for column in zip(*scores.values())] + + +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} {mean}" for name, mean in zip(DIMENSIONS, found) if mean < FLOOR] + 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 round :` commit titles; a pass with none has 0.""" + """Each pass's highest round among the branch's `Answer round :` 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): @@ -62,8 +86,8 @@ def first_ruling(history: str) -> Entry | None: return rulings[0] if rulings else None -def plan_items(todo: str) -> list[PlanItem] | Failure: - """The ID, release and tagline of each row in a todo.md's items table, in the shape `rank_todo.py --help` shows; a plan with no table has no items.""" +def plan_items(todo: str) -> list[Item] | Failure: + """Each row of a todo.md's items table, read as `rank_todo.py` reads it; a plan with no table has no items.""" lines = todo.splitlines() if ITEMS_HEADER not in lines: return [] @@ -72,18 +96,14 @@ def plan_items(todo: str) -> list[PlanItem] | Failure: return table items = [] for row in table.rows: - found = cells(row, 10) - if isinstance(found, Failure): - return found - id_, release, _, tagline, *_ = found - if not re.fullmatch(r"[0-9]+", id_) or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release): - return Failure(f"a todo.md row has no whole-number ID or no semver release: {row}") - major, minor, patch = (int(part) for part in release.split(".")) - items.append(PlanItem(int(id_), (major, minor, patch), tagline)) + item = parse_row(row) + if isinstance(item, Failure): + return item + items.append(item) return items -def scoring_run_due(before: list[PlanItem], after: list[PlanItem], ships: list[int], landed: bool) -> list[str]: +def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str]: """Why the chunk takes a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release before names and landed holds.""" plan = {item.id: item for item in before + after} shipped = [plan[id_] for id_ in ships] diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index a711d06b..c7c4194d 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -4,12 +4,9 @@ import re from failure import Failure DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") -FIRST_SEATS = ("Mid A", "Inherited architect") -SPLIT_SEATS = ("Maintainability senior", "Junior A") SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", "Inherited architect") SEAT_LINE = re.compile(r"^(Junior A|Mid A|Maintainability senior|Inherited architect): (.+)$") SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS)) -VOTES = ("better", "same", "worse") @dataclasses.dataclass(frozen=True) @@ -45,26 +42,6 @@ def report(text: str) -> Report | Failure: return Report(lines[0].strip(), seats) -def votes(seats: list[Seat]) -> dict[str, str] | Failure: - """Each seat's vote as it counts: a better or worse vote naming no `path:line` place counts as same.""" - names = [seat.name for seat in seats] - if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)): - return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}") - if unknown := [seat for seat in seats if seat.said not in VOTES]: - return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse") - return {seat.name: seat.said if seat.said == "same" or any(re.search(r"`[^`\s]*:\d+`", place) for place in seat.places) else "same" for seat in seats} - - -def ruling(counted: list[str]) -> str | None: - """The vote that leads each other vote by two or more, else same; None when only the first two seats voted and they differ, so two more must vote.""" - if len(counted) == 2 and counted[0] != counted[1]: - return None - for vote in VOTES: - if all(counted.count(vote) >= counted.count(other) + 2 for other in VOTES if other != vote): - return vote - return "same" - - def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure: """Each seat's five scores as written, in DIMENSIONS' order.""" if [seat.name for seat in seats] != list(SCORING_SEATS): diff --git a/bin/rank_todo.py b/bin/rank_todo.py index c41af4fe..b63ed716 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -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) diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 648e5399..07c31733 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -9,11 +9,12 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from larv_review.history import appended, entries, entry_text, Place, scoring_runs +from larv_review.history import appended, entries, Place, ruling_entry, scoring_runs from failure import Failure -from larv_review.rules import first_ruling, HistoryChange, means, measured_commit, plan_items, PlanItem, round_counts, scoring_run_due, under_floor +from larv_review.rules import first_ruling, HistoryChange, means, measured_commit, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes from test_loop_claude_black_box import host_env -from larv_review.seats import report, ruling, scores, Seat, votes +from rank_todo import Item +from larv_review.seats import report, 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" @@ -23,8 +24,8 @@ 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.**") -> PlanItem: - return PlanItem(id_, release, tagline) +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: @@ -83,10 +84,12 @@ class Seats(unittest.TestCase): class History(unittest.TestCase): def test_reads_back_what_it_writes(self): - ruled = entry_text("2026-10-08T18:37:21Z, PR #2 at bbbbbbb, against aaaaaaa", ["Ruling: worse"], [["Seat", "Vote"], ["Mid A", "worse"]], [("Mid A, decided by:", ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), ("Inherited architect, decided by:", [])]) + 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")]) @@ -113,15 +116,15 @@ class Base(unittest.TestCase): 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", "Rescore: w"]) - self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"]), (1, 2, 0, 0)) + 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", "Rescore: w"]) + self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"]), (1, 2, 0, 0, 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.assertEqual(plan_items("# todo\n"), []) - self.assertIsInstance(plan_items(todo("| x | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), 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))] @@ -228,6 +231,7 @@ class LarvReviewTool(unittest.TestCase): self.assertEqual(ran.stdout.splitlines()[0], "Ruling: same. Votes as counted: Mid A worse, Inherited architect same, Maintainability senior worse, Junior A same.") recorded = entries(history.read_text()) self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [("abc1234", "def5678", "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): diff --git a/todo.md b/todo.md index d48f36e5..f037aeb5 100644 --- a/todo.md +++ b/todo.md @@ -24,7 +24,7 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| -| 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 | +| 85 | 0.1.0 | | **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 | -- 2.52.0 From 05efbb1d8a36ecdb256d61416d83f7af15026c0a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:18:57 +0200 Subject: [PATCH 03/15] 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 --- CHANGELOG.md | 2 +- bin/larv_review/git.py | 26 +++++++++++++----- bin/larv_review/history.py | 31 +++++++++++++++------- bin/larv_review/main.py | 50 ++++++++++++++++------------------- bin/larv_review/rules.py | 37 ++++++++++++-------------- bin/larv_review/seats.py | 15 +++++++---- bin/test_larv_review.py | 49 +++++++++++++++++++++++++++------- docs/comprehension-history.md | 30 +++++++++++++++++++++ skills/larv-review/SKILL.md | 12 ++++----- todo.md | 5 ---- 10 files changed, 168 insertions(+), 89 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6be4974c..9e28d2a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +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 ...`), 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 left with no plan item is due a scoring run however its items left, moved to another release included. +- 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 ...`), 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 left with no plan item is due a scoring run however its items left, moved to another release included. 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. diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 960072b5..841bf793 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,7 +1,9 @@ +import re import subprocess +import sys from failure import Failure -from larv_review.rules import HistoryChange +from larv_review.history import HistoryChange HISTORY = "docs/comprehension-history.md" @@ -26,20 +28,32 @@ def default_branch() -> str | Failure: return remotes if "origin" in remotes.split(): if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure): - return fetched + print(f"reading origin as last fetched: {fetched.reason}", file=sys.stderr) default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD") - if isinstance(default, Failure): - return Failure(f"origin names no default branch; set it with `git remote set-head origin --auto`: {default.reason}") - return default.strip() + return default.strip() if not isinstance(default, Failure) else origin_head() for branch in ("main", "master"): if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure): return branch 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") + + +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 isinstance(git("rev-parse", "--quiet", "--verify", f"{revision}^{{commit}}"), Failure): + if not commit_exists(revision): return "" listed = git("ls-tree", "--name-only", revision, "--", path) if isinstance(listed, Failure): diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index 92ae74a5..af9cdf8d 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -3,17 +3,19 @@ import os import re import time -from larv_review.seats import DIMENSIONS, Seat +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}[^,]*, ") DECIDED_BY = "decided by" HARDEST_FIRST = "hardest first" -WOULD_RESTRUCTURE_FIRST = "would restructure first" HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$") -RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M) -SEAT_PLACES = re.compile(rf"^.+, ({DECIDED_BY}|{HARDEST_FIRST}|{WOULD_RESTRUCTURE_FIRST}):$") # `path:line` or `:line`, then the unit's name where one follows. PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?") +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" @@ -35,6 +37,14 @@ class Entry: places: list[Place] +@dataclasses.dataclass(frozen=True) +class HistoryChange: + """A merged change on the default branch that touched the history, and the history before and after it.""" + commit: str + before: str + after: str + + @dataclasses.dataclass(frozen=True) class ScoringRun: heading: str @@ -98,9 +108,12 @@ def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list return found, dropped -def heading(at: float, read: str) -> str: - """An entry's heading: when the seats finished, in UTC, and what they read.""" - return f"{time.strftime(STAMP, time.gmtime(at))}, {read}" +def heading(at: float, read: str, paired: bool) -> re.Match[str] | Failure: + """An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read; a read that opens with its own date, as a run moved from a decision entry does, keeps it.""" + title = read if DATED.match(read) else f"{time.strftime(STAMP, time.gmtime(at))}, {read}" + if (named := HEADING.match(title)) and bool(named.group(4)) == paired: + return named + return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {read}") def appended(history: str, entry: str) -> str: @@ -116,8 +129,8 @@ def ruling_entry(title: str, seats: list[Seat], counted: dict[str, str], ruled: def scoring_entry(title: str, seats: list[Seat], scores: dict[str, list[str]], means: list[str]) -> str: - rows = [[seat, *values] for seat, values in scores.items()] + [["Mean", *means]] - labels = [(f"{seat.name}, {WOULD_RESTRUCTURE_FIRST if seat.name == 'Inherited architect' else HARDEST_FIRST}:", seat.places) for seat in seats] + rows = [[seat, *values] for seat, values in scores.items() if seat != MEAN] + [[MEAN, *means]] + labels = [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats if seat.name != MEAN] return entry_text(title, [], [["Seat", *DIMENSIONS], *rows], labels) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 285e5102..29a13446 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -15,7 +15,7 @@ of HEAD and the default branch. round-count prints, for each pass, the highest among this branch's commit titles opening `Answer round :`, counting commits the default branch does not hold, and marks a pass at -the cap of 3 rounds, and a name in such a title that is no pass. +the cap of {cap} rounds, and a name in such a title that is no pass. needs-scoring-run prints why the chunk shipping the given todo.md item IDs takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension @@ -43,13 +43,14 @@ appends nothing and says to add the maintainability senior's and Junior A's line ruling is the vote that leads each other vote by two or more, else same, and it appends the ruling. record-scoring takes Junior A's, Mid A's, the maintainability senior's and the inherited -architect's lines in that order, each `Navigation , Locality , Shape , Self-sufficiency -, Overall `, each score from 1 to 10 and the overall at most 1 above the seat's lowest -dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded -half up to two decimals, and prints the means and each one under the floor of 7.0. +architect's lines in that order, or a `Mean:` line alone for a run moved from a decision entry. +Each line is `Navigation , Locality , Shape , Self-sufficiency , Overall `, each +score from 1 to 10 and the overall at most 1 above the line's lowest dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded +half up to two decimals, and prints the means and each one under the floor of {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. +time and the seats file's first line, or of that line alone when it opens with a date. Each commit +the line names must be in the checkout. Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that breaks the shape above, or when git cannot start, finds no checkout or no default branch, or the @@ -60,9 +61,9 @@ import sys import time import typing -from larv_review.history import appended, HEADING, heading, ruling_entry, scoring_entry -from larv_review.rules import CAP, first_ruling, means, measured_commit, PASSES, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes -from larv_review.git import default_branch, file_at, git, HISTORY, history_changes, landed_since_release, top +from larv_review.history import appended, heading, ruling_entry, scoring_entry +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, report, scores from failure import Failure from file_writes import replace_file @@ -72,7 +73,7 @@ USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run int: if argv in (["-h"], ["--help"]): - print(__doc__.strip()) + print(__doc__.strip().format(cap=CAP, floor=FLOOR)) return 0 command, *given = argv or [""] if command in ("ruling-base", "round-count") and not given: @@ -99,19 +100,13 @@ def ruling_base(default: str) -> Failure | None: changes = history_changes(default) if isinstance(changes, Failure): return changes - if found := measured_commit(changes): - print(f"{found}\nThe newest merged change on {default} that adds a scoring run to {HISTORY}, or whose last added paired ruling is better.") - return None history = file_at(default, HISTORY) if isinstance(history, Failure): return history - if (first := first_ruling(history)) and first.against: - print(f"{first.against}\nNo merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names.") - return None merge_base = git("merge-base", "HEAD", default) if isinstance(merge_base, Failure): return merge_base - print(f"{merge_base.strip()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.") + print("\n".join(base(changes, history, merge_base.strip(), default))) return None @@ -133,22 +128,20 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: return before try: after = pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8") - except FileNotFoundError: - after = "" except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read todo.md: {failure}") planned = plan_items(before) if isinstance(planned, Failure): - return planned + return Failure(f"{default}'s todo.md: {planned.reason}") chunk = plan_items(after) if isinstance(chunk, Failure): - return chunk - if unknown := sorted(set(ids) - {item.id for item in planned + chunk}): - return Failure(f"neither {default}'s todo.md nor the checkout's holds item {', '.join(map(str, unknown))}") + 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 @@ -160,9 +153,12 @@ def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: return Failure(f"could not read {seats_file}: {failure}") if isinstance(given, Failure): return given - title = heading(time.time(), given.read) - if not (named := HEADING.match(title)) or bool(named.group(4)) != paired: - return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {given.read}") + named = heading(time.time(), given.read, paired) + if isinstance(named, Failure): + return named + title = named.group(0) + if unknown := [commit for commit in named.group(3, 4) if commit and not commit_exists(commit)]: + return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout") if paired: counted = votes(given.seats) if isinstance(counted, Failure): @@ -179,7 +175,7 @@ def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: return found mean = means(found) under = under_floor(mean) - print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, mean))}. {'Under the floor of 7.0: ' + ', '.join(under) if under else 'None under the floor of 7.0'}.") + 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])) diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index e80e4fcd..04fd2bc9 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -1,29 +1,18 @@ -import dataclasses import decimal import re -from larv_review.seats import DIMENSIONS, Seat -from larv_review.history import entries, Entry, PLACE +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 -FIRST_SEATS = ("Mid A", "Inherited architect") FLOOR = decimal.Decimal("7.0") PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose") -ROUND = re.compile(r"^Answer (.+) round ([0-9]+):") -SPLIT_SEATS = ("Maintainability senior", "Junior A") +ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):") VOTES = ("better", "same", "worse") -@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 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] @@ -86,12 +75,18 @@ def first_ruling(history: str) -> Entry | None: return rulings[0] if rulings else None +def base(changes: list[HistoryChange], history: str, merge_base: str, default: str) -> tuple[str, str]: + """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names, else the merge base of HEAD and the default branch. history is the default branch's.""" + if found := measured_commit(changes): + return found, f"The newest merged change on {default} that adds a scoring run to the history, or whose last added paired ruling is better." + if (first := first_ruling(history)) and first.against: + return first.against, f"No merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names." + return merge_base, f"No merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}." + + def plan_items(todo: str) -> list[Item] | Failure: - """Each row of a todo.md's items table, read as `rank_todo.py` reads it; a plan with no table has no items.""" - lines = todo.splitlines() - if ITEMS_HEADER not in lines: - return [] - table = table_rows(lines, ITEMS_HEADER) + """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 = [] @@ -103,9 +98,11 @@ def plan_items(todo: str) -> list[Item] | Failure: return items -def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str]: +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 the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release before names and landed holds.""" plan = {item.id: item for item in before + after} + 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()] left = {item.release for item in after if item.id not in ships} diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index c7c4194d..a1db8990 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -3,10 +3,15 @@ import re from failure import Failure +ARCHITECT = "Inherited architect" DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") -SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", "Inherited architect") -SEAT_LINE = re.compile(r"^(Junior A|Mid A|Maintainability senior|Inherited architect): (.+)$") +FIRST_SEATS = ("Mid A", ARCHITECT) +# A scoring run moved from a `comprehension floor:` decision entry kept only the seats' means. +MEAN = "Mean" SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS)) +SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", ARCHITECT) +SEAT_LINE = re.compile(rf"^({'|'.join((*SCORING_SEATS, MEAN))}): (.+)$") +SPLIT_SEATS = ("Maintainability senior", "Junior A") @dataclasses.dataclass(frozen=True) @@ -43,9 +48,9 @@ def report(text: str) -> Report | Failure: def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure: - """Each seat's five scores as written, in DIMENSIONS' order.""" - if [seat.name for seat in seats] != list(SCORING_SEATS): - return Failure(f"a scoring run's seats are {', '.join(SCORING_SEATS)}, in that order; the file has {', '.join(seat.name for seat in seats) or 'none'}") + """Each seat's five scores as written, in DIMENSIONS' order: the four seats', or the Mean line's alone.""" + if [seat.name for seat in seats] not in (list(SCORING_SEATS), [MEAN]): + 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: if not (written := SCORES.fullmatch(seat.said)): diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 07c31733..19d7c98d 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -9,9 +9,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from larv_review.history import appended, entries, Place, ruling_entry, scoring_runs +from larv_review.history import appended, entries, HistoryChange, Place, ruling_entry, scoring_runs +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 larv_review.rules import first_ruling, HistoryChange, means, measured_commit, plan_items, round_counts, ruling, scoring_run_due, under_floor, votes from test_loop_claude_black_box import host_env from rank_todo import Item from larv_review.seats import report, scores, Seat @@ -108,6 +108,12 @@ class Base(unittest.TestCase): self.assertEqual(measured_commit([worse_last, older]), "old") self.assertIsNone(measured_commit([same])) + def test_falls_back_to_the_first_rulings_base_then_to_the_merge_base(self): + ruled = paired("2026-10-08T13:00:00Z", "worse") + self.assertEqual(base([HistoryChange("c", "", ruled)], ruled, "m", "main")[0], "aaaaaaa") + self.assertEqual(base([], "", "m", "main")[0], "m") + self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "m", "main")[0], "c") + 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") @@ -116,19 +122,20 @@ class Base(unittest.TestCase): 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", "Rescore: w"]) - self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"]), (1, 2, 0, 0, 1)) + 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.assertEqual(plan_items("# todo\n"), []) + 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))] @@ -163,6 +170,7 @@ class LarvReviewTool(unittest.TestCase): 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 @@ -213,7 +221,7 @@ class LarvReviewTool(unittest.TestCase): def test_records_a_ruling_once_four_seats_settle_a_split(self): lines = """\ - PR #2 at abc1234, against def5678 + PR #2 at {start}, against {start} Mid A: worse @@ -221,6 +229,7 @@ class LarvReviewTool(unittest.TestCase): 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.")) @@ -230,14 +239,14 @@ class LarvReviewTool(unittest.TestCase): 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.") recorded = entries(history.read_text()) - self.assertEqual([(entry.commit, entry.against, entry.ruling) for entry in recorded], [("abc1234", "def5678", "same")]) + 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("PR #2 at abc1234\n" + seats)) + 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() @@ -245,10 +254,30 @@ class LarvReviewTool(unittest.TestCase): self.assertIn("Inherited architect, would restructure first:", text) self.assertEqual([run.places for run in scoring_runs(text)], [[Place("bin/a.py", "f")] * 4]) - def test_refuses_a_ruling_file_that_names_no_base(self): - ran = self.run_tool("record-ruling", self.seats_file("PR #2 at abc1234\n\nMid A: same\n\nInherited architect: same\n")) + 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 ", 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_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__": diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index ee87e816..0fd6b682 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -422,3 +422,33 @@ 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 diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 09d565c1..e0c081a7 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A pass is one kind of review, a row of the table, named by its first column. Its | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk, one round | -`~/.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; `larv-review --help` states each rule. On exit 1, repair what its message names and run it again. +`~/.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. A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. @@ -57,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 round : โ€ฆ`, `` 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. `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. +- **Count.** Close each round with one commit that holds the round's fixes and is titled `Answer round : โ€ฆ`, `` 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 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. @@ -92,12 +92,12 @@ 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, which `larv-review ruling-base` prints. +- **Base.** The last measured commit, which `~/.claude/bin/larv-review ruling-base` prints. - **Head.** Before each ruling, merge `origin/` 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. Write what they read and their replies into a seats file in your scratchpad, in the shape `larv-review --help` shows, and run `larv-review record-ruling `. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. +- **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 `. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. - **Ruling.** The `Ruling:` line it prints, which it appends to the history. -**Scoring run**, when `larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `larv-review record-scoring `, which appends the run to the history and prints the four seats' means. +**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `, which appends the run to the history and prints the four seats' means. The chunk does not merge while either holds: @@ -113,7 +113,7 @@ Two files of the project keep the records: - **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; nothing edits them. 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: run `~/.claude/bin/larv-review record-scoring` on a seats file whose first line is the date or time the entry gives, then what it names the run by and the commit, the one it names or else the one that wrote those scores into the entry, and whose one seat line is `Mean:` followed by the five scores. The rest of the entry stays. 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`). diff --git a/todo.md b/todo.md index f037aeb5..47261aa8 100644 --- a/todo.md +++ b/todo.md @@ -24,7 +24,6 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| -| 85 | 0.1.0 | | **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 | @@ -53,10 +52,6 @@ ## Details -### 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: 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. -- 2.52.0 From 9c2f982741f3c061af242cab5b4b4eda6da5e9f7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:24:48 +0200 Subject: [PATCH 04/15] 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 --- bin/larv_review/git.py | 18 ++++--- bin/larv_review/history.py | 10 ++-- bin/larv_review/main.py | 99 ++++++++++++++++++++++++-------------- bin/larv_review/rules.py | 6 +-- bin/larv_review/seats.py | 10 ++-- bin/test_larv_review.py | 22 +++++++-- 6 files changed, 108 insertions(+), 57 deletions(-) diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 841bf793..93783a1c 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -1,6 +1,5 @@ import re import subprocess -import sys from failure import Failure from larv_review.history import HistoryChange @@ -21,19 +20,22 @@ def top() -> str | Failure: return found if isinstance(found, Failure) else found.strip() -def default_branch() -> str | Failure: - """The default branch's ref: `origin/` after a fetch, with that remote, else the local main or master.""" +def default_branch(fetched: bool) -> tuple[str, str | None] | Failure: + """The default branch's ref, `origin/` after a fetch with that remote, else the local main or master, and a note for stderr. Unless fetched, 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(): - if isinstance(fetched := git("fetch", "--quiet", "origin"), Failure): - print(f"reading origin as last fetched: {fetched.reason}", file=sys.stderr) + fetch = git("fetch", "--quiet", "origin") + if isinstance(fetch, Failure) and fetched: + 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") - return default.strip() if not isinstance(default, Failure) else 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 + return branch, None return Failure("no origin remote, and no main or master branch to take as the default branch") @@ -44,7 +46,7 @@ def origin_head() -> str | 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") + return Failure("origin names no default branch; set it with `git remote set-head origin --auto`") def commit_exists(commit: str) -> bool: diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index af9cdf8d..2695686a 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -7,7 +7,7 @@ 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}[^,]*, ") +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}))?$") @@ -108,9 +108,11 @@ def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list return found, dropped -def heading(at: float, read: str, paired: bool) -> re.Match[str] | Failure: - """An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read; a read that opens with its own date, as a run moved from a decision entry does, keeps it.""" - title = read if DATED.match(read) else f"{time.strftime(STAMP, time.gmtime(at))}, {read}" +def heading(at: float, read: str, paired: bool, moved: bool) -> re.Match[str] | 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 != bool(DATED.match(read)): + return Failure(f"only a seats file holding a {MEAN} line alone opens with a date or UTC time, then `, `: {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 named return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {read}") diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 29a13446..1b441050 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -64,8 +64,9 @@ import typing from larv_review.history import appended, heading, ruling_entry, scoring_entry 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, report, scores +from larv_review.seats import DIMENSIONS, MEAN, Report, report, 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 ... | record-ruling | record-scoring " @@ -76,12 +77,16 @@ def main(argv: list[str]) -> int: print(__doc__.strip().format(cap=CAP, floor=FLOOR)) return 0 command, *given = argv or [""] - if command in ("ruling-base", "round-count") and not given: - done = with_default_branch(ruling_base if command == "ruling-base" else round_count) + if command == "ruling-base" and not given: + done = with_default_branch(ruling_base, fetched=True) + elif command == "round-count" and not given: + done = with_default_branch(round_count, fetched=False) elif command == "needs-scoring-run" and given and all(id_.isdigit() for id_ in given): - done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given])) - elif command in ("record-ruling", "record-scoring") and len(given) == 1: - done = record(pathlib.Path(given[0]), command == "record-ruling") + done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), fetched=True) + 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])) else: print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr) return 1 @@ -91,9 +96,15 @@ def main(argv: list[str]) -> int: return 0 -def with_default_branch(command: typing.Callable[[str], Failure | None]) -> Failure | None: - default = default_branch() - return default if isinstance(default, Failure) else command(default) +def with_default_branch(command: typing.Callable[[str], Failure | None], fetched: bool) -> Failure | None: + """fetched: whether the command needs origin as it is now, or may read it as last fetched.""" + default = default_branch(fetched) + 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: @@ -103,10 +114,13 @@ def ruling_base(default: str) -> Failure | None: history = file_at(default, HISTORY) if isinstance(history, Failure): return history + if found := base(changes, history, default): + print("\n".join(found)) + return None merge_base = git("merge-base", "HEAD", default) if isinstance(merge_base, Failure): return merge_base - print("\n".join(base(changes, history, merge_base.strip(), default))) + print(f"{merge_base.strip()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.") return None @@ -130,7 +144,8 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: 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}") - planned = plan_items(before) + # A plan a chunk is reshaping into one table has none yet on the default branch. + 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) @@ -146,30 +161,28 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: return None -def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: - try: - given = report(seats_file.read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"could not read {seats_file}: {failure}") - if isinstance(given, Failure): - return given - named = heading(time.time(), given.read, paired) - if isinstance(named, Failure): - return named - title = named.group(0) - if unknown := [commit for commit in named.group(3, 4) if commit and not commit_exists(commit)]: - return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout") - if paired: - counted = votes(given.seats) - if isinstance(counted, Failure): - return counted - tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) - ruled = ruling(list(counted.values())) - if ruled is None: - print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") - return None - print(f"Ruling: {ruled}. Votes as counted: {tally}.") - return append(ruling_entry(title, given.seats, counted, ruled)) +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} {vote}" for seat, vote in counted.items()) + ruled = ruling(list(counted.values())) + if ruled is None: + print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the seats file, and run this again.") + return None + print(f"Ruling: {ruled}. Votes as counted: {tally}.") + return append(ruling_entry(title, given.seats, counted, ruled)) + + +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 isinstance(found, Failure): return found @@ -179,6 +192,22 @@ def record(seats_file: pathlib.Path, paired: bool) -> Failure | None: 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, [seat.name for seat in given.seats] == [MEAN]) + if isinstance(named, Failure): + return named + if unknown := [commit for commit in named.group(3, 4) 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.group(0), given + + def append(entry: str) -> Failure | None: checkout = top() if isinstance(checkout, Failure): diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index 04fd2bc9..bfdc6ea2 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -75,13 +75,13 @@ def first_ruling(history: str) -> Entry | None: return rulings[0] if rulings else None -def base(changes: list[HistoryChange], history: str, merge_base: str, default: str) -> tuple[str, str]: - """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names, else the merge base of HEAD and the default branch. history is the default branch's.""" +def base(changes: list[HistoryChange], history: str, default: str) -> tuple[str, str] | None: + """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names; None when neither exists, so the base is the merge base of HEAD and the default branch. history is the default branch's.""" if found := measured_commit(changes): return found, f"The newest merged change on {default} that adds a scoring run to the history, or whose last added paired ruling is better." if (first := first_ruling(history)) and first.against: return first.against, f"No merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names." - return merge_base, f"No merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}." + return None def plan_items(todo: str) -> list[Item] | Failure: diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index a1db8990..af8238a3 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -5,13 +5,17 @@ from failure import Failure ARCHITECT = "Inherited architect" DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall") -FIRST_SEATS = ("Mid A", ARCHITECT) +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)) -SCORING_SEATS = ("Junior A", "Mid A", "Maintainability senior", ARCHITECT) +SENIOR = "Maintainability senior" + +FIRST_SEATS = (MID, ARCHITECT) +SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT) SEAT_LINE = re.compile(rf"^({'|'.join((*SCORING_SEATS, MEAN))}): (.+)$") -SPLIT_SEATS = ("Maintainability senior", "Junior A") +SPLIT_SEATS = (SENIOR, JUNIOR) @dataclasses.dataclass(frozen=True) diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 19d7c98d..fbb897b0 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -108,11 +108,11 @@ class Base(unittest.TestCase): self.assertEqual(measured_commit([worse_last, older]), "old") self.assertIsNone(measured_commit([same])) - def test_falls_back_to_the_first_rulings_base_then_to_the_merge_base(self): + 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, "m", "main")[0], "aaaaaaa") - self.assertEqual(base([], "", "m", "main")[0], "m") - self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "m", "main")[0], "c") + self.assertEqual(base([HistoryChange("c", "", ruled)], ruled, "main"), ("aaaaaaa", "No merged change on main adds a scoring run or a better ruling; the base its first paired ruling names.")) + self.assertIsNone(base([], "", "main")) + self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "main")[0], "c") 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")) @@ -269,6 +269,20 @@ class LarvReviewTool(unittest.TestCase): 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("the 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")) -- 2.52.0 From fb764a754937482c93e333e5a34a56ede0b5591c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:24:52 +0200 Subject: [PATCH 05/15] Answer security round 1: no finding -- 2.52.0 From e2cb4a26f8149259e6097346307d8d30b7d317c1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:26:30 +0200 Subject: [PATCH 06/15] Answer architecture round 3: name the fetch flag stale_ok, and say in --help which commands exit 1 when origin cannot be fetched --- bin/larv_review/git.py | 6 +++--- bin/larv_review/main.py | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 93783a1c..031e3c0a 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -20,14 +20,14 @@ def top() -> str | Failure: return found if isinstance(found, Failure) else found.strip() -def default_branch(fetched: bool) -> tuple[str, str | None] | Failure: - """The default branch's ref, `origin/` after a fetch with that remote, else the local main or master, and a note for stderr. Unless fetched, a failed fetch reads origin as last fetched, and the note says so.""" +def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure: + """The default branch's ref, `origin/` 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 fetched: + 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") diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 1b441050..4a35adb0 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -4,7 +4,8 @@ usage: larv-review ruling-base | round-count | needs-scoring-run ... | Run it inside a project checkout or one of its worktrees. ruling-base, round-count and needs-scoring-run first fetch origin, when the checkout has that remote, and take origin's default -branch, or else the local main or master, as the default branch. The history is +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 how it was found: the default @@ -53,8 +54,8 @@ time and the seats file's first line, or of that line alone when it opens with a the line names must be in the checkout. Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that -breaks the shape above, or when git cannot start, finds no checkout or no default branch, or the -history or todo.md cannot be read or written. +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 sys @@ -78,11 +79,11 @@ def main(argv: list[str]) -> int: return 0 command, *given = argv or [""] if command == "ruling-base" and not given: - done = with_default_branch(ruling_base, fetched=True) + done = with_default_branch(ruling_base, stale_ok=False) elif command == "round-count" and not given: - done = with_default_branch(round_count, fetched=False) + done = with_default_branch(round_count, stale_ok=True) elif command == "needs-scoring-run" and given and all(id_.isdigit() for id_ in given): - done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), fetched=True) + 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: @@ -96,9 +97,8 @@ def main(argv: list[str]) -> int: return 0 -def with_default_branch(command: typing.Callable[[str], Failure | None], fetched: bool) -> Failure | None: - """fetched: whether the command needs origin as it is now, or may read it as last fetched.""" - default = default_branch(fetched) +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 -- 2.52.0 From 56ac92963445e80cb96eddc2e5457ad329fcfa6e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:32:19 +0200 Subject: [PATCH 07/15] 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 --- bin/larv_review/git.py | 8 +++++++- bin/larv_review/history.py | 12 +++++++++--- bin/larv_review/main.py | 39 ++++++++++++++++++++++++------------- bin/larv_review/rules.py | 6 +++++- bin/larv_review/seats.py | 5 +++-- bin/test_larv_review.py | 9 ++++++++- skills/larv-review/SKILL.md | 4 ++-- 7 files changed, 59 insertions(+), 24 deletions(-) diff --git a/bin/larv_review/git.py b/bin/larv_review/git.py index 031e3c0a..5c4d0bb5 100644 --- a/bin/larv_review/git.py +++ b/bin/larv_review/git.py @@ -65,6 +65,11 @@ def file_at(revision: str, path: str) -> str | Failure: 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 @@ -82,7 +87,8 @@ def history_changes(default: str) -> list[HistoryChange] | Failure: 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.""" - tags = git("tag", "--list", "v*", "--merged", default, "--sort=-v:refname") + # 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] diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index 2695686a..ff2a3293 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -110,8 +110,10 @@ def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list def heading(at: float, read: str, paired: bool, moved: bool) -> re.Match[str] | 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 != bool(DATED.match(read)): - return Failure(f"only a seats file holding a {MEAN} line alone opens with a date or UTC time, then `, `: {read}") + 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 named @@ -126,10 +128,14 @@ def appended(history: str, entry: str) -> str: 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, counted[seat.name] if counted[seat.name] == seat.said else f"same (voted {seat.said}, naming no place)"] for seat in seats] + 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: rows = [[seat, *values] for seat, values in scores.items() if seat != MEAN] + [[MEAN, *means]] labels = [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats if seat.name != MEAN] diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 4a35adb0..67379fa9 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -1,6 +1,6 @@ """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 ... | record-ruling | record-scoring +usage: larv-review ruling-base | round-count | needs-scoring-run [...] | record-ruling | record-scoring 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 @@ -18,15 +18,17 @@ round-count prints, for each pass, the highest among this branch's commit ti `Answer round :`, counting commits the default branch does not hold, and marks a pass at the cap of {cap} rounds, and a name in such a title that is no pass. -needs-scoring-run prints why the chunk shipping the given todo.md item IDs takes a scoring run, or -`No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension +needs-scoring-run prints why the chunk shipping the given todo.md item IDs, none for a chunk that +ships no item, takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension floor, or when a release the default branch's todo.md names has no item left in the checkout's todo.md, less the items shipped, and work has landed towards it: the chunk ships one of its items, or it is the earliest release the default branch's todo.md names and the default branch has a commit after its newest v* tag, or has no such tag. record-ruling and record-scoring read a seats file: a first line naming what the seats read, then -each seat's line, each followed by its places, one `- ` bullet each, as the history writes them: +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 @@ -39,30 +41,33 @@ each seat's line, each followed by its places, one `- ` bullet each, as the hist - `bin/x.py:12` `run`: ... record-ruling takes Mid A's and the inherited architect's votes, better, same or worse; a better or -worse vote naming no `path:line` place counts as same. When the two counted votes differ, it -appends nothing and says to add the maintainability senior's and Junior A's lines. Otherwise the -ruling is the vote that leads each other vote by two or more, else same, and it appends the ruling. +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 , Locality , Shape , Self-sufficiency , Overall `, each -score from 1 to 10 and the overall at most 1 above the line's lowest dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded -half up to two decimals, and prints the means and each one under the floor of {floor}. +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, or of that line alone when it opens with a date. Each commit -the line names must be in the checkout. +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 +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, scores @@ -70,7 +75,7 @@ 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 ... | record-ruling | record-scoring " +USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [...] | record-ruling | record-scoring " def main(argv: list[str]) -> int: @@ -82,12 +87,18 @@ def main(argv: list[str]) -> int: 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 given and all(id_.isdigit() for id_ in given): + 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 @@ -169,7 +180,7 @@ def record_ruling(seats_file: pathlib.Path) -> Failure | None: counted = votes(given.seats) if isinstance(counted, Failure): return counted - tally = ", ".join(f"{seat} {vote}" for seat, vote in counted.items()) + 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.") diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index bfdc6ea2..86423c95 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -20,7 +20,11 @@ def votes(seats: list[Seat]) -> dict[str, str] | Failure: return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}") if unknown := [seat for seat in seats if seat.said not in VOTES]: return Failure(f"{unknown[0].name}'s vote {unknown[0].said!r} is not better, same or worse") - return {seat.name: seat.said if names_a_place(seat) else "same" for seat in seats} + 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: diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index af8238a3..bbda295b 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -1,4 +1,5 @@ import dataclasses +import decimal import re from failure import Failure @@ -47,7 +48,7 @@ def report(text: str) -> Report | Failure: elif seats and seats[-1].places and line.startswith(" "): seats[-1].places[-1] += " " + line.strip() else: - return Failure(f"the seats file has a line that is neither a seat's line nor one of its places: {line}") + return Failure(f"the seats file has a line that is neither a seat's line, opening with one of {', '.join((*SCORING_SEATS, MEAN))} and a colon, nor one of its places: {line}") return Report(lines[0].strip(), seats) @@ -59,7 +60,7 @@ def scores(seats: list[Seat]) -> dict[str, list[str]] | Failure: for seat in seats: if not (written := SCORES.fullmatch(seat.said)): return Failure(f"{seat.name}'s line is not {', '.join(name + ' ' for name in DIMENSIONS)}: {seat.said}") - values = [float(value) for value in written.groups()] + values = [decimal.Decimal(value) for value in written.groups()] if not all(1 <= value <= 10 for value in values): return Failure(f"{seat.name}'s scores are not each from 1 to 10: {seat.said}") if values[-1] > min(values[:-1]) + 1: diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index fbb897b0..8e6149b3 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -47,6 +47,10 @@ class Seats(unittest.TestCase): 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) @@ -74,6 +78,7 @@ class Seats(unittest.TestCase): 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(scores([Seat("Mean", "Navigation 7.38, Locality 7.38, Shape 8, Self-sufficiency 8, Overall 8.38", [])])["Mean"][-1], "8.38") def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self): found = means({"a": ["7.5", "6.5", "7", "7", "7"], "b": ["7.5", "7", "7", "6.5", "7"], "c": ["7", "6.5", "7", "6.5", "6.5"], "d": ["7.5", "6.5", "7", "6.5", "7"]}) @@ -218,6 +223,8 @@ class LarvReviewTool(unittest.TestCase): 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 = """\ @@ -237,7 +244,7 @@ class LarvReviewTool(unittest.TestCase): 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.") + 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) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index e0c081a7..8dda2a05 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A pass is one kind of review, a row of the table, named by its first column. Its | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk, one round | -`~/.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. +`~/.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. A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. @@ -97,7 +97,7 @@ Then the comprehension check: simulated readers, launched per `~/.claude/skills/ - **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 `. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. - **Ruling.** The `Ruling:` line it prints, which it appends to the history. -**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `, which appends the run to the history and prints the four seats' means. +**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `, which appends the run to the history and prints the four seats' means. The chunk does not merge while either holds: -- 2.52.0 From 1c5551a145a834793b3178750d8de5362a4a6331 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:32:19 +0200 Subject: [PATCH 08/15] 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 -- 2.52.0 From acbe3ec8b53d919bb0163b9e3682a5f77d67ec6b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:33:12 +0200 Subject: [PATCH 09/15] Answer architecture round 4: no finding; the architect and principles audit confirm round 3's fixes -- 2.52.0 From 8da25d8c551452d2aa95e335636a0e67ca880f9a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:34:17 +0200 Subject: [PATCH 10/15] Answer stability round 2: no finding; also rewraps a --help paragraph for product-owner round 2 --- bin/larv_review/main.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 67379fa9..cb252cb8 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -19,11 +19,11 @@ round-count prints, for each pass, the highest among this branch's commit ti the cap of {cap} rounds, and a name in such a title that is no pass. needs-scoring-run prints why the chunk shipping the given todo.md item IDs, none for a chunk that -ships no item, takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item whose tagline names the comprehension -floor, or when a release the default branch's todo.md names has no item left in the checkout's -todo.md, less the items shipped, and work has landed towards it: the chunk ships one of its items, -or it is the earliest release the default branch's todo.md names and the default branch has a -commit after its newest v* tag, or has no such tag. +ships no item, takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item +whose tagline names the comprehension floor, or when a release the default branch's todo.md names +has no item left in the checkout's todo.md, less the items shipped, and work has landed towards +it: the chunk ships one of its items, or it is the earliest release the default branch's todo.md +names and the default branch has a commit after its newest v* tag, or has no such tag. record-ruling and record-scoring read a seats file: a first line naming what the seats read, then each seat's line, each followed by its places, one `- ` bullet each, as the history writes them. A -- 2.52.0 From 642a8bc80bf135903e26e267eae27cbff544df7a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:34:17 +0200 Subject: [PATCH 11/15] Answer product-owner round 2: rewrap the needs-scoring-run help paragraph; fix in the stability round's commit -- 2.52.0 From efed78bf5eac00475e724a8ecacda275646473b2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:37:56 +0200 Subject: [PATCH 12/15] 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 --- CHANGELOG.md | 2 +- bin/larv_review/main.py | 45 ++++++++++++++++++++----------------- bin/larv_review/rules.py | 2 +- bin/test_larv_review.py | 2 +- skills/larv-review/SKILL.md | 12 +++++----- 5 files changed, 33 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e28d2a5..db6d64d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +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 ...`), 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 left with no plan item is due a scoring run however its items left, moved to another release included. 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. +- 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 ...`), 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. diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index cb252cb8..ca329efb 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -8,27 +8,29 @@ branch, or else the local main or master, as the default branch. When the fetch 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 how it was found: the default -branch's newest merged change that adds a scoring run to the history, or whose last added paired -ruling, by its heading's time, is better; a merge commit is one change against its first parent. -With none, the base the history's first paired ruling names; with no ruling either, the merge base -of HEAD and the default branch. +ruling-base prints the commit a paired ruling reads against, then a line saying how it found it. +The base 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 no such change, 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, for each pass, the highest among this branch's commit titles opening -`Answer round :`, counting commits the default branch does not hold, and marks a pass at -the cap of {cap} rounds, and a name in such a title that is no pass. +round-count prints each pass's count: the highest among the titles opening +`Answer round :` 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 prints why the chunk shipping the given todo.md item IDs, none for a chunk that -ships no item, takes a scoring run, or `No scoring run due.` It is due when the chunk ships an item -whose tagline names the comprehension floor, or when a release the default branch's todo.md names -has no item left in the checkout's todo.md, less the items shipped, and work has landed towards -it: the chunk ships one of its items, or it is the earliest release the default branch's todo.md -names and the default branch has a commit after its newest v* tag, or has no such tag. +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, 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:`. +record-ruling and record-scoring read a seats file: a first line naming what the seats read, +` at `, ending `, against ` 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 @@ -54,8 +56,9 @@ names no `, against`. It appends the seats' scores and their means, rounded half 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, or of that line alone when it opens with a date. Each commit -the line names must be in the checkout. Each run appends, so record a ruling or a run once. +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 @@ -155,7 +158,7 @@ def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: 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}") - # A plan a chunk is reshaping into one table has none yet on the default branch. + # 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}") diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index 86423c95..3928c608 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -103,7 +103,7 @@ def plan_items(todo: str) -> list[Item] | Failure: 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 the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release before names and landed holds.""" + """Why the chunk takes a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release in before 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))}") diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 8e6149b3..1aaa79c0 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -279,7 +279,7 @@ class LarvReviewTool(unittest.TestCase): 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("the cap of 3 rounds", helped.stdout) + 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") diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 8dda2a05..97664cd5 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,12 +39,12 @@ A pass is one kind of review, a row of the table, named by its first column. Its | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk, one round | -`~/.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. - A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. 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. @@ -95,9 +95,9 @@ Then the comprehension check: simulated readers, launched per `~/.claude/skills/ - **Base.** The last measured commit, which `~/.claude/bin/larv-review ruling-base` prints. - **Head.** Before each ruling, merge `origin/` 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. 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 `. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again. -- **Ruling.** The `Ruling:` line it prints, which it appends to the history. +- **Ruling.** The `Ruling:` line `record-ruling` prints and appends to the history. -**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run ` prints `Scoring run due:`. Run it 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 `, which appends the run to the history and prints the four seats' means. +**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run ` 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 `, which appends the run to the history and prints the four seats' means. The chunk does not merge while either holds: @@ -110,10 +110,10 @@ 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, which `larv-review` appends; nothing edits them. 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: run `~/.claude/bin/larv-review record-scoring` on a seats file whose first line is the date or time the entry gives, then what it names the run by and the commit, the one it names or else the one that wrote those scores into the entry, and whose one seat line is `Mean:` followed by the five scores. 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 `, at `, 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. 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`). -- 2.52.0 From c1133edf390072d43fcc74bc343919612916ced5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:44:53 +0200 Subject: [PATCH 13/15] 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 --- bin/larv_review/history.py | 49 ++++++++++++----------------------- bin/larv_review/main.py | 27 ++++++++++--------- bin/larv_review/rules.py | 37 ++++++++++++++------------ bin/larv_review/seats.py | 44 ++++++++++++++++++++----------- bin/metric_bench/bench.py | 17 ++++++++++++ bin/metric_bench/main.py | 8 +++--- bin/test_larv_review.py | 18 ++++++------- bin/test_metric_bench.py | 6 ++--- docs/comprehension-history.md | 29 +++++++++++++++++++++ 9 files changed, 143 insertions(+), 92 deletions(-) diff --git a/bin/larv_review/history.py b/bin/larv_review/history.py index ff2a3293..3e497d38 100644 --- a/bin/larv_review/history.py +++ b/bin/larv_review/history.py @@ -1,5 +1,4 @@ import dataclasses -import os import re import time @@ -36,6 +35,17 @@ class Entry: 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: @@ -45,13 +55,6 @@ class HistoryChange: after: str -@dataclasses.dataclass(frozen=True) -class ScoringRun: - heading: str - commit: str - places: list[Place] - - def entries(history: str) -> list[Entry]: """Each paired ruling and scoring run in a comprehension history, in the order the file holds them; a section whose heading names no commit is left out.""" found = [] @@ -63,11 +66,6 @@ def entries(history: str) -> list[Entry]: return found -def scoring_runs(history: str) -> list[ScoringRun]: - """Each scoring run, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out.""" - return [ScoringRun(entry.heading, entry.commit, entry.places) for entry in entries(history) if entry.against is None] - - def seat_places(body: str) -> list[Place]: places = [] listing = False @@ -92,23 +90,7 @@ def bullet_places(bullet: str) -> list[Place]: return places -def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]: - """Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones.""" - found = [] - dropped = [] - before = "" - for place in places: - candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)] - nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates - if len(nearest) == 1: - before = nearest[0] - found.append(Place(before, place.name)) - else: - dropped.append(place) - return found, dropped - - -def heading(at: float, read: str, paired: bool, moved: bool) -> re.Match[str] | Failure: +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}") @@ -116,7 +98,7 @@ def heading(at: float, read: str, paired: bool, moved: bool) -> re.Match[str] | 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 named + return Heading(title, named.group(3), named.group(4)) return Failure(f"the seats file's first line is not ` at {', against ' if paired else ''}`: {read}") @@ -137,8 +119,9 @@ def vote_text(seat: Seat, counted: str) -> str: def scoring_entry(title: str, seats: list[Seat], scores: dict[str, list[str]], means: list[str]) -> str: - rows = [[seat, *values] for seat, values in scores.items() if seat != MEAN] + [[MEAN, *means]] - labels = [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats if seat.name != MEAN] + """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) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index ca329efb..bd6dc2da 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -8,10 +8,10 @@ branch, or else the local main or master, as the default branch. When the fetch 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 a line saying how it found it. -The base 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 no such change, the base is the one the history's first paired +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 among the titles opening @@ -73,7 +73,7 @@ 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, scores +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 @@ -128,13 +128,13 @@ def ruling_base(default: str) -> Failure | None: history = file_at(default, HISTORY) if isinstance(history, Failure): return history - if found := base(changes, history, default): + 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()}\nNo merged change on {default} adds a scoring run or a paired ruling; the merge base of HEAD and {default}.") + print(f"{merge_base.strip()}\nthe merge base of HEAD and {default}") return None @@ -197,10 +197,13 @@ def record_scoring(seats_file: pathlib.Path) -> Failure | None: if isinstance(read, Failure): return read title, given = read - found = scores(given.seats) + found = scores(given.seats) if given.moved_mean is None else {} if isinstance(found, Failure): return found - mean = means(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])) @@ -214,12 +217,12 @@ def read_seats(seats_file: pathlib.Path, paired: bool) -> tuple[str, Report] | F return Failure(f"could not read {seats_file}: {failure}") if isinstance(given, Failure): return given - named = heading(time.time(), given.read, paired, [seat.name for seat in given.seats] == [MEAN]) + 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.group(3, 4) if commit and not commit_exists(commit)]: + 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.group(0), given + return named.title, given def append(entry: str) -> Failure | None: diff --git a/bin/larv_review/rules.py b/bin/larv_review/rules.py index 3928c608..bce9be1f 100644 --- a/bin/larv_review/rules.py +++ b/bin/larv_review/rules.py @@ -41,9 +41,9 @@ def ruling(counted: list[str]) -> str | None: return "same" -def means(scores: dict[str, list[str]]) -> list[decimal.Decimal]: - """The seats' mean of each score, in the order each seat's scores are, rounded half up to two decimals.""" - return [mean([decimal.Decimal(score) for score in column]) for column in zip(*scores.values())] +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: @@ -68,23 +68,23 @@ def measured_commit(changes: list[HistoryChange]) -> str | None: for change in changes: held = {entry.heading for entry in entries(change.before)} added = [entry for entry in entries(change.after) if entry.heading not in held] - rulings = sorted((entry for entry in added if entry.against), key=lambda entry: entry.time) - if any(entry.against is None for entry in added) or rulings and rulings[-1].ruling == "better": + 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.against), key=lambda entry: entry.time) + 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, default: str) -> tuple[str, str] | None: - """The commit a paired ruling reads against, and how it was found: the last measured commit, else the base the history's first paired ruling names; None when neither exists, so the base is the merge base of HEAD and the default branch. history is the default branch's.""" +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, f"The newest merged change on {default} that adds a scoring run to the history, or whose last added paired ruling is better." + return found, "the last measured commit" if (first := first_ruling(history)) and first.against: - return first.against, f"No merged change on {default} adds a scoring run or a better ruling; the base its first paired ruling names." + return first.against, "the base the history's first paired ruling names" return None @@ -103,16 +103,21 @@ def plan_items(todo: str) -> list[Item] | Failure: 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 the newest release tag. A release has work landed towards it when the chunk ships one of its items, or when it is the earliest release in before and landed holds.""" + """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()] - left = {item.release for item in after if item.id not in ships} - named = {item.release for item in before} | {item.release for item in shipped} - earliest = min((item.release for item in before), default=None) - for release in sorted(named - left): - if any(item.release == release for item in shipped) or release == earliest and landed: + 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) diff --git a/bin/larv_review/seats.py b/bin/larv_review/seats.py index bbda295b..0f404dad 100644 --- a/bin/larv_review/seats.py +++ b/bin/larv_review/seats.py @@ -15,7 +15,7 @@ SENIOR = "Maintainability senior" FIRST_SEATS = (MID, ARCHITECT) SCORING_SEATS = (JUNIOR, MID, SENIOR, ARCHITECT) -SEAT_LINE = re.compile(rf"^({'|'.join((*SCORING_SEATS, MEAN))}): (.+)$") +SEAT_LINE = re.compile(rf"^({'|'.join(SCORING_SEATS)}): (.+)$") SPLIT_SEATS = (SENIOR, JUNIOR) @@ -28,9 +28,10 @@ class Seat: @dataclasses.dataclass(frozen=True) class Report: - """A seats file: what the seats read, ` at `, with `, against ` for a paired ruling, then each seat's line and its places.""" + """A seats file: what the seats read, ` at `, with `, against ` 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: @@ -38,8 +39,13 @@ def report(text: str) -> Report | Failure: if not lines: return Failure("the seats file is empty; its first line names what the seats read: at ") seats: list[Seat] = [] + moved_mean = None for line in lines[1:]: - if seat := SEAT_LINE.match(line): + 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(), [])) @@ -48,22 +54,30 @@ def report(text: str) -> Report | Failure: 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, MEAN))} and a colon, nor one of its places: {line}") - return Report(lines[0].strip(), seats) + 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: the four seats', or the Mean line's alone.""" - if [seat.name for seat in seats] not in (list(SCORING_SEATS), [MEAN]): + """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: - if not (written := SCORES.fullmatch(seat.said)): - return Failure(f"{seat.name}'s line is not {', '.join(name + ' ' for name in DIMENSIONS)}: {seat.said}") - values = [decimal.Decimal(value) for value in written.groups()] - if not all(1 <= value <= 10 for value in values): - return Failure(f"{seat.name}'s scores are not each from 1 to 10: {seat.said}") - if values[-1] > min(values[:-1]) + 1: - return Failure(f"{seat.name}'s overall exceeds their lowest dimension by more than 1; ask the seat to rescore: {seat.said}") - found[seat.name] = list(written.groups()) + 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 + ' ' 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()) diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index f39ac536..4beda4a5 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -1,6 +1,7 @@ from typing import Callable import collections import dataclasses +import os import statistics from larv_review.history import Place @@ -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 diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index 6efa65a3..6b071534 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -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 larv_review.history import resolved, scoring_runs, ScoringRun def main(argv: list[str]) -> int: @@ -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): diff --git a/bin/test_larv_review.py b/bin/test_larv_review.py index 1aaa79c0..48dc243c 100644 --- a/bin/test_larv_review.py +++ b/bin/test_larv_review.py @@ -9,12 +9,12 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from larv_review.history import appended, entries, HistoryChange, Place, ruling_entry, scoring_runs +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, scores, Seat +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" @@ -78,10 +78,10 @@ class Seats(unittest.TestCase): 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(scores([Seat("Mean", "Navigation 7.38, Locality 7.38, Shape 8, Self-sufficiency 8, Overall 8.38", [])])["Mean"][-1], "8.38") + 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({"a": ["7.5", "6.5", "7", "7", "7"], "b": ["7.5", "7", "7", "6.5", "7"], "c": ["7", "6.5", "7", "6.5", "6.5"], "d": ["7.5", "6.5", "7", "6.5", "7"]}) + 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), []) @@ -98,7 +98,7 @@ class History(unittest.TestCase): 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([run.commit for run in scoring_runs(history)], ["aaaaaaa"]) + self.assertEqual([entry.paired for entry in found], [False, True]) class Base(unittest.TestCase): @@ -115,9 +115,9 @@ class Base(unittest.TestCase): 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, "main"), ("aaaaaaa", "No merged change on main adds a scoring run or a better ruling; the base its first paired ruling names.")) - self.assertIsNone(base([], "", "main")) - self.assertEqual(base([HistoryChange("c", "", SCORING)], SCORING, "main")[0], "c") + 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")) @@ -259,7 +259,7 @@ class LarvReviewTool(unittest.TestCase): 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([run.places for run in scoring_runs(text)], [[Place("bin/a.py", "f")] * 4]) + 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")) diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index 9adbbe32..b302342b 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -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 larv_review.history 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")]) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 0fd6b682..18aa8013 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -452,3 +452,32 @@ Inherited architect, decided by: - `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 -- 2.52.0 From 28d027ffef3787849ec186a0b74e23aa29b16605 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:48:44 +0200 Subject: [PATCH 14/15] Rescore: the paired ruling at c1133ed against 12d6d75 is same, 2 votes to 2 --- docs/comprehension-history.md | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 18aa8013..16424e25 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -481,3 +481,50 @@ Inherited architect, decided by: - `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.52.0 From dd56ad8fdd70a0f26b65eff1e42d2a2608f0da77 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 01:50:13 +0200 Subject: [PATCH 15/15] Answer stability round 3: no finding -- 2.52.0