Files
claude-config/bin/larv_review/rules.py
T

197 lines
9.9 KiB
Python

import decimal
import re
from larv_review.seats import DIMENSIONS, FIRST_SEATS, Seat, SPLIT_SEATS, vote_line
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
FLOOR = decimal.Decimal("7.0")
PASSES = ("architecture", "full scan", "security", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):")
VOTES = ("better", "same", "worse")
def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure:
"""Each seat's five votes as written, in DIMENSIONS' order."""
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 overall votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}")
said = {}
for seat in seats:
line = vote_line(seat.name, seat.said)
if isinstance(line, Failure):
return line
if unnamed := [place for place in seat.places if not place_dimensions(place)]:
return Failure(f"{seat.name}'s place does not open with the dimensions it moves, each one of {', '.join(DIMENSIONS)}, then `: `: {unnamed[0]}")
said[seat.name] = line
first, second, *more = (each[-1] for each in counted(seats, said).values())
if more and first == second:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first} overall, which settles the ruling; drop the other seats' lines")
return said
def counted(seats: list[Seat], said: dict[str, list[str]]) -> dict[str, list[str]]:
"""Each seat's votes as they count: a dimension's vote counts as same unless one of the seat's `path:line` places opens with that dimension, and the overall vote unless the seat names any such place."""
return {seat.name: [vote if names_a_place(seat, name) else "same" for name, vote in zip(DIMENSIONS, said[seat.name])] for seat in seats}
def names_a_place(seat: Seat, dimension: str) -> bool:
return any(PLACE.search(place) and (dimension == DIMENSIONS[-1] or dimension in place_dimensions(place)) for place in seat.places)
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 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 fallen(counted: dict[str, list[str]]) -> list[str]:
"""Each dimension, Overall aside, that the seats rule worse by a lead of two."""
return [name for name, column in zip(DIMENSIONS[:-1], zip(*counted.values())) if ruling(list(column)) == "worse"]
def chunk_entries(default_history: str, history: str) -> list[Entry]:
"""The checkout's entries whose headings the default branch's history lacks, oldest first; entries sharing a time keep their file order."""
held = {entry.heading for entry in entries(default_history)}
return sorted((entry for entry in entries(history) if entry.heading not in held), key=lambda entry: entry.time)
def pending_fall(chunk: list[Entry]) -> list[str]:
"""The dimensions that fell in the chunk's newest entry, empty unless that entry is a paired ruling."""
return chunk[-1].fell if chunk and chunk[-1].paired else []
def uncalled(chunk: list[Entry]) -> str:
"""Why a scoring run nothing calls fails, and what to do instead."""
if chunk and not chunk[-1].paired:
return "the chunk's newest entry is already a scoring run; record a paired ruling first, or name the item IDs the chunk ships"
return "no plan item, release or fall calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them"
def standing_ratchet(chunk: list[Entry]) -> str | None:
"""The chunk's newest `Ratchet:` line, unless a paired ruling has followed it."""
for entry in reversed(chunk):
if entry.paired:
return None
if entry.ratchet:
return entry.ratchet
return None
def floor_verdict(under: list[str], reasons: list[str]) -> str:
"""Whether the means under the floor block the merge: they do on a run due for a reason besides a fall."""
if not under:
return f"None under the floor of {FLOOR}."
if reasons:
return f"Floor: {', '.join(under)} under the floor of {FLOOR} block the merge, as the chunk {' and '.join(reasons)}."
return f"Under the floor of {FLOOR}, blocking nothing, as only a fall called this run: {', '.join(under)}."
def fall_outcome(fell: list[str], found: list[decimal.Decimal]) -> tuple[str, list[str]] | None:
"""What a scoring run says of a pending fall, and the lines it records: a `Ratchet:` line when a fallen dimension's mean is under the floor."""
if not fell:
return None
if dropped := [f"{name} is {value}" for name, value in zip(DIMENSIONS, found) if name in fell and value < FLOOR]:
line = f"Ratchet: the paired ruling counts as worse, as {' and '.join(fell)} fell and {', '.join(dropped)}, under the floor of {FLOOR}."
return line, [line]
return f"The paired ruling stands: {' and '.join(fell)} fell and each stays at or above the floor of {FLOOR}.", []
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:
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} {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, and a title naming no known pass adds its name."""
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, whose last added paired ruling is better, or that adds a scoring run and whose last added paired ruling names no fall."""
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.paired), key=lambda entry: entry.time)
last = rulings[-1] if rulings else None
ruled_better = last is not None and last.ruling == "better"
scored_without_fall = any(not entry.paired for entry in added) and not (last and last.fell)
if ruled_better or scored_without_fall:
return change.commit
return None
def first_ruling(history: str) -> Entry | None:
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) -> 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, "the last measured commit"
if (first := first_ruling(history)) and first.against:
return first.against, "the base the history's first paired ruling names"
return None
def plan_items(todo: str) -> list[Item] | Failure:
"""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 = []
for row in table.rows:
item = parse_row(row)
if isinstance(item, Failure):
return item
items.append(item)
return items
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool, fell: list[str]) -> 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, landed whether the default branch holds a commit after its newest release tag, and fell what pending_fall finds in the chunk's history. 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()]
if fell:
reasons.append(f"has a paired ruling in which {' and '.join(fell)} fell")
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)