"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`.""" import dataclasses import datetime import pathlib import re import typing from claude_code.entries import assistant_parts, content, part_text, parts from rung_replay.search import Replay from model_routing.ladder import Rung # A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them. FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)") # An absolute path in a prompt, up to the quote, bracket or punctuation that ends it. PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+") LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$") @dataclasses.dataclass(frozen=True) class Round: """One archived stability review of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding.""" root: str branch: str at: str began: float prompt: str findings: tuple[str, ...] @property def seconds(self) -> float: return stamp_seconds(self.at) def round_from(root: str, began: float, entries: list[dict]) -> Round | None: """The round a stability reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to.""" reports = [text for found in entries for part in assistant_parts(found) if (text := part_text(part))] first = entries[0] if entries else {} if not stamped(first) or not reports or not (findings := recorded_findings(reports[-1])): return None prompt = content(first) prompt = prompt if isinstance(prompt, str) else "".join(part_text(part) or "" for part in parts(first)) return Round(root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings)) def stamped(entry: dict) -> bool: try: return isinstance(entry.get("timestamp"), str) and bool(stamp_seconds(entry["timestamp"])) except ValueError: return False def stamp_seconds(stamp: str) -> float: return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() def recorded_findings(report_text: str) -> list[str]: findings: list[list[str]] = [] open_finding = False for line in report_text.splitlines(): if FINDING.match(line): findings.append([line]) open_finding = True elif open_finding and line.strip(): findings[-1].append(line) else: open_finding = False return ["\n".join(lines) for lines in findings] def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool]) -> str | None: """Where the reviewer read the code: the one gone directory the prompt names beside the checkout or inside it, as a removed worktree, else the checkout when the prompt names it; None when it names neither, or two gone ones.""" checkout = pathlib.PurePath(root) # A path that ends a sentence or names a line, such as /code/p/a.py:3, loses that ending. named = [LINE_OR_STOP.sub("", path) for path in PATH.findall(prompt)] gone = set() for path in map(pathlib.PurePath, named): # The path's directories from the top down, without the filesystem root; the first one gone is what a removed worktree took with it. down_the_path = [*reversed(path.parents), path][1:] first_gone = next((prefix for prefix in down_the_path if not exists(str(prefix))), None) if first_gone and (first_gone.parent == checkout.parent or checkout in first_gone.parents): gone.add(str(first_gone)) if len(gone) == 1: return gone.pop() return root if not gone and root in named else None def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None: """The newest commit in log, which lists newest first, authored at or before seconds. A rebase keeps author times, so a merged branch's commits still say what it held.""" return next((commit for commit, authored in log if authored <= seconds), None) def sample(rounds: list[Round], latest: int) -> list[Round]: """The latest rounds, in the order they ran.""" return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:] def report(model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str: total = sum(len(found_round.findings) for found_round in rounds) lines = [ f"Replayed {len(rounds)} stability rounds of {model} projects, holding {total} 🔴 and 🟡 findings.", f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.", ] for tried in replay.tried: lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {miss.case.root} {miss.case.at}: {miss.case.findings[miss.item].splitlines()[0]}" for miss in tried.missed)] if not replay.tried: lines.append("No rung tried: the reference reviewer found no finding to hold one to.") else: lowest = replay.lowest or "none below the project's rung" lines.append(f"Lowest rung that finds every finding the reference reviewer finds: {lowest}") return "\n".join(lines)