208 lines
11 KiB
Python
208 lines
11 KiB
Python
"""Replay archived stability rounds on the rungs below the project's, to find which rungs may run the stability reviewer: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`.
|
|
|
|
usage: stability-replay <model>
|
|
|
|
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
|
latest 10 archived stability rounds 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.
|
|
|
|
It first replays every round on the project's rung, the reference reviewer. Findings on record
|
|
that the reference reviewer does not raise again may rest on code or rules that have changed
|
|
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
|
|
rung below, highest first, down to the rung the lowest R + C picks, and stops at the first rung
|
|
that misses one. For each replay, claude on the project's rung matches the report to the findings
|
|
on record, and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each
|
|
finding a rung missed and the lowest rung that, like each rung above it, missed none. That rung is
|
|
the evidence for running the stability reviewer on the worker's rung whenever the worker runs at
|
|
or above it; docs/decisions.md → `routing: the stability reviewer stays on the project's rung`
|
|
records the run.
|
|
|
|
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
|
review or match 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 stability_replay.rounds import authored_by, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
|
from project_key import checkout_of
|
|
from claude_code.reply import claude_reply, Limited
|
|
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
|
|
from loop_claude.effects import Effects
|
|
from failure import Failure
|
|
from rung_replay.search import first_reply, replayed
|
|
from claude_code.transcript import first_timestamped_line, read_transcript
|
|
from claude_code.entries import parse_entry, structured_output
|
|
from model_routing.ladder import Rung
|
|
|
|
TOOL = "stability-replay"
|
|
LATEST = 10
|
|
REVIEWER = "stability-reviewer"
|
|
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:
|
|
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
|
if isinstance(anchor, int):
|
|
return anchor
|
|
rounds = archived_rounds(anchor.model, archive_root(home, env), home)
|
|
if isinstance(rounds, Failure):
|
|
return failed(TOOL, rounds.reason)
|
|
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
|
|
if not codes:
|
|
return failed(TOOL, f"no archived stability round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
|
chosen = sample(list(codes), LATEST)
|
|
# The project's rung is the reference, so the candidates start below it.
|
|
replay = replayed(chosen, anchor, down_from(anchor)[1:], lambda found, rung: findings_found(found, codes[found], rung, anchor, effects), lambda _, found: sorted(found), "stability rounds")
|
|
if isinstance(replay, Limited):
|
|
return limited_exit(TOOL, replay)
|
|
print(report(anchor.model, anchor, chosen, replay))
|
|
return 0
|
|
|
|
|
|
def archived_rounds(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(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(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 isinstance(began.get("timestamp"), str):
|
|
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(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 prompt's removed worktree, 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 costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
|
|
"""
|
|
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 = git(effects, found.root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD")
|
|
if isinstance(default, Failure):
|
|
return default
|
|
default = default.strip().removeprefix("origin/")
|
|
log = git(effects, found.root, "log", "--format=%H %at", f"refs/remotes/origin/{default}")
|
|
main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}")
|
|
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_found(found: Round, code: Code, rung: Rung, anchor: Rung, effects: Effects) -> set[int] | Limited:
|
|
"""The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them."""
|
|
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, effects))
|
|
if isinstance(reviewed, Limited):
|
|
return reviewed
|
|
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects))
|
|
if isinstance(matched, Failure):
|
|
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
|
return set()
|
|
return matched
|
|
|
|
|
|
# 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, effects: Effects) -> str | Failure | Limited:
|
|
clone = tempfile.mkdtemp(prefix="stability-replay-")
|
|
try:
|
|
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 := git(effects, found.root, *command), Failure):
|
|
return ran
|
|
args = ["--agent", REVIEWER, *rung.flags()]
|
|
reply = claude_reply(effects.claude, args, clone, found.prompt.replace(code.path, clone), "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")
|
|
finally:
|
|
shutil.rmtree(clone, ignore_errors=True)
|
|
|
|
|
|
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)}
|
|
|
|
|
|
def git(effects: Effects, cwd: str, *args: str) -> str | Failure:
|
|
try:
|
|
ran = effects.git(list(args), cwd)
|
|
except OSError as failure:
|
|
return Failure(f"git {' '.join(args)} could not start in {cwd}: {failure.strerror}")
|
|
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|