118 lines
5.7 KiB
Python
118 lines
5.7 KiB
Python
"""Replay loop-claude's judge on archived verdicts, to find the cheapest rung that returns them: docs/decisions.md → `routing:`.
|
|
|
|
usage: judge-replay <model>
|
|
|
|
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
|
verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest
|
|
15 of each kind, finished, unfinished, interrupt and quoted answer. Each transcript copy in the
|
|
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.
|
|
|
|
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.
|
|
"""
|
|
import concurrent.futures
|
|
import pathlib
|
|
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 loop_claude.effects import Effects
|
|
from failure import Failure
|
|
from loop_claude.cycle.judge import judge_args, judge_prompt, run_judge
|
|
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
|
|
from claude_code.transcript import read_transcript, render
|
|
from loop_claude.stop import Stop
|
|
|
|
PER_KIND = 15
|
|
# 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())
|
|
return 0
|
|
anchor = project_rung(argv[0]) if len(argv) == 1 else None
|
|
if anchor is None:
|
|
print(f"judge-replay: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr)
|
|
return 1
|
|
cases = archived_cases(argv[0], archive_root(home, env), home)
|
|
if isinstance(cases, Failure):
|
|
print(f"judge-replay: {cases.reason}", file=sys.stderr)
|
|
return 1
|
|
cases = sample(cases, PER_KIND)
|
|
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)
|
|
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'}")
|
|
return 0
|
|
|
|
|
|
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
|
models = read_models_file(home / ".claude" / "loop-claude-models.json")
|
|
if isinstance(models, Stop):
|
|
return Failure(models.reason)
|
|
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)
|
|
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]:
|
|
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))
|
|
|
|
|
|
def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> str:
|
|
premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript))
|
|
for unread in (premises, records):
|
|
if isinstance(unread, Stop):
|
|
return verdict_kind(Failure(unread.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)
|
|
|
|
|
|
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}")
|