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") 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) RULED_PLACES = re.compile(rf"^.+, {DECIDED_BY}:$") SCORED_PLACES = re.compile(rf"^.+, ({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 Entry: """One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither. The places under a scoring seat's label are scored_places; a ruling recorded before PR #255 may hold them too.""" heading: str time: str commit: str against: str | None ruling: str | None ruled_places: list[Place] scored_places: list[Place] body: str @property def paired(self) -> bool: return self.against is not None @dataclasses.dataclass(frozen=True) class HistoryChange: """A merged change on the default branch that touched the history, and the history before and after it.""" commit: str before: str after: str @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 `, hardest first:` or, for the architect, `, 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) found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body, RULED_PLACES), seat_places(body, SCORED_PLACES), body)) return found def latest_places(history: str) -> str | None: """The places seats found hard from the oldest entry on the commit of the newest entry, by time, that is a scoring run or holds scoring seats' places: in it and each later entry, each ruled place opening with a dimension its seat's vote counted as worse, and every scoring seat's place. Each entry's places come under its heading, oldest first; with no such entry, it starts at the oldest entry. None when no place counts.""" found = sorted(entries(history), key=lambda entry: entry.time) scored = [index for index, entry in enumerate(found) if not entry.paired or entry.scored_places] newest_commit = found[scored[-1]].commit if scored else None start = next((index for index in scored if found[index].commit == newest_commit), 0) parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]] return "\n".join(part for part in parts if part) or None def worse_places(entry: Entry) -> list[tuple[str, list[str]]]: """Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one.""" worse = worse_votes(entry.body) return [(label, [bullet for bullet in bullets if worse.get(label.split(",")[0], set()) & set(place_dimensions(bullet.removeprefix("- ")))]) for label, bullets in labelled_bullets(entry.body, RULED_PLACES)] def placed(entry: Entry, labelled: list[tuple[str, list[str]]]) -> str: """The entry's heading, then each label with bullets and its bullets; empty when no label has any.""" text = "".join(f"\n{label}\n\n" + "".join(f"{bullet}\n" for bullet in bullets) for label, bullets in labelled if bullets) return f"## {entry.heading}\n{text}" if text else "" def worse_votes(body: str) -> dict[str, set[str]]: """Each seat's dimensions, Overall included, whose vote in the ruling's table counted as worse; `same (voted worse, …)` counted as same. The votes table comes first, so a seat's row in a later scores table is not its vote.""" return {name: {dimension for dimension, vote in zip(DIMENSIONS, cells) if vote == "worse"} for name, cells in table_rows(body).items() if len(cells) == len(DIMENSIONS)} def table_rows(body: str) -> dict[str, list[str]]: """Each table row's cells after its first, keyed by that first cell; where rows share a first cell, the first row wins. Header and Mean rows are included.""" found: dict[str, list[str]] = {} for line in body.splitlines(): if line.startswith("| "): name, *cells = [cell.strip() for cell in line.strip("|").split("|")] found.setdefault(name, cells) return found 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 seat_places(body: str, labels: re.Pattern[str]) -> list[Place]: """The places on the first line of each bullet under a seat label the pattern `labels` matches.""" return [place for _, bullets in labelled_bullets(body, labels) for bullet in bullets for place in bullet_places(bullet.splitlines()[0])] def labelled_bullets(body: str, labels: re.Pattern[str]) -> list[tuple[str, list[str]]]: """Each seat label the pattern `labels` matches, with its bullets, each with its indented continuation lines.""" found: list[tuple[str, list[str]]] = [] listing = False for line in body.splitlines(): if labels.match(line): found.append((line, [])) listing = True elif listing and line.startswith("- "): found[-1][1].append(line) elif listing and line.startswith(" ") and found[-1][1]: found[-1][1][-1] += f"\n{line}" elif not line.startswith(" "): listing = 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 ` at {', against ' 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) + " |"