359 lines
21 KiB
Python
359 lines
21 KiB
Python
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: 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`.
|
|
|
|
usage: review-replay <pass> <model> [--omit-claude-md]
|
|
|
|
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
|
|
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
|
latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects
|
|
that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
|
|
reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD
|
|
authored by the time the round began, on the branch the reviewer started on. The clone's default
|
|
branch stands at the newest commit authored before the round's chunk began, so a diff against it
|
|
shows the chunk's change. The prompt names the clone in place of the worktree it named, which the
|
|
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
|
|
names it and why. The prompt also names a copy of the chunk's review folder in place of that
|
|
folder, holding only the reports written after the chunk began and before the round did. A replay
|
|
fails where its prompt still names the review folder, or names a file there, other than a round's
|
|
report, that the folder did not hold from the chunk's start until the round's.
|
|
|
|
It replays every round twice on the project's rung. Even that rung finds only part of its own
|
|
archived findings again, so the bar for a rung below is the mean share of those two replays, less
|
|
a margin of 10 percentage points. Rounds that either replay failed on are left out, and where
|
|
fewer than 8 remain, or the bar is zero or below, no rung is tried. It
|
|
then replays the rounds on each rung below, highest first: the project's model at each lower
|
|
effort, which the ladder leaves out, then each ladder rung down to the ladder's lowest. It stops at
|
|
the first rung that doesn't qualify. A rung qualifies where it finds as many findings as reach the
|
|
bar and misses no 🔴 that both replays on the project's rung found; a replay that failed on it
|
|
finds nothing. For
|
|
each replay, claude on the project's rung matches the report to the archived findings, and counts
|
|
a finding only where the report raises it as 🔴 or 🟡. The tool prints each rung's count, each 🔴
|
|
it missed, and the lowest rung that, like each rung above it, qualifies. That rung is the evidence
|
|
for running the pass's reviewer on it; the decision above records each run.
|
|
|
|
With --omit-claude-md it tests instead whether the pass's reviewer may start without CLAUDE.md:
|
|
docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where its replay missed no
|
|
more findings than the most an unchanged replay missed`. It replays every round four times on the
|
|
project's rung: three as archived, then once without the instruction files. The unchanged reviewer
|
|
does not find the same findings twice, so each unchanged replay is a control: the tool prints how
|
|
many findings it missed that the other two found. The replay without CLAUDE.md is held to the
|
|
findings the first two found, and passes where it missed no more than the most any unchanged replay
|
|
did. It prints how many findings each replay found, and each finding the last missed. A round that
|
|
any of the four replays failed on is left out, and where the first two share no finding the last
|
|
line says there is no evidence.
|
|
Claude Code ignores an agent's `omitClaudeMd` where the agent runs the session, as it does in a
|
|
replay, and runs no SubagentStart hook there. So the third replay turns the instruction files off
|
|
in its settings and opens the prompt with what the hook hands a reviewer, and closes it with the
|
|
header's line on the project principles.
|
|
|
|
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
|
review or match leaves its round out, except on a rung below the project's, where it finds
|
|
nothing. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived
|
|
round to replay, or a usage limit.
|
|
"""
|
|
import dataclasses
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import typing
|
|
|
|
from transcript_archive.location import archive_root
|
|
from rung_replay.command import arguments_or_exit, failed, limited_exit, projects_on
|
|
from review_replay.rounds import authored_by, comparison, lost_inputs, reviewed_path, Round, round_from, sample, stamp_seconds
|
|
from review_replay.recall import candidates, enough, needed, Recall, recall_report, Reference, RungRecall, tried
|
|
from transcript_archive.project_key import checkout_of
|
|
from claude_code.reply import claude_reply, Limited
|
|
from loop_effects.effects import Effects
|
|
from failure import Failure
|
|
from rung_replay.search import first_reply, replayed_on
|
|
from claude_code.transcript import first_timestamped_line, read_transcript
|
|
from claude_code.entries import parse_entry, structured_output
|
|
from review_rules.reviewer_context import principles_line, reviewer_context
|
|
from model_routing.ladder import project_rung, Rung
|
|
from review_rules.review_folder import REPORTS, review_folder
|
|
from review_rules.review_passes import ReviewedPass, REVIEWERS
|
|
|
|
TOOL = "review-replay"
|
|
OMIT = "--omit-claude-md"
|
|
# Starts claude without its instruction files, as `omitClaudeMd` starts a subagent.
|
|
NO_CLAUDE_MD = ["--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})]
|
|
USAGE = f"{TOOL} <pass> <model> [{OMIT}], <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
|
|
LATEST = 10
|
|
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Code:
|
|
"""Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began."""
|
|
path: str
|
|
reviewed: str
|
|
default: str
|
|
base: str
|
|
|
|
|
|
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
|
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
|
|
if isinstance(read, int):
|
|
return read
|
|
reviewed, project, without = read
|
|
rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home)
|
|
if isinstance(rounds, Failure):
|
|
return failed(TOOL, rounds.reason)
|
|
codes = codes_found(rounds, effects)
|
|
if not codes:
|
|
return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
|
chosen = sample(list(codes), LATEST)
|
|
if without:
|
|
return compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare))
|
|
|
|
def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited:
|
|
matched = findings_replayed(found, codes[found], rung, project, home, effects, False)
|
|
if isinstance(matched, Failure):
|
|
print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True)
|
|
return matched
|
|
|
|
recall = recalled(chosen, project, replay_one, f"{reviewed} rounds")
|
|
if isinstance(recall, Limited):
|
|
return limited_exit(TOOL, recall)
|
|
print(recall_report(reviewed, project, recall))
|
|
return 0
|
|
|
|
|
|
def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
|
|
"""Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify."""
|
|
runs: list[list[set[int] | Failure]] = []
|
|
for _ in range(2):
|
|
found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what)
|
|
if isinstance(found, Limited):
|
|
return found
|
|
runs.append(found)
|
|
rounds: list[Round] = []
|
|
reference: Reference = ([], [])
|
|
for one, first, second in zip(chosen, *runs):
|
|
if not isinstance(first, Failure) and not isinstance(second, Failure):
|
|
rounds.append(one)
|
|
reference[0].append(first)
|
|
reference[1].append(second)
|
|
recalls: list[RungRecall] = []
|
|
lowest = None
|
|
for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []:
|
|
on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what)
|
|
if isinstance(on_rung, Limited):
|
|
return on_rung
|
|
# A failed replay on a candidate found nothing, so it lowers that rung's count and never lifts it to what a rung needs.
|
|
one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung])
|
|
recalls.append(one)
|
|
if not one.qualifies:
|
|
break
|
|
lowest = rung
|
|
return Recall(rounds, reference, len(chosen) - len(rounds), recalls, lowest)
|
|
|
|
|
|
def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing.Callable[[Round, bool], set[int] | Failure | Limited]) -> int:
|
|
"""Replays chosen three times with CLAUDE.md and once without, as found_on(round, bare) finds, and prints the comparison of the rounds no replay failed on."""
|
|
runs: list[list[set[int] | Failure]] = []
|
|
for bare in (False, False, False, True):
|
|
def replay_one(one: Round, _: Rung, bare: bool = bare) -> set[int] | Failure | Limited:
|
|
found = found_on(one, bare)
|
|
if isinstance(found, Failure):
|
|
print(f" {one.root} {one.at} {'without' if bare else 'with'} the instruction files failed, so the round is left out: {found.reason}", file=sys.stderr, flush=True)
|
|
return found
|
|
|
|
found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {'without' if bare else 'with'} the instruction files")
|
|
if isinstance(found, Limited):
|
|
return limited_exit(TOOL, found)
|
|
runs.append(found)
|
|
# A failed replay found nothing, which would lower the bar where it had CLAUDE.md and count as misses where it had none.
|
|
kept = [(one, *found) for one, *found in zip(chosen, *runs) if not any(isinstance(each, Failure) for each in found)]
|
|
first, second, third, without = ([typing.cast(set[int], found[run]) for _, *found in kept] for run in range(4))
|
|
print(comparison(reviewed, project, [one for one, *_ in kept], (first, second, third), without, len(chosen) - len(kept)))
|
|
return 0
|
|
|
|
|
|
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
|
|
"""The pass, the project's rung of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
|
|
if argv[2:] not in ([], [OMIT]) or len(argv) < 2:
|
|
return None
|
|
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
|
project = project_rung(argv[1])
|
|
return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None
|
|
|
|
|
|
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
|
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
|
|
codes = {}
|
|
for found in rounds:
|
|
if isinstance(code := code_of(found, effects), Failure):
|
|
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
|
else:
|
|
codes[found] = code
|
|
return codes
|
|
|
|
|
|
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
|
projects = projects_on(model, home)
|
|
if isinstance(projects, Failure):
|
|
return projects
|
|
found = []
|
|
try:
|
|
for key in projects:
|
|
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
|
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
|
|
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
|
return Failure(f"could not read the archive {root}: {failure}")
|
|
return found
|
|
|
|
|
|
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
|
|
copies = sorted(chunk.glob("*.jsonl"))
|
|
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
|
if not began or not began.timestamp:
|
|
return []
|
|
found = []
|
|
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
|
described = json.loads(meta.read_text(encoding="utf-8"))
|
|
if not isinstance(described, dict) or described.get("agentType") != reviewer:
|
|
continue
|
|
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
|
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began.timestamp), entries)):
|
|
found.append(one)
|
|
return found
|
|
|
|
|
|
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
|
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, and the commits authored by then.
|
|
|
|
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess shows every rung the same wrong code: the project's rung finds fewer of that round's archived findings, which lowers the bar, and the rungs below find fewer too.
|
|
"""
|
|
if not os.path.isdir(found.root):
|
|
return Failure("the project has no checkout")
|
|
path = reviewed_path(found.prompt, found.root, os.path.exists)
|
|
if path is None:
|
|
return Failure("the prompt names neither one removed worktree nor the checkout")
|
|
default = effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=found.root)
|
|
if isinstance(default, Failure):
|
|
return default
|
|
default = default.strip().removeprefix("origin/")
|
|
log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
|
main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
|
if isinstance(log, Failure):
|
|
return log
|
|
if isinstance(main_line, Failure):
|
|
return main_line
|
|
reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began)
|
|
if reviewed is None or base is None:
|
|
return Failure("no commit was authored by then")
|
|
return Code(path, reviewed, default, base)
|
|
|
|
|
|
def commit_log(listed: str) -> list[tuple[str, float]]:
|
|
return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())]
|
|
|
|
|
|
def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> set[int] | Failure | Limited:
|
|
"""The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where bare, the replay runs without CLAUDE.md, as `launch` says."""
|
|
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, bare))
|
|
if isinstance(reviewed, (Failure, Limited)):
|
|
return reviewed
|
|
return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects))
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Copies:
|
|
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
|
|
clone: str
|
|
reports: str
|
|
|
|
|
|
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
|
|
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited:
|
|
try:
|
|
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
|
|
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, bare)
|
|
except OSError as failure:
|
|
return Failure(f"could not prepare the replay: {failure}")
|
|
|
|
|
|
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited:
|
|
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports; without CLAUDE.md where bare."""
|
|
folder = pathlib.Path(review_folder(str(home), code.path))
|
|
copy_reports(found, folder, copies.reports)
|
|
prompt = redirected(found.prompt, home, folder, code.path, copies)
|
|
if isinstance(prompt, Failure):
|
|
return prompt
|
|
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
|
|
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
|
|
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
|
|
return cloned
|
|
launched = launch(found.reviewer, rung, prompt, copies.clone, home, bare)
|
|
if isinstance(launched, Failure):
|
|
return launched
|
|
reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude")
|
|
if isinstance(reply, Failure | Limited):
|
|
return reply
|
|
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
|
|
|
|
|
def launch(reviewer: str, rung: Rung, prompt: str, clone: str, home: pathlib.Path, bare: bool) -> tuple[list[str], str] | Failure:
|
|
"""claude's arguments and prompt for reviewer on rung. Where bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer."""
|
|
args = ["--agent", reviewer, *rung.flags()]
|
|
if not bare:
|
|
return args, prompt
|
|
context = reviewer_context(home)
|
|
if isinstance(context, Failure):
|
|
return context
|
|
return [*args, *NO_CLAUDE_MD], "\n".join([f"{context}\n\n{prompt}", *([principles] if (principles := principles_line(clone)) else [])])
|
|
|
|
|
|
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
|
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
|
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
|
for written in folder.iterdir() if folder.is_dir() else ():
|
|
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
|
|
shutil.copy2(written, reports)
|
|
|
|
|
|
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
|
|
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
|
|
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
|
|
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
|
|
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
|
|
if REPORTS in prompt.replace(copies.reports, ""):
|
|
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
|
|
return prompt
|
|
|
|
|
|
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
|
|
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
|
|
for command in (
|
|
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
|
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
|
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
|
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
|
):
|
|
if isinstance(ran := effects.git(*command, cwd=found.root), Failure):
|
|
return ran
|
|
return None
|
|
|
|
|
|
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
|
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
|
prompt = (
|
|
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
|
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
|
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
|
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
|
)
|
|
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
|
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
|
if isinstance(reply, Failure | Limited):
|
|
return reply
|
|
output = structured_output(reply)
|
|
numbers = output.get("found") if isinstance(output, dict) else None
|
|
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
|
return Failure(f"the match replied: {json.dumps(reply)}")
|
|
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|