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

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