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

This commit is contained in:
2026-10-09 01:18:57 +02:00
parent 53ed5150be
commit 05efbb1d8a
10 changed files with 168 additions and 89 deletions
+20 -6
View File
@@ -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):
+22 -9
View File
@@ -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 `<PR or branch> at <commit>{', against <base>' 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)
+23 -27
View File
@@ -15,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, 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 <n>, Locality <n>, Shape <n>, Self-sufficiency
<n>, Overall <n>`, each score from 1 to 10 and the overall at most 1 above the seat's lowest
dimension. A first line names no `, against`. It appends the seats' scores and their means, rounded
half up to two decimals, and prints the means and each one under the floor of 7.0.
architect's lines in that order, or a `Mean:` line alone for a run moved from a decision entry.
Each line is `Navigation <n>, Locality <n>, Shape <n>, Self-sufficiency <n>, Overall <n>`, each
score from 1 to 10 and the overall at most 1 above the line's lowest dimension. 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 <item
def main(argv: list[str]) -> 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 `<PR or branch> at <commit>{', against <base>' 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]))
+17 -20
View File
@@ -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}
+10 -5
View File
@@ -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)):