Answer architecture round 1: 2 🔴, 13 🟡; test the replay's main and report, share one judge run and the archive format, pin the reference judge, route only replayed models, and say why the judge climbs

This commit is contained in:
2026-10-15 08:39:10 +02:00
parent 069b3814b9
commit 16aba4cd98
18 changed files with 309 additions and 139 deletions
+46 -42
View File
@@ -8,15 +8,16 @@ verdicts archived for the projects that ~/.claude/loop-claude-models.json runs o
archive is what the judge read for the verdict beside it, so the replay hands the judge that copy,
with the task, premises and records each project holds now.
It first replays every verdict on today's judge: the model at its settings' effort. A verdict
today's judge returns another kind on rests on the records and judge rules of its day, so no rung
is held to it. It then replays the rest on each rung from the one the lowest R + C picks up to the
project's rung, cheapest first, and stops at the first rung that returns all of them. It prints
each verdict a rung missed, and the cheapest rung that missed none.
It first replays every verdict on the reference judge: the model at xhigh effort, where the judge
ran before it was routed. A verdict the reference judge returns another kind on rests on the
records and judge rules of its day, so no rung is held to it. It then replays the rest on each rung
from the one the lowest R + C picks up to the model's cheapest rung, cheapest first, and stops at
the first rung that returns all of them. It prints each verdict a rung missed, and the cheapest
rung that missed none.
A verdict whose project or transcript cannot be read replays as failed, and so does a reply the loop
would reject. Exit 1, saying why, on bad arguments, an unreadable archive or models file, or a
usage limit.
Like the loop, it tries a judge three times running before it counts the reply as failed. A
verdict whose project or transcript cannot be read replays as failed too. Exit 1, saying why, on
bad arguments, an unreadable archive or models file, or a usage limit.
"""
import concurrent.futures
import pathlib
@@ -24,12 +25,14 @@ import sys
import typing
from transcript_archive.location import archive_root
from judge_replay.replay import Case, case_from, checkout_root, replayed, sample, verdict_kind
from transcript_archive.read import archived_outcomes, transcript_of
from judge_replay.replay import Case, case_from, Kind, replayed, report, sample, verdict_kind
from project_key import checkout_of
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge import judge_args, judge_prompt, run_judge
from loop_claude.cycle.retry import FAILURES_RUNNING, Limited
from loop_claude.cycle.judge import judge_once, Verdict
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
from loop_claude.cycle.retry import Limited
from loop_claude.project.model_choice import read_models_file
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
@@ -37,16 +40,14 @@ from claude_code.transcript import read_transcript, render
from loop_claude.stop import Stop
PER_KIND = 15
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
REFERENCE_EFFORT = "xhigh"
# claude runs at a time; each judge reads up to JUDGE_PROMPT_CHARS.
AT_ONCE = 4
LOWEST_R_PLUS_C = 2
USAGE = "usage: judge-replay <model>, a model on the routing ladder"
class UsageLimit(Exception):
pass
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())
@@ -60,20 +61,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
print(f"judge-replay: {cases.reason}", file=sys.stderr)
return 1
cases = sample(cases, PER_KIND)
reference = Rung(argv[0], REFERENCE_EFFORT)
candidates = list(LADDER[position(picked(anchor, LOWEST_R_PLUS_C)):position(anchor) + 1])
try:
replay = replayed(cases, Rung(argv[0]), candidates, lambda on, rung: rule_all(on, rung, home / ".claude", effects))
except UsageLimit as limit:
print(f"judge-replay: {limit}", file=sys.stderr)
replay = replayed(cases, reference, candidates, lambda on, rung: rule_all(on, rung, home / ".claude", effects))
if isinstance(replay, Limited):
print(f"judge-replay: claude hit a usage limit: {replay.said}; replay again once it resets", file=sys.stderr)
return 1
kinds = {kind: sum(found.on_record == kind for found in cases) for kind in dict.fromkeys(found.on_record for found in cases)}
print(f"Replayed {len(cases)} verdicts of {argv[0]} projects: {', '.join(f'{count} {kind}' for kind, count in kinds.items())}.")
print(f"Today's judge, {argv[0]}, reproduced {len(cases) - len(replay.unreproduced)}.{' It returned another kind on:' if replay.unreproduced else ''}")
print_missed(replay.unreproduced)
for tried in replay.tried:
print(f"{tried.rung} missed {len(tried.missed) or 'none'}{':' if tried.missed else '.'}")
print_missed(tried.missed)
print(f"Cheapest rung that returns every verdict today's judge reproduces: {replay.cheapest or 'none up to the project rung'}")
print(report(argv[0], reference, cases, replay))
return 0
@@ -81,24 +75,34 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C
models = read_models_file(home / ".claude" / "loop-claude-models.json")
if isinstance(models, Stop):
return Failure(models.reason)
listed = archived_outcomes(root)
if isinstance(listed, Failure):
return listed
found = []
try:
for outcomes in root.rglob("*.outcomes.md"):
key = str(outcomes.parent.parent.relative_to(root))
if models.get(key) == model and (case := case_from(checkout_root(key, home), outcomes.read_text(encoding="utf-8"), outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"))):
found.append(case)
for key, outcomes in listed:
case = case_from(checkout_of(key, home), outcomes.read_text(encoding="utf-8"), transcript_of(outcomes)) if models.get(key) == model else None
found += [case] if case else []
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {root}: {failure}")
return found
def rule_all(cases: list[Case], rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> list[str]:
def rule_all(cases: list[Case], rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> list[Kind] | Limited:
print(f"replaying {len(cases)} verdicts on {rung}", file=sys.stderr, flush=True)
with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool:
return list(pool.map(lambda found: rule(found, rung, claude_dir, effects), cases))
running = [pool.submit(rule, found, rung, claude_dir, effects) for found in cases]
kinds = []
for future in running:
kind = future.result()
if isinstance(kind, Limited):
pool.shutdown(cancel_futures=True)
return kind
kinds.append(kind)
return kinds
def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> str:
def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> Kind | Limited:
premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript))
if isinstance(premises, Stop):
return verdict_kind(Failure(premises.reason))
@@ -106,13 +110,13 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) ->
return verdict_kind(Failure(records.reason))
if isinstance(entries, Failure):
return verdict_kind(entries)
prompt, shown = judge_prompt(case.task, premises, records, render(entries))
verdict = run_judge(case.root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
if isinstance(verdict, Limited):
raise UsageLimit(f"{rung} hit a usage limit: {verdict.said}; replay again once it resets")
return verdict_kind(verdict)
verdict = retried_as_the_loop_does(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
def print_missed(missed: list[tuple[Case, str]]) -> None:
for found, kind in missed:
print(f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}")
def retried_as_the_loop_does(attempt: typing.Callable[[], Verdict | Failure | Limited]) -> Verdict | Failure | Limited:
"""The first reply that is no Failure, or the last of FAILURES_RUNNING failures."""
for _ in range(FAILURES_RUNNING - 1):
if not isinstance(verdict := attempt(), Failure):
return verdict
return attempt()
+52 -41
View File
@@ -1,101 +1,112 @@
"""Which archived verdicts to replay, and the cheapest rung that returns them: docs/decisions.md → `routing:`."""
"""Which archived verdicts to replay, the cheapest rung that returns them, and the report: docs/decisions.md → `routing:`."""
import collections
import dataclasses
import pathlib
import re
import typing
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.retry import Limited
from model_routing.ladder import Rung
from utc_stamp import STAMPED
# The first verdict archived beside a transcript copy: the judge ruled on that copy as it stands.
FIRST_VERDICT = re.compile(rf"^({STAMPED}) Verdict: (finished|unfinished|interrupt|quoted answer)$", re.MULTILINE)
TASK = re.compile(rf"\ATask: (.*?)\n\n{STAMPED} ", re.DOTALL)
# claude's reply as the replay compares it: a verdict as the archive words it, such as FINISHED, or a failure with its reason.
Kind = str
@dataclasses.dataclass(frozen=True)
class Case:
"""One archived verdict: on_record is its kind, as the archive words it, and at its UTC stamp."""
"""One archived verdict: on_record, judged at its UTC stamp."""
root: str
task: str
transcript: pathlib.Path
at: str
on_record: str
on_record: Kind
@dataclasses.dataclass(frozen=True)
class Tried:
"""A rung, and each case it returned another kind of verdict on, with that kind."""
"""A rung, and each case it returned another kind on, with that kind."""
rung: Rung
missed: list[tuple[Case, str]]
missed: list[tuple[Case, Kind]]
@dataclasses.dataclass(frozen=True)
class Replay:
"""unreproduced holds each case today's judge returned another kind on; tried, each rung tried, cheapest first; cheapest, the first rung that missed none, or None."""
unreproduced: list[tuple[Case, str]]
"""unreproduced holds each case the reference judge returned another kind on; tried, each rung tried, cheapest first; cheapest, the first rung that missed none, or None."""
unreproduced: list[tuple[Case, Kind]]
tried: list[Tried]
cheapest: Rung | None
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
"""The case an outcomes file holds; None when it holds no verdict."""
task, verdict = TASK.match(outcomes), FIRST_VERDICT.search(outcomes)
if not (task and verdict):
"""The first verdict an outcomes file holds: the judge ruled on the transcript copy beside it as the copy stands. None when it holds none."""
task, verdict = task_of(outcomes), first_verdict(outcomes)
if task is None or verdict is None:
return None
return Case(root, task[1], transcript, verdict[1], verdict[2])
def checkout_root(key: str, home: pathlib.Path) -> str:
"""The checkout an archive key names: the inverse of project_key."""
under_code = home / "code" / key
return str(under_code) if under_code.is_dir() else f"/{key}"
return Case(root, task, transcript, *verdict)
def sample(cases: list[Case], per_kind: int) -> list[Case]:
"""The latest per_kind cases of each kind of verdict, in the order they were judged."""
seen: collections.Counter[str] = collections.Counter()
seen: collections.Counter[Kind] = collections.Counter()
kept = []
for found in sorted(cases, key=lambda found: found.at, reverse=True):
for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript)), reverse=True):
seen[found.on_record] += 1
if seen[found.on_record] <= per_kind:
kept.append(found)
return kept[::-1]
def verdict_kind(verdict: Verdict | Failure) -> str:
def verdict_kind(verdict: Verdict | Failure) -> Kind:
match verdict:
case Finished():
return "finished"
return FINISHED
case Unfinished():
return "unfinished"
return UNFINISHED
case Interrupt():
return "interrupt"
return INTERRUPTED
case QuotedAnswer():
return "quoted answer"
return ANSWERED
case Failure(reason):
return f"failed: {reason}"
case _:
typing.assert_never(verdict)
def replayed(cases: list[Case], today: Rung, candidates: list[Rung], rule_all: typing.Callable[[list[Case], Rung], list[str]]) -> Replay:
"""Replays the cases on today's rung, then only those it reproduces on each candidate, cheapest first, until one returns every verdict.
def replayed(cases: list[Case], reference: Rung, candidates: list[Rung], rule_all: typing.Callable[[list[Case], Rung], list[Kind] | Limited]) -> Replay | Limited:
"""Replays the cases on the reference rung, then only those it reproduces on each candidate, cheapest first, until one returns every verdict.
A verdict today's judge does not reproduce rests on the records and judge rules of its day, so no rung is held to it.
A verdict the reference judge does not reproduce rests on the records and judge rules of its day, so no rung is held to it.
"""
reproduced, unreproduced = [], []
for found, kind in zip(cases, rule_all(cases, today)):
if kind == found.on_record:
reproduced.append(found)
else:
unreproduced.append((found, kind))
ruled = rule_all(cases, reference)
if isinstance(ruled, Limited):
return ruled
reproduced = [found for found, kind in zip(cases, ruled) if kind == found.on_record]
unreproduced = [(found, kind) for found, kind in zip(cases, ruled) if kind != found.on_record]
tried = []
for rung in candidates:
missed = [(found, kind) for found, kind in zip(reproduced, rule_all(reproduced, rung)) if kind != found.on_record]
tried.append(Tried(rung, missed))
if not missed:
ruled = rule_all(reproduced, rung)
if isinstance(ruled, Limited):
return ruled
tried.append(Tried(rung, [(found, kind) for found, kind in zip(reproduced, ruled) if kind != found.on_record]))
if not tried[-1].missed:
return Replay(unreproduced, tried, rung)
return Replay(unreproduced, tried, None)
def report(model: str, reference: Rung, cases: list[Case], replay: Replay) -> str:
kinds = collections.Counter(found.on_record for found in cases)
lines = [
f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.",
f"The reference judge, {reference}, reproduced {len(cases) - len(replay.unreproduced)}{'. It returned another kind on:' if replay.unreproduced else '.'}",
*missed_lines(replay.unreproduced),
]
for tried in replay.tried:
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *missed_lines(tried.missed)]
lines.append(f"Cheapest rung that returns every verdict the reference judge reproduces: {replay.cheapest or 'none up to the project rung'}")
return "\n".join(lines)
def missed_lines(missed: list[tuple[Case, Kind]]) -> list[str]:
return [f" {found.root} {found.at}: on record {found.on_record}, replayed {kind}" for found, kind in missed]
+122 -28
View File
@@ -1,19 +1,28 @@
import contextlib
import io
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from judge_replay.replay import Case, case_from, checkout_root, replayed, sample, verdict_kind
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
from judge_replay.replay import Case, case_from, Replay, replayed, report, sample, Tried, verdict_kind
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle.retry import Limited
from judge_replay import main
from model_routing.ladder import Rung
TOOL = pathlib.Path(__file__).resolve().parents[1] / "judge-replay"
TRANSCRIPT = pathlib.Path("/archive/p/c/a.jsonl")
CHEAP = Rung("claude-haiku-5-5", "xhigh")
MIDDLE = Rung("claude-sonnet-5-5", "high")
TODAY = Rung("claude-opus-5-5")
REFERENCE = Rung("claude-opus-5-5", "xhigh")
def case(at, on_record):
@@ -23,61 +32,146 @@ def case(at, on_record):
class CaseFrom(unittest.TestCase):
def test_takes_the_task_and_the_first_verdict_on_the_copy(self):
outcomes = "Task: Do the next chunk.\nThen merge it.\n\n2026-10-14T10:00:00Z Stopped: claude failed\n\nWorker: x\n2026-10-14T11:00:00Z Verdict: unfinished\n\nEvidence:\n> on\n\nWorker: x\n2026-10-14T11:00:01Z Stepped up\n\nWorker: y\n"
self.assertEqual(case_from("/code/p", outcomes, TRANSCRIPT), Case("/code/p", "Do the next chunk.\nThen merge it.", TRANSCRIPT, "2026-10-14T11:00:00Z", "unfinished"))
self.assertEqual(case_from("/code/p", outcomes, TRANSCRIPT), Case("/code/p", "Do the next chunk.\nThen merge it.", TRANSCRIPT, "2026-10-14T11:00:00Z", UNFINISHED))
def test_reads_each_kind_of_verdict(self):
for kind in ("finished", "unfinished", "interrupt", "quoted answer"):
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z Verdict: {kind}\n\nmore\n", TRANSCRIPT)
self.assertEqual(found.on_record, kind)
for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED):
found = case_from("/code/p", f"Task: t\n\n2026-10-14T10:00:00Z {verdict}\n\nmore\n", TRANSCRIPT)
self.assertEqual(found.on_record, verdict)
def test_skips_a_copy_with_no_verdict(self):
self.assertIsNone(case_from("/code/p", "Task: t\n\n2026-10-14T10:00:00Z Stepped up\n\nWorker: y\n", TRANSCRIPT))
self.assertIsNone(case_from("/code/p", "not an outcomes file", TRANSCRIPT))
class CheckoutRoot(unittest.TestCase):
def test_finds_a_key_under_code_or_else_under_the_root(self):
with tempfile.TemporaryDirectory() as home:
(pathlib.Path(home) / "code" / "log").mkdir(parents=True)
self.assertEqual(checkout_root("log", pathlib.Path(home)), f"{home}/code/log")
self.assertEqual(checkout_root("home/me/.claude", pathlib.Path(home)), "/home/me/.claude")
class Sample(unittest.TestCase):
def test_keeps_the_latest_of_each_kind_in_the_order_they_were_judged(self):
cases = [case("2026-10-14T10:00:01Z", "finished"), case("2026-10-14T10:00:03Z", "finished"), case("2026-10-14T10:00:02Z", "finished"), case("2026-10-14T10:00:00Z", "interrupt")]
cases = [case("2026-10-14T10:00:01Z", FINISHED), case("2026-10-14T10:00:03Z", FINISHED), case("2026-10-14T10:00:02Z", FINISHED), case("2026-10-14T10:00:00Z", INTERRUPTED)]
self.assertEqual(sample(cases, 2), [cases[3], cases[2], cases[1]])
class VerdictKind(unittest.TestCase):
def test_names_each_verdict_as_the_archive_does(self):
self.assertEqual(verdict_kind(Finished("e")), "finished")
self.assertEqual(verdict_kind(Unfinished("e", 3)), "unfinished")
self.assertEqual(verdict_kind(Interrupt("e", "q?")), "interrupt")
self.assertEqual(verdict_kind(QuotedAnswer("e", "q?", "a")), "quoted answer")
self.assertEqual(verdict_kind(Finished("e")), FINISHED)
self.assertEqual(verdict_kind(Unfinished("e", 3)), UNFINISHED)
self.assertEqual(verdict_kind(Interrupt("e", "q?")), INTERRUPTED)
self.assertEqual(verdict_kind(QuotedAnswer("e", "q?", "a")), ANSWERED)
self.assertEqual(verdict_kind(Failure("the judge quoted x")), "failed: the judge quoted x")
class Replayed(unittest.TestCase):
def test_tries_rungs_cheapest_first_on_the_verdicts_todays_judge_reproduces_and_stops_at_the_first_that_returns_all(self):
cases = [case("2026-10-14T10:00:00Z", "finished"), case("2026-10-14T10:00:01Z", "interrupt"), case("2026-10-14T10:00:02Z", "finished")]
replies = {TODAY: ["finished", "interrupt", "unfinished"], CHEAP: ["finished", "finished"], MIDDLE: ["finished", "interrupt"]}
def test_tries_rungs_cheapest_first_on_the_verdicts_the_reference_reproduces_and_stops_at_the_first_that_returns_all(self):
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED), case("2026-10-14T10:00:02Z", FINISHED)]
replies = {REFERENCE: [FINISHED, INTERRUPTED, UNFINISHED], CHEAP: [FINISHED, FINISHED], MIDDLE: [FINISHED, INTERRUPTED]}
asked = []
def rule_all(on, rung):
asked.append((len(on), rung))
return replies[rung]
replay = replayed(cases, TODAY, [CHEAP, MIDDLE, Rung("claude-opus-5-5", "medium")], rule_all)
self.assertEqual(replay.unreproduced, [(cases[2], "unfinished")])
self.assertEqual([(tried.rung, tried.missed) for tried in replay.tried], [(CHEAP, [(cases[1], "finished")]), (MIDDLE, [])])
self.assertEqual(replay.cheapest, MIDDLE)
self.assertEqual(asked, [(3, TODAY), (2, CHEAP), (2, MIDDLE)])
replay = replayed(cases, REFERENCE, [CHEAP, MIDDLE, Rung("claude-opus-5-5", "medium")], rule_all)
self.assertEqual(replay, Replay([(cases[2], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE))
self.assertEqual(asked, [(3, REFERENCE), (2, CHEAP), (2, MIDDLE)])
def test_names_no_rung_when_every_candidate_misses_a_verdict(self):
replay = replayed([case("2026-10-14T10:00:00Z", "finished")], TODAY, [CHEAP], lambda on, rung: ["finished"] if rung == TODAY else ["interrupt"])
replay = replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else [INTERRUPTED])
self.assertIsNone(replay.cheapest)
def test_stops_at_a_usage_limit(self):
limit = Limited(None, "limit")
self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: limit), limit)
self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else limit), limit)
class Report(unittest.TestCase):
def test_counts_the_verdicts_and_names_each_miss_and_the_cheapest_rung(self):
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)]
replay = Replay([(cases[0], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE)
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
" /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished",
"claude-haiku-5-5 at xhigh effort missed 1:",
" /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished",
"claude-sonnet-5-5 at high effort missed 0.",
"Cheapest rung that returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
])
self.assertTrue(report("claude-opus-5-5", REFERENCE, cases, Replay([], [Tried(CHEAP, [(cases[1], FINISHED)])], None)).endswith(": none up to the project rung"))
def unused(*_):
raise AssertionError("not called")
class Main(unittest.TestCase):
"""The tool on a temporary home: a project on Opus 5.5 with one finished and one interrupt verdict, and one on another model."""
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"}))
for key, verdicts in (("proj", (FINISHED, INTERRUPTED)), ("other", (FINISHED,))):
(self.home / "code" / key).mkdir(parents=True)
(self.home / "code" / key / "README.md").write_text("# p\n\n## Goals\n\n1. Ship.\n\n## Audience\n\nMe.\n")
chunk = self.home / ".claude" / "loop-claude-transcripts" / key / "c1"
chunk.mkdir(parents=True)
for n, verdict in enumerate(verdicts):
(chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {verdict}"}]}}) + "\n")
(chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {verdict}\n\nEvidence:\n> e\n")
self.calls = []
def run_main(self, argv, reply):
def claude(args, cwd, prompt):
self.calls.append((args[args.index("--model") + 1], args[args.index("--effort") + 1], cwd))
result = reply(args[args.index("--model") + 1], "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, 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()
@staticmethod
def verdict(interrupt, evidence):
output = {"answer": "", "bundled": 0, "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""}
return {"type": "result", "structured_output": output}
def test_replays_the_models_projects_on_the_reference_then_cheapest_first_and_prints_the_rung_that_returns_all(self):
# Haiku misses the interrupt; Sonnet returns both.
def reply(model, interrupted):
return self.verdict(interrupted and model != "claude-haiku-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
code, out, err = self.run_main(["claude-opus-5-5"], reply)
self.assertEqual(code, 0, err)
self.assertEqual({cwd for _, _, cwd in self.calls}, {str(self.home / "code" / "proj")})
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-haiku-5-5", "xhigh"), ("claude-haiku-5-5", "max"), ("claude-sonnet-5-5", "high")])
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"))
def test_tries_up_to_the_models_cheapest_rung_and_retries_a_failed_reply_as_the_loop_does(self):
def reply(model, interrupted):
return self.verdict(interrupted, "not in the transcript" if model != "claude-opus-5-5" else f"said {INTERRUPTED if interrupted else FINISHED}")
code, out, _ = self.run_main(["claude-opus-5-5"], reply)
self.assertEqual(code, 0)
self.assertEqual(sum(model == "claude-sonnet-5-5" for model, _, _ in self.calls), 6)
self.assertIn("claude-opus-5-5 at medium effort missed 0.", out)
def test_exits_1_on_a_usage_limit_bad_arguments_or_an_unreadable_models_file(self):
code, _, err = self.run_main(["claude-opus-5-5"], lambda model, interrupted: {"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)
(self.home / ".claude" / "loop-claude-models.json").write_text("[")
self.assertEqual(self.run_main(["claude-opus-5-5"], unused)[0], 1)
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: judge-replay <model>", ran.stdout)
if __name__ == "__main__":
unittest.main()