Files
claude-config/bin/comprehension_history.py
T

322 lines
14 KiB
Python

import dataclasses
import decimal
import re
from failure import Failure
from markdown_text import sections
from utc_stamp import utc
ARCHITECT = "Inherited architect"
DECIDED_BY = "decided by"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
FLOOR = decimal.Decimal("7.0")
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
HISTORY = "docs/comprehension-history.md"
JUNIOR = "Junior A"
MEAN = "Mean"
MID = "Mid A"
# `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)
# A seat's label over its bullets: its name, then what the bullets are.
LABEL = re.compile(rf"^(.+), ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
SENIOR = "Maintainability senior"
TITLE = "# Comprehension history\n"
@dataclasses.dataclass(frozen=True)
class Seat:
name: str
said: str
places: list[str]
@dataclasses.dataclass(frozen=True)
class Place:
path: str
name: str | None
@dataclasses.dataclass(frozen=True)
class Listing:
"""The bullets a seat lists under one label of an entry, each with its indented continuation lines. `kind` is what the label ends in: DECIDED_BY, HARDEST_FIRST or RESTRUCTURE_FIRST."""
label: str
seat: str
kind: str
bullets: list[str]
@property
def places(self) -> list[Place]:
"""The places on the first line of each bullet."""
return [place for bullet in self.bullets for place in bullet_places(bullet.splitlines()[0])]
@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.
`votes` and `scores` hold table rows, each the cells after the first, by the first, with the header left out. `scores` is the table with a Mean row, `votes` any other: a ruling's votes, whose one cell in a ruling before PR #232 is the overall vote. A ruling before PR #255 holds both tables, and scoring seats' listings too."""
heading: str
time: str
commit: str
against: str | None
ruling: str | None
votes: dict[str, list[str]]
scores: dict[str, list[str]]
decided: list[Listing]
hardest: list[Listing]
@property
def paired(self) -> bool:
return self.against is not None
@property
def scored(self) -> bool:
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
return not self.paired or bool(self.scored_places)
@property
def ruled_places(self) -> list[Place]:
return [place for listing in self.decided for place in listing.places]
@property
def scored_places(self) -> list[Place]:
return [place for listing in self.hardest for place in listing.places]
@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 Heading:
title: str
label: str
commit: str
against: str | None
@dataclasses.dataclass(frozen=True)
class ScoringRun:
"""The four scoring seats' lines, their scores as written and the means, in DIMENSIONS' order."""
seats: list[Seat]
scores: dict[str, list[str]]
means: list[decimal.Decimal]
# A paired ruling as entry_text writes it. A scoring run's heading has no `, against`; it has no Ruling line, ends its table with a Mean row, and labels each seat's places `<seat>, hardest first:` or, for the architect, `<seat>, would restructure first:`. A ruling recorded before PR #232 has a `| Seat | Vote |` table, whose one cell is the overall vote.
#
# ## 2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75
#
# Ruling: same
#
# | Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
# |---|---|---|---|---|---|
# | Mid A | better | worse | same | same | better |
#
# Mid A, decided by:
#
# - Locality: `bin/x.py:12` `run`: three branches to hold at once
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)
tables = table_rows(body)
listed = listings(body)
found.append(Entry(
heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None,
votes={name: cells for table in tables if MEAN not in table for name, cells in table.items()},
scores={name: cells for table in tables if MEAN in table for name, cells in table.items()},
decided=[listing for listing in listed if listing.kind == DECIDED_BY],
hardest=[listing for listing in listed if listing.kind != DECIDED_BY],
))
return found
def latest_places(history: str) -> str | None:
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
They start at the first of newest_scored's entries, so a rerun of one head adds to the run before it. Where no entry counts as scoring the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
found = by_time(entries(history))
newest = newest_scored(found)
start = found.index(newest[0]) if newest else 0
parts = [placed(entry, worse_places(entry) + entry.hardest) for entry in found[start:]]
return "\n".join(part for part in parts if part) or None
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
"""The mean of the overall means of newest_scored's entries, since a rerun of one head measures it again; None where no entry counts as scoring the project."""
overalls = []
for entry in newest_scored(by_time(entries(history))):
overall = run_overall(entry)
if isinstance(overall, Failure):
return overall
overalls.append(overall)
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
def newest_scored(found: list[Entry]) -> list[Entry]:
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
scoring = [entry for entry in found if entry.scored]
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
def run_overall(run: Entry) -> decimal.Decimal | Failure:
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
try:
overall = decimal.Decimal(last_cells(run.scores).get(MEAN, ""))
except decimal.InvalidOperation:
overall = None
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
def last_cells(rows: dict[str, list[str]]) -> dict[str, str]:
"""Each row's last non-empty cell, by its first cell: a seat's overall vote in an entry's `votes`, or its overall score, or the Mean row's, in its `scores`."""
return {name: cells[-1] for name, cells in rows.items() if cells and cells[-1]}
def scoring_runs(found: list[Entry]) -> list[Entry]:
"""The scoring runs among the entries, oldest first. Unlike Entry.scored, it leaves out a ruling from before PR #255 that holds scoring seats' places."""
return [entry for entry in by_time(found) if not entry.paired]
def by_time(found: list[Entry]) -> list[Entry]:
return sorted(found, key=lambda entry: entry.time)
def worse_places(entry: Entry) -> list[Listing]:
"""Each of a ruling's decided-by listings, cut to the bullets that open with a dimension its seat's vote counted as worse; Overall counts as one."""
cut = []
for listing in entry.decided:
worse = worse_dimensions(entry.votes.get(listing.seat, []))
cut.append(dataclasses.replace(listing, bullets=[bullet for bullet in listing.bullets if worse.intersection(place_dimensions(bullet.removeprefix("- ")))]))
return cut
def placed(entry: Entry, listed: list[Listing]) -> str:
"""The entry's heading, then each listing with bullets, its label and its bullets; empty when no listing has any."""
text = "".join(f"\n{listing.label}\n\n" + "".join(f"{bullet}\n" for bullet in listing.bullets) for listing in listed if listing.bullets)
return f"## {entry.heading}\n{text}" if text else ""
def worse_dimensions(votes: list[str]) -> set[str]:
"""The dimensions, Overall included, whose vote in a seat's row of the ruling's votes counted as worse; `same (voted worse, …)` counted as same. A row without one vote per dimension, as in the older table with a single `Vote`, has none."""
return {dimension for dimension, vote in zip(DIMENSIONS, votes) if vote == "worse"} if len(votes) == len(DIMENSIONS) else set()
def table_rows(body: str) -> list[dict[str, list[str]]]:
"""Each table's rows after its header and separator, the cells after the first keyed by the first cell. A table starts at the row above a separator; `sections` has dropped the blank lines between tables."""
lines = [line for line in body.splitlines() if line.startswith("|")]
separators = [index for index, line in enumerate(lines) if line.startswith("|-")]
ends = [*(index - 1 for index in separators[1:]), len(lines)]
return [dict(row_cells(line) for line in lines[separator + 1:end]) for separator, end in zip(separators, ends)]
def row_cells(line: str) -> tuple[str, list[str]]:
"""A table row's first cell, then the cells after it."""
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
return name, cells
def place_dimensions(place: str) -> list[str]:
"""The dimensions a place opens with, as in `Locality, Shape: `path:line` ...`; empty when any name before the first `: ` is no dimension."""
named = place.partition(": ")[0].split(", ")
return named if all(name in DIMENSIONS for name in named) else []
def recorded(history: str, read: str) -> bool:
"""Whether the history holds an entry on what a seats file's first line says the seats read."""
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
def listings(body: str) -> list[Listing]:
"""Each seat label in the body, with its bullets, each with its indented continuation lines."""
found: list[Listing] = []
under_label = False
for line in body.splitlines():
if label := LABEL.match(line):
found.append(Listing(line, label.group(1), label.group(2), []))
under_label = True
elif under_label and line.startswith("- "):
found[-1].bullets.append(line)
elif under_label and line.startswith(" ") and found[-1].bullets:
found[-1].bullets[-1] += f"\n{line}"
elif not line.startswith(" "):
under_label = False
return found
def bullet_places(bullet: str) -> list[Place]:
"""A `:line` with no path is in the file named before it in the bullet."""
places = []
path = ""
for match in PLACE.finditer(bullet):
path = match.group(1) or path
if path:
places.append(Place(path, match.group(2)))
return places
def heading(at: float, read: str, paired: bool) -> Heading | Failure:
"""An entry's heading, matched by HEADING: when the seats finished, in UTC, and what they read."""
title = f"{utc(at)}, {read}"
if (named := HEADING.match(title)) and bool(named.group(4)) == paired:
return Heading(title, named.group(2), named.group(3), named.group(4))
return Failure(f"the seats file's first line is not `<PR or branch> at <commit>{', against <base>' if paired else ''}`: {read}")
def appended(history: str, entry: str) -> str:
"""The history with entry added last; an empty history gets the file's title first."""
text = history.rstrip("\n") + "\n" if history.strip() else TITLE
return f"{text}\n{entry}"
def ruling_entry(title: str, seats: list[Seat], said: dict[str, list[str]], counted: dict[str, list[str]], ruled: str) -> str:
"""A paired ruling's entry; a seat's vote that counted as same for want of a place says so."""
votes = [[seat.name, *map(vote_text, DIMENSIONS, said[seat.name], counted[seat.name])] for seat in seats]
return entry_text(title, [f"Ruling: {ruled}"], [[["Seat", *DIMENSIONS], *votes]], [(f"{seat.name}, {DECIDED_BY}:", seat.places) for seat in seats])
def vote_text(dimension: str, said: str, counted: str) -> str:
if counted == said:
return counted
return f"same (voted {said}, naming no place)" if dimension == DIMENSIONS[-1] else f"same (voted {said}, no place naming {dimension})"
def counted_vote(cell: str) -> str:
"""The vote a ruling's table cell counted as, which is its first word, as vote_text writes it."""
return cell.split()[0]
def scoring_entry(title: str, scoring: ScoringRun) -> str:
return entry_text(title, [], [scores_table(scoring)], scoring_labels(scoring.seats))
def scores_table(scoring: ScoringRun) -> list[list[str]]:
return [["Seat", *DIMENSIONS], *([seat, *values] for seat, values in scoring.scores.items()), [MEAN, *map(str, scoring.means)]]
def scoring_labels(seats: list[Seat]) -> list[tuple[str, list[str]]]:
return [(f"{seat.name}, {RESTRUCTURE_FIRST if seat.name == ARCHITECT else HARDEST_FIRST}:", seat.places) for seat in seats]
def entry_text(title: str, lines: list[str], tables: list[list[list[str]]], seats: list[tuple[str, list[str]]]) -> str:
"""The heading, any lines such as `Ruling: same`, each table, whose first row is its header, and under each seat's label its places, one bullet each."""
parts = [f"## {title}", *lines, *("\n".join([row_text(header), "|" + "---|" * len(header), *map(row_text, rows)]) for header, *rows in tables)]
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) + " |"