Record the stability replay: no rung below the project's finds every finding it finds
This commit is contained in:
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from stability_replay import main
|
||||
from loop_claude.effects import system_effects
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
|
||||
@@ -0,0 +1,226 @@
|
||||
"""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 claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.retry import first_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from loop_claude.stop import Stop
|
||||
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
|
||||
from project_key import checkout_of
|
||||
from stability_replay.rounds import authored_by, replayed, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from transcript_archive.location import archive_root
|
||||
|
||||
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()}")
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Which archived stability rounds to replay, the lowest rung that finds their findings, and the report: docs/decisions.md → `routing: the stability reviewer stays on 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 loop_claude.cycle.retry import Limited
|
||||
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
|
||||
seconds: float
|
||||
began: float
|
||||
prompt: str
|
||||
findings: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Tried:
|
||||
"""A rung, and each finding it missed that the reference reviewer found, with its round."""
|
||||
rung: Rung
|
||||
missed: list[tuple[Round, str]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Replay:
|
||||
"""unfound counts the findings on record the reference reviewer did not find; tried holds each rung tried, highest first; lowest, the lowest rung that missed none of the rest, or None."""
|
||||
unfound: int
|
||||
tried: list[Tried]
|
||||
lowest: Rung | None
|
||||
|
||||
|
||||
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 isinstance(first.get("timestamp"), str) 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"], stamp_seconds(first["timestamp"]), began, prompt, tuple(findings))
|
||||
|
||||
|
||||
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):
|
||||
first_gone = next((prefix for prefix in [*reversed(path.parents), path][1:] 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 of log, newest first, authored by then. 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 replayed(rounds: list[Round], reference: Rung, candidates: list[Rung], review_all: typing.Callable[[list[Round], Rung], list[set[int]] | Limited]) -> Replay | Limited:
|
||||
"""Replays the rounds on the reference rung, then each candidate, highest first, on the rounds where the reference found a finding, until one misses a finding it found.
|
||||
|
||||
Going down, every rung at or above the lowest that missed none was tried.
|
||||
"""
|
||||
found = review_all(rounds, reference)
|
||||
if isinstance(found, Limited):
|
||||
return found
|
||||
held = [(found_round, kept) for found_round, kept in zip(rounds, found) if kept]
|
||||
unfound = sum(len(found_round.findings) for found_round in rounds) - sum(len(kept) for _, kept in held)
|
||||
tried: list[Tried] = []
|
||||
lowest = None
|
||||
# With no finding to hold a rung to, every rung would miss none.
|
||||
for rung in candidates if held else []:
|
||||
found = review_all([found_round for found_round, _ in held], rung)
|
||||
if isinstance(found, Limited):
|
||||
return found
|
||||
tried.append(Tried(rung, [(found_round, found_round.findings[n]) for (found_round, kept), on_rung in zip(held, found) for n in sorted(kept - on_rung)]))
|
||||
if tried[-1].missed:
|
||||
break
|
||||
lowest = rung
|
||||
return Replay(unfound, tried, lowest)
|
||||
|
||||
|
||||
def report(model: str, reference: Rung, rounds: list[Round], replay: Replay) -> 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 {total - replay.unfound} of them.",
|
||||
]
|
||||
for tried in replay.tried:
|
||||
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {found_round.root} {found_round.at}: {finding.splitlines()[0]}" for found_round, finding 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)
|
||||
@@ -0,0 +1,217 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from model_routing.ladder import Rung
|
||||
from stability_replay import main
|
||||
from stability_replay.rounds import authored_by, recorded_findings, replayed, report, reviewed_path, Round, round_from, sample, Replay, Tried
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
|
||||
def entry(kind, text, **fields):
|
||||
return {"type": kind, "message": {"content": [{"type": "text", "text": text}]}, **fields}
|
||||
|
||||
|
||||
def a_round(at, findings=("🔴 a",)):
|
||||
return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", at, 0, "Review it.", tuple(findings))
|
||||
|
||||
|
||||
class RecordedFindings(unittest.TestCase):
|
||||
def test_takes_each_red_and_yellow_finding_with_the_lines_up_to_the_next_blank_line_or_finding(self):
|
||||
report_text = "BLOCK\n\n1 🔴, 2 🟡 in all.\n\n1. 🔴 **Loop** at a.py:3\nnever ends.\n- 🟡 b.py:1 slow\n| 🟡 | c.py | odd |\n\n🟢 nit\n### 🔴 Heading\n**🟡 Bold**"
|
||||
self.assertEqual(recorded_findings(report_text), ["1. 🔴 **Loop** at a.py:3\nnever ends.", "- 🟡 b.py:1 slow", "| 🟡 | c.py | odd |", "### 🔴 Heading", "**🟡 Bold**"])
|
||||
|
||||
def test_skips_a_count_or_verdict_line_that_names_the_marks(self):
|
||||
self.assertEqual(recorded_findings("APPROVE\n\nNo 🔴 or 🟡 findings.\n0 🔴, 0 🟡"), [])
|
||||
|
||||
|
||||
class RoundFrom(unittest.TestCase):
|
||||
def test_reads_the_prompt_the_last_report_and_when_the_reviewer_started(self):
|
||||
entries = [
|
||||
entry("user", "Review branch x in /code/p-x.", timestamp="2026-10-14T10:00:00.500Z", cwd="/code/p-x", gitBranch="x"),
|
||||
entry("assistant", "Reading."),
|
||||
entry("assistant", "BLOCK\n\n🔴 a.py:1 breaks"),
|
||||
]
|
||||
self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 1791972000.5, 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
|
||||
|
||||
def test_skips_a_round_with_no_red_or_yellow_finding_or_no_report(self):
|
||||
start = entry("user", "Review.", timestamp="2026-10-14T10:00:00Z", cwd="/code/p", gitBranch="x")
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, []))
|
||||
|
||||
|
||||
class ReviewedPath(unittest.TestCase):
|
||||
def test_names_the_worktree_the_prompt_names_that_is_gone(self):
|
||||
exists = {"/code", "/code/p", "/code/p/worktrees", "/tmp"}.__contains__
|
||||
self.assertEqual(reviewed_path("Review /code/p-x/src/a.py:3-5; the diff is at /tmp/s/x.diff; /code/p is older.", "/code/p", exists), "/code/p-x")
|
||||
self.assertEqual(reviewed_path("Review `/code/p/worktrees/x`.", "/code/p", exists), "/code/p/worktrees/x")
|
||||
|
||||
def test_names_the_checkout_when_the_prompt_names_no_gone_worktree_and_none_when_it_names_neither_or_two(self):
|
||||
exists = {"/code", "/code/p"}.__contains__
|
||||
self.assertEqual(reviewed_path("Review /code/p.", "/code/p", exists), "/code/p")
|
||||
self.assertIsNone(reviewed_path("Review the branch.", "/code/p", exists))
|
||||
self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists))
|
||||
|
||||
|
||||
class AuthoredBy(unittest.TestCase):
|
||||
def test_takes_the_newest_commit_authored_by_then(self):
|
||||
log = [("c3", 30), ("c2", 20), ("c1", 10)]
|
||||
self.assertEqual(authored_by(log, 25), "c2")
|
||||
self.assertEqual(authored_by(log, 30), "c3")
|
||||
self.assertIsNone(authored_by(log, 5))
|
||||
|
||||
|
||||
class Sample(unittest.TestCase):
|
||||
def test_keeps_the_latest_rounds_in_the_order_they_ran(self):
|
||||
rounds = [a_round(2), a_round(1), a_round(3)]
|
||||
self.assertEqual(sample(rounds, 2), [rounds[0], rounds[2]])
|
||||
|
||||
|
||||
class Replayed(unittest.TestCase):
|
||||
def test_holds_each_rung_highest_first_to_what_the_reference_found_and_stops_at_the_first_that_misses(self):
|
||||
rounds = [a_round(1, ("🔴 a", "🟡 b")), a_round(2, ("🔴 c",))]
|
||||
found = {REFERENCE: [{0, 1}, set()], MIDDLE: [{0, 1}], CHEAP: [{1}]}
|
||||
asked = []
|
||||
|
||||
def review_all(on, rung):
|
||||
asked.append((len(on), rung))
|
||||
return found[rung]
|
||||
|
||||
replay = replayed(rounds, REFERENCE, [MIDDLE, CHEAP, Rung("claude-haiku-5-5", "xhigh")], review_all)
|
||||
self.assertEqual(replay, Replay(1, [Tried(MIDDLE, []), Tried(CHEAP, [(rounds[0], "🔴 a")])], MIDDLE))
|
||||
self.assertEqual(asked, [(2, REFERENCE), (1, MIDDLE), (1, CHEAP)])
|
||||
|
||||
def test_names_no_rung_when_the_first_misses_or_the_reference_found_nothing(self):
|
||||
rounds = [a_round(1)]
|
||||
self.assertEqual(replayed(rounds, REFERENCE, [MIDDLE], lambda on, rung: [{0}] if rung == REFERENCE else [set()]), Replay(0, [Tried(MIDDLE, [(rounds[0], "🔴 a")])], None))
|
||||
self.assertEqual(replayed(rounds, REFERENCE, [MIDDLE], lambda on, rung: [set()]), Replay(1, [], None))
|
||||
|
||||
def test_stops_at_a_usage_limit(self):
|
||||
limit = Limited(None, "limit")
|
||||
self.assertEqual(replayed([a_round(1)], REFERENCE, [MIDDLE], lambda on, rung: limit), limit)
|
||||
self.assertEqual(replayed([a_round(1)], REFERENCE, [MIDDLE], lambda on, rung: [{0}] if rung == REFERENCE else limit), limit)
|
||||
|
||||
|
||||
class Report(unittest.TestCase):
|
||||
def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self):
|
||||
rounds = [a_round(1, ("🔴 a", "🟡 b")), a_round(2)]
|
||||
lines = report("claude-opus-5-5", REFERENCE, rounds, Replay(1, [Tried(MIDDLE, []), Tried(CHEAP, [(rounds[0], "🔴 a\nmore")])], MIDDLE)).splitlines()
|
||||
self.assertEqual(lines, [
|
||||
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
|
||||
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
|
||||
"claude-sonnet-5-5 at high effort missed 0.",
|
||||
"claude-haiku-5-5 at max effort missed 1:",
|
||||
" /code/p 2026-10-14T10:00:01Z: 🔴 a",
|
||||
"Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort",
|
||||
])
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay(0, [Tried(MIDDLE, [(rounds[1], "🔴 a")])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay(3, [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
|
||||
|
||||
def unused(*_):
|
||||
raise AssertionError("not called")
|
||||
|
||||
|
||||
def run_git(cwd, *args):
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=cwd, check=True, capture_output=True)
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
"""The tool on a temporary home: a chunk that began after the checkout's first commit, and whose stability reviewer reviewed branch x at its second, from a worktree since removed."""
|
||||
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"}))
|
||||
origin, self.checkout = self.home / "origin.git", self.home / "code" / "proj"
|
||||
run_git(self.home, "init", "-q", "--bare", "-b", "main", str(origin))
|
||||
run_git(self.home, "clone", "-q", str(origin), str(self.checkout))
|
||||
for n, stamp in enumerate(("2026-10-14T09:00:00Z", "2026-10-14T09:30:00Z", "2026-10-14T11:00:00Z")):
|
||||
(self.checkout / "a.txt").write_text(f"{n}\n")
|
||||
run_git(self.checkout, "add", "a.txt")
|
||||
run_git(self.checkout, "commit", "-qm", f"c{n}", f"--date={stamp}")
|
||||
run_git(self.checkout, "push", "-q", "origin", "main")
|
||||
run_git(self.checkout, "remote", "set-head", "origin", "main")
|
||||
gone = self.home / "code" / "proj-x"
|
||||
for key, cwd in (("proj", gone), ("other", self.home / "code" / "other")):
|
||||
subagents = self.home / ".claude" / "loop-claude-transcripts" / key / "c1" / "session" / "s" / "subagents"
|
||||
subagents.mkdir(parents=True)
|
||||
(subagents.parents[2] / "t0.jsonl").write_text(json.dumps({"type": "summary"}) + "\n" + json.dumps(entry("user", "Do the next chunk.", timestamp="2026-10-14T09:15:00Z")) + "\n")
|
||||
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "stability-reviewer"}))
|
||||
(subagents / "agent-b.meta.json").write_text(json.dumps({"agentType": "prose-reviewer"}))
|
||||
lines = [entry("user", f"Review branch x in {gone}.", timestamp="2026-10-14T10:00:00Z", cwd=str(cwd), gitBranch="x"), entry("assistant", "BLOCK\n\n🔴 a.txt:1 wrong\n\n🟡 slow")]
|
||||
for name in ("agent-a.jsonl", "agent-b.jsonl"):
|
||||
(subagents / name).write_text("".join(json.dumps(line) + "\n" for line in lines))
|
||||
self.reviews = []
|
||||
|
||||
def run_main(self, argv, found):
|
||||
"""found(rung) is the indexes of the recorded findings the reviewer on rung finds."""
|
||||
|
||||
def claude(args, cwd, prompt):
|
||||
rung = Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1])
|
||||
if "--agent" in args:
|
||||
shown = [subprocess.run(["git", *command], cwd=cwd, capture_output=True, text=True).stdout for command in (["show", "HEAD:a.txt"], ["branch", "--show-current"], ["show", "origin/main:a.txt"])]
|
||||
self.reviews.append((rung, *shown, prompt, cwd))
|
||||
result = {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
|
||||
else:
|
||||
reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups())
|
||||
result = found(reviewed)
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
|
||||
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
|
||||
# The default branch stands where it stood when the chunk began, so the prompt's diff against it shows the branch's change.
|
||||
self.assertEqual((reviewed, branch, base), ("1\n", "x\n", "0\n"))
|
||||
self.assertEqual(prompt, f"Review branch x in {cwd}.")
|
||||
self.assertFalse(pathlib.Path(cwd).exists())
|
||||
self.assertIn("The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", out)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"))
|
||||
|
||||
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived stability round of projects on claude-haiku-5-5", err)
|
||||
|
||||
def test_prints_the_help(self):
|
||||
code, out, _ = self.run_main(["-h"], unused)
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: stability-replay <model>"))
|
||||
|
||||
def test_the_launcher_prints_the_help(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0)
|
||||
self.assertIn("usage: stability-replay <model>", ran.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user