Files
claude-config/bin/stability_replay/main.py
T

227 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.
It first replays every round on the reference reviewer, the project's rung, which the reviewer
runs on while the worker runs below it. Findings it does not find may rest on code or rules that
have changed since; either way no rung is held to them. It then replays the rest on each rung
below, highest first, down to the rung the lowest R + C picks, and stops at the first rung that
misses one. The project's rung decides, for each replay, which findings on record it reports as
🔴 or 🟡. The tool prints each finding a rung missed and the lowest rung that missed none. Such a
rung is the evidence to route the stability reviewer onto the worker's rung down to it, which
docs/decisions.md → `routing: the stability reviewer stays on the project's rung` records.
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 concurrent.futures
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, replayed, report, reviewed_path, Round, round_from, sample, stamp_seconds
from project_key import checkout_of
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.retry import first_reply, Limited
from claude_code.transcript import first_timestamped_line, read_transcript
from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
from loop_claude.project.model_choice import read_models_file
from loop_claude.stop import Stop
LATEST = 10
# Reviews replayed at once.
AT_ONCE = 4
LOWEST_R_PLUS_C = 2
REVIEWER = "stability-reviewer"
USAGE = "usage: stability-replay <model>, a model on the routing ladder"
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:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
anchor = project_rung(argv[0]) if len(argv) == 1 else None
if anchor is None:
print(f"stability-replay: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr)
return 1
rounds = archived_rounds(argv[0], archive_root(home, env), home)
if isinstance(rounds, Failure):
print(f"stability-replay: {rounds.reason}", file=sys.stderr)
return 1
codes = {found: code for found in rounds if not isinstance(code := code_of(found, effects), Failure)}
if not codes:
print(f"stability-replay: no archived stability round of projects on {argv[0]} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find", file=sys.stderr)
return 1
chosen = sample(list(codes), LATEST)
candidates = list(LADDER[position(picked(anchor, LOWEST_R_PLUS_C)):position(anchor)])[::-1]
replay = replayed(chosen, anchor, candidates, lambda on, rung: review_all([(found, codes[found]) for found in on], rung, anchor, effects))
if isinstance(replay, Limited):
print(f"stability-replay: claude hit a usage limit: {replay.said}; replay again once it resets", file=sys.stderr)
return 1
print(report(argv[0], anchor, chosen, replay))
return 0
def archived_rounds(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
models = read_models_file(home / ".claude" / "loop-claude-models.json")
if isinstance(models, Stop):
return Failure(models.reason)
found = []
try:
for key in sorted(key for key, on in models.items() if on == model):
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")):
if json.loads(meta.read_text(encoding="utf-8")).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:
path = reviewed_path(found.prompt, found.root, os.path.exists)
if path is None:
return Failure("the prompt names no one worktree")
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", "refs/remotes/origin/HEAD")
main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", "refs/remotes/origin/HEAD")
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 review_all(on: list[tuple[Round, Code]], rung: Rung, anchor: Rung, effects: Effects) -> list[set[int]] | Limited:
print(f"replaying {len(on)} stability rounds on {rung}", file=sys.stderr, flush=True)
with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool:
running = [pool.submit(findings_found, found, code, rung, anchor, effects) for found, code in on]
found_sets = []
for future in running:
found = future.result()
if isinstance(found, Limited):
pool.shutdown(cancel_futures=True)
return found
found_sets.append(found)
return found_sets
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
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 = ["-p", "--agent", REVIEWER, *rung.flags(), "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"]
reply = claude_reply(effects, args, clone, found.prompt.replace(code.path, clone))
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 = ["-p", "--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions", "--tools", ""]
reply = claude_reply(effects, args, root, prompt)
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 claude_reply(effects: Effects, args: list[str], cwd: str, prompt: str) -> dict | Failure | Limited:
try:
proc = effects.claude(args, cwd, prompt)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
reply = parse_entry(proc.stdout) or {}
if hit_limit(reply):
return Limited(None, limit_said(reply))
if proc.returncode != 0:
return Failure(proc.stderr.strip() or f"claude exited {proc.returncode}")
return reply
def git(effects: Effects, cwd: str, *args: str) -> str | Failure:
ran = effects.git(list(args), cwd)
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")