135 lines
8.2 KiB
Python
135 lines
8.2 KiB
Python
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report with --omit-claude-md: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
|
|
import dataclasses
|
|
import datetime
|
|
import pathlib
|
|
import re
|
|
import typing
|
|
|
|
from claude_code.entries import AssistantTurn, Entry, Text, UserText
|
|
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+)?)?[.:]?$")
|
|
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-round-1-rerun.md.
|
|
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Round:
|
|
"""One archived review by the agent reviewer 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."""
|
|
reviewer: str
|
|
root: str
|
|
branch: str
|
|
at: str
|
|
began: float
|
|
prompt: str
|
|
findings: tuple[str, ...]
|
|
|
|
@property
|
|
def seconds(self) -> float:
|
|
return stamp_seconds(self.at)
|
|
|
|
|
|
def is_red(finding: str) -> bool:
|
|
"""Whether finding, which opens with a line FINDING matches, is raised as 🔴: by the mark it opens with, whatever marks its text names."""
|
|
mark = FINDING.match(finding)
|
|
return mark is not None and mark[0].endswith("🔴")
|
|
|
|
|
|
def round_from(reviewer: str, root: str, began: float, entries: list[Entry]) -> Round | None:
|
|
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
|
reports = [part.text for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text) and part.text]
|
|
first = entries[0] if entries else Entry()
|
|
if not stamped(first) or not reports or not (findings := recorded_findings(reports[-1])):
|
|
return None
|
|
prompt = first.text if isinstance(first, UserText) else ""
|
|
return Round(reviewer, root, first.git_branch, first.timestamp, began, prompt, tuple(findings))
|
|
|
|
|
|
def stamped(entry: Entry) -> bool:
|
|
try:
|
|
return bool(entry.timestamp) 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 lost_inputs(prompt: str, reports: str, held: typing.Callable[[str], bool]) -> list[str]:
|
|
"""The files the prompt names in reports, the copy of a round's review folder, that the copy does not hold, other than round reports. A report the copy lacks is the round's own or a later one, left out on purpose; any other file it lacks, such as a branch diff written again after the round began, would leave the replay without an input the round had."""
|
|
named = [LINE_OR_STOP.sub("", path).removeprefix(reports + "/") for path in PATH.findall(prompt) if path.startswith(reports + "/")]
|
|
return sorted({name for name in named if not ROUND_REPORT.search(name) and not held(name)})
|
|
|
|
|
|
def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None:
|
|
"""The commit in log with the newest author time at or before seconds; the first in log order breaks a tie. The log lists commits newest first by when they were merged, so taking the first one authored by seconds would pick a commit authored early but merged late, such as a dependency bump, over the commits a round reviewed. A rebase keeps author times, so a merged branch's commits keep the times their author wrote them."""
|
|
return max(((commit, authored) for commit, authored in log if authored <= seconds), key=lambda listed: listed[1], default=(None, 0))[0]
|
|
|
|
|
|
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 comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str:
|
|
"""What the three replays with CLAUDE.md and the one without found in rounds. Each replay with it missed some findings the other two found: the control, the noise of an unchanged reviewer. The one without it is held to the findings the first two found, as the third is, and passes where it missed no more than the most a replay with it did. left_out counts the rounds a replay failed on, which rounds leaves out."""
|
|
first, second, third = with_it
|
|
|
|
def shared(one: list[set[int]], other: list[set[int]]) -> list[set[int]]:
|
|
return [found_by_one & found_by_other for found_by_one, found_by_other in zip(one, other)]
|
|
|
|
def missing(held: list[set[int]], run: list[set[int]]) -> list[tuple[Round, int]]:
|
|
return [(found_round, index) for found_round, held_in_round, found in zip(rounds, held, run) for index in sorted(held_in_round - found)]
|
|
|
|
def count(run: list[set[int]]) -> int:
|
|
return sum(len(found) for found in run)
|
|
|
|
both = shared(first, second)
|
|
missed = missing(both, without)
|
|
control = [len(missing(shared(one, other), run)) for run, one, other in ((first, second, third), (second, first, third), (third, first, second))]
|
|
passes = len(missed) <= max(control)
|
|
return "\n".join([
|
|
f"Replayed {len(rounds)} {reviewed} rounds of {reference.model} projects, which hold {sum(len(found_round.findings) for found_round in rounds)} 🔴 and 🟡 findings, four times on {reference}: three with CLAUDE.md, one without.",
|
|
*([f"Left out {left_out} more, which a replay failed on; stderr says why."] if left_out else []),
|
|
f"With CLAUDE.md the reviewer found {count(first)}, {count(second)} and {count(third)} of them. Each missed {control[0]}, {control[1]} and {control[2]} of the findings the other two found.",
|
|
*([f"Without CLAUDE.md it found {count(without)} of them, and missed {len(missed)} of the findings the first two found{':' if missed else '.'}"] if count(both) else [f"Without CLAUDE.md it found {count(without)} of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to."]),
|
|
*(f" {found_round.root} {found_round.at}: {found_round.findings[index].splitlines()[0]}" for found_round, index in missed),
|
|
*([f"It {'passes' if passes else 'fails'}: {len(missed)} missed is {'no more' if passes else 'more'} than the most a replay with CLAUDE.md missed, {max(control)}."] if count(both) else []),
|
|
])
|