Merge remote-tracking branch 'origin/main' into item-310

# Conflicts:
#	bin/agent_cycle/interrupt.py
#	bin/agent_cycle/run.py
#	bin/agent_cycle/states.py
#	docs/reading-cost.md
#	todo.md
This commit is contained in:
2026-11-19 04:47:53 +01:00
172 changed files with 9805 additions and 1296 deletions
+9 -7
View File
@@ -1,15 +1,17 @@
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER
from claude_code.entries import Entry
from loop_claude import escalation_mark
from agent_cycle import escalation_mark
from failure import Failure
from loop_claude.cycle.judge import Grounds, JUDGE_RULES, TASK_HEADING, TRANSCRIPT_HEADING
from agent_cycle.judge import Grounds, judge_rules, TASK_HEADING, transcript_heading
from claude_code.transcript import human_answers
from loop_claude.cycle.prompts import typed_answer
from agent_cycle.worker_prompts import typed_answer
def grounds_of(prompt: str, entries: list[Entry]) -> Grounds | Failure:
"""What the quotes of a judge run on prompt are checked against, as judge_prompt would have made it for the transcript's entries: the premises and the records before the task are quotable, the transcript the judge was shown comes before the rules. The prompt is split on the headings judge_prompt writes, at the first of each; a Failure where it lacks one. Rules of an earlier wording stay part of the transcript, a slack that lets an evidence quote them pass."""
before_task, task_heading, after_task = prompt.partition(f"\n\n{TASK_HEADING}")
_, transcript_heading, shown = after_task.partition(TRANSCRIPT_HEADING)
if not (task_heading and transcript_heading):
return Failure(f"the archived prompt lacks the heading {TASK_HEADING.strip()!r} or {TRANSCRIPT_HEADING.strip()!r}, which judge_prompt writes")
return Grounds(shown.removesuffix(f"\n\n{JUDGE_RULES}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer)))
heading = transcript_heading(DRIVER)
_, found_heading, shown = after_task.partition(heading)
if not (task_heading and found_heading):
return Failure(f"the archived prompt lacks the heading {TASK_HEADING.strip()!r} or {heading.strip()!r}, which judge_prompt writes")
return Grounds(shown.removesuffix(f"\n\n{judge_rules(ANSWER_DESTINATIONS, DRIVER)}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer)))
+43 -9
View File
@@ -1,6 +1,6 @@
"""Replay loop-claude's judge on archived verdicts, to find the lowest rung that returns them: docs/decisions.md → `routing: on a model judge-replay covered`.
usage: judge-replay <model>
usage: judge-replay <model> [--offline]
<model> is a project model on the routing ladder this setup ships, 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
@@ -23,7 +23,7 @@ it, missed none.
Record each run in docs/decisions.md → `routing: on a model judge-replay covered`. Where the
model's cheapest rung misses no interrupt, the run is the evidence to add the model to
JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge. judge_rung there
JUDGE_REPLAYED in bin/agent_cycle/routing.py, which routes that model's judge. judge_rung there
keeps the judge to its own model's rungs; a rung above them that misses no interrupt is the
evidence to let the judge climb onto it.
@@ -36,19 +36,34 @@ Like the loop, it tries a judge three times running before it counts the reply a
verdict whose project, transcript or archived judge run cannot be read replays as failed too. Exit 1, saying why, on
bad arguments, an unreadable archive or models file, no archived verdict of the model's projects,
or a usage limit.
With --offline it doesn't call a judge, so the runs, retries and usage limit above don't apply. It reads every
archived verdict of the model's projects, not a sample. It counts how many of them each of three code
deciders decides from the worker's final message, and how many archived interrupts it decides as another
kind, which are its missed interrupts: a "?" rule, a decision table, and a classifier trained on the archive
(judge_replay/offline.py). The rule and the table run on the whole archive; the table's rows were read from
it, so its run isn't a held-out test. The classifier runs on held-out folds, each tested by a model trained on
the other folds, and on the latest fifth of the verdicts, tested by a model trained on the earlier four
fifths. The classifier trains 330 regressions in Python, about 12 minutes on 1,100 verdicts. The report is
kept in replays/judge-replay-<model>-offline-<UTC stamp>/result.md. A verdict whose transcript cannot be read is skipped, and the report counts the skipped. Exit 1, saying why, on bad
arguments, an unreadable archive or models file, no archived verdict of the model's projects, or none with a
transcript that can be read.
"""
import pathlib
import sys
import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER
from transcript_archive.location import archive_root, transcript_of
from transcript_archive.read import archived_outcomes
from rung_replay.archive import archiving, print_report, replay_folder
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
from loop_claude.cycle.judge import Brief, judge_archived, judge_once
from agent_cycle.judge import Brief, judge_archived, judge_once
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
from transcript_archive.project_key import checkout_of
from loop_effects.effects import Effects
from failure import Failure
from judge_replay.offline import final_message, LEARNERS, offline_report, RULES, Sample
from rung_replay.search import first_reply, replayed
from judge_replay.archived_prompt import grounds_of
from transcript_archive.judge_run import JudgeRun
@@ -56,12 +71,13 @@ from model_routing.ladder import Ladder, ProjectRung, REVIEW_STEPS, Rung
from claude_code.reply import Limited
from model_routing.ladder_file import read_ladder, SHIPPED
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from loop_claude.project.records import read_records, RECORDS_NAMED
from claude_code.transcript import read_transcript
from loop_claude.verdicts import Verdict
from agent_cycle.verdicts import Verdict
TOOL = "judge-replay"
USAGE = f"{TOOL} <model>, a model on the routing ladder"
USAGE = f"{TOOL} <model> [--offline]; <model> is a model on the routing ladder"
OFFLINE = "--offline"
PER_KIND = 15
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
REFERENCE_EFFORT = "xhigh"
@@ -72,7 +88,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return failed(TOOL, ladder.reason)
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, argv))
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, [arg for arg in argv if arg != OFFLINE]))
if isinstance(project, int):
return project
cases = archived_cases(project.rung.model, archive_root(home, env), home)
@@ -80,6 +96,8 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
return failed(TOOL, cases.reason)
if not cases:
return failed(TOOL, f"no archived verdicts of projects on {project.rung.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
if OFFLINE in argv:
return offline(project.rung.model, cases, archive_root(home, env), effects)
cases = sample(cases, PER_KIND)
folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now())
effects = archiving(effects, folder)
@@ -92,6 +110,22 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
return 0
def offline(model: str, cases: list[Case], root: pathlib.Path, effects: Effects) -> int:
"""Replays the verdicts of cases offline, oldest first, and keeps the report in the archive as a judge replay does."""
samples, skipped = [], 0
for found in sorted(cases, key=lambda found: (found.at, found.root, str(found.transcript))):
entries = read_transcript(str(found.transcript))
if isinstance(entries, Failure):
skipped += 1
print(f"{TOOL}: skipped a verdict: {entries.reason}", file=sys.stderr)
else:
samples.append(Sample(found.archived_kind, final_message(entries)))
if not samples:
return failed(TOOL, "no archived verdict has a transcript that can be read")
print_report(replay_folder(root, TOOL, [model, OFFLINE], effects.now()), offline_report(model, samples, RULES, LEARNERS, skipped=skipped))
return 0
def model_argument(ladder: Ladder, argv: list[str]) -> ProjectRung | None:
"""The project's rung on ladder of the one model argv names; None for any other argv."""
return ladder.project_rung(argv[0]) if len(argv) == 1 else None
@@ -130,7 +164,7 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind |
grounds = grounds_of(kept.prompt, entries)
if isinstance(grounds, Failure):
return verdict_kind(grounds)
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, effects))
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, DRIVER, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
premises, records = read_premises(case.root, home), read_records(case.root, home, home / ".claude")
if isinstance(premises, Failure):
@@ -138,5 +172,5 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind |
if isinstance(records, Failure):
return verdict_kind(records)
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
verdict = first_reply(lambda: judge_once(case.root, Brief(case.task, premises, records, entries, 0), rung, effects))
verdict = first_reply(lambda: judge_once(case.root, Brief(task=case.task, premises=premises, records=records, records_named=RECORDS_NAMED, answer_destinations=ANSWER_DESTINATIONS, entries=entries, escalated_at=0, driver=DRIVER), rung, effects))
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
+175
View File
@@ -0,0 +1,175 @@
"""Deciders of a verdict's kind that run offline on the worker's final message, replayed on the archive: docs/decisions.md → `routing: the offline classifier may decide finished, …`."""
import collections
import math
import random
import re
import typing
from claude_code.entries import AssistantTurn, Entry, Text
from transcript_archive.outcomes import FINISHED, INTERRUPTED, UNFINISHED
from judge_replay.replay import Kind
class Sample(typing.NamedTuple):
"""What a decider reads of one archived verdict: the kind the archive gives it and the worker's final message."""
kind: Kind
text: str
# A decider names a kind, or None to leave the verdict to the judge's model. A method builds one from the samples it may learn from.
Decider = typing.Callable[[str], Kind | None]
Method = typing.Callable[[typing.Sequence[Sample]], Decider]
Counts = collections.Counter[tuple[Kind, Kind | None]]
FOLDS = 10
INNER_FOLDS = 5
# A word in fewer messages than this is left out of the classifier.
MIN_MESSAGES = 3
EPOCHS = 8
# The classifier averages this many regressions, each shuffling the samples in its own order: one shuffle alone moved the missed interrupts of a run between 0 and 2.
SEEDS = 5
RATE = 0.05
DECAY = 1e-3
# The latest 1/LATEST of the archive is the second test: the verdicts a decider would meet next.
LATEST = 5
# The first row whose pattern matches the final message decides it; a message no row matches is left to the judge. The rows come from reading the archive's interrupts, so a run of the table on the whole archive is not a held-out test.
DECISION_TABLE = (
(INTERRUPTED, re.compile(r"(?i)\?|recommend|your call|needs? you|tell me|you answer|please|unmerged|not merged|do you|should i|i need|need your|you say|decisions? for|stays until")),
(FINISHED, re.compile(r"(?i)\bmerged\b(?!.*ready to cut)")),
)
def final_message(entries: list[Entry]) -> str:
"""The text of the worker's last turn that has any, "" where it wrote none."""
for entry in reversed(entries):
if isinstance(entry, AssistantTurn):
text = "\n".join(part.text for part in entry.parts if isinstance(part, Text) and part.text.strip())
if text:
return text
return ""
def question_mark(samples: typing.Sequence[Sample]) -> Decider:
"""The one rule: an interrupt where the message holds a "?", finished where it holds none."""
return lambda text: INTERRUPTED if "?" in text else FINISHED
def decision_table(samples: typing.Sequence[Sample]) -> Decider:
return lambda text: next((kind for kind, pattern in DECISION_TABLE if pattern.search(text)), None)
def words_of(text: str) -> frozenset[str]:
"""Each word and each pair of neighbouring words of the message, and its question marks."""
words = re.findall(r"[a-z0-9']+|\?", text.lower())
return frozenset(words) | {f"{first} {second}" for first, second in zip(words, words[1:])}
def logistic(samples: typing.Sequence[Sample], seed: int) -> typing.Callable[[str], float]:
"""The chance that a message is an interrupt, from a logistic regression over its words that the samples train, shuffled in the order seed gives."""
seen = collections.Counter(word for found in samples for word in words_of(found.text))
vocabulary = {word for word, count in seen.items() if count >= MIN_MESSAGES}
data = [(words_of(found.text) & vocabulary, 1.0 if found.kind == INTERRUPTED else 0.0) for found in samples]
weights: dict[str, float] = collections.defaultdict(float)
bias = 0.0
shuffler = random.Random(seed)
def chance(words: typing.Iterable[str]) -> float:
return 1 / (1 + math.exp(-max(-30.0, min(30.0, bias + sum(weights[word] for word in words)))))
for _ in range(EPOCHS):
shuffler.shuffle(data)
for words, interrupt in data:
error = chance(words) - interrupt
bias -= RATE * error
for word in words:
weights[word] -= RATE * (error + DECAY * weights[word])
return lambda text: chance(words_of(text) & vocabulary)
def averaged(samples: typing.Sequence[Sample]) -> typing.Callable[[str], float]:
"""The mean chance of SEEDS regressions that differ only in the order they shuffle the samples."""
regressions = [logistic(samples, seed) for seed in range(SEEDS)]
return lambda text: sum(regression(text) for regression in regressions) / SEEDS
def classifier(samples: typing.Sequence[Sample]) -> Decider:
"""Finished where the chance of an interrupt is below one half and below that of every interrupt among the samples; interrupt where it is at least one half and above that of every other kind; otherwise the judge's model decides.
A sample's chance is the one a model trained on the other folds of the samples gives it, so the bounds don't rest on how well the model fits what it trained on. A bound is where the samples held no miss; that doesn't promise the next verdict holds none."""
interrupts = [found for found in samples if found.kind == INTERRUPTED]
if not interrupts or len(interrupts) == len(samples):
return lambda text: None
held_out = [(tested.kind, chance) for trained, tests in folds_of(samples, INNER_FOLDS) for chance, tested in zip(map(averaged(trained), (found.text for found in tests)), tests)]
below = min(chance for kind, chance in held_out if kind == INTERRUPTED)
above = max(chance for kind, chance in held_out if kind != INTERRUPTED)
chance = averaged(samples)
def decide(text: str) -> Kind | None:
found = chance(text)
if found < below and found < 0.5:
return FINISHED
return INTERRUPTED if found > above and found >= 0.5 else None
return decide
# Rules are fixed, and run on the whole archive; a learner trains on samples, and runs on samples it didn't train on.
RULES: dict[str, Method] = {'"?" rule': question_mark, "decision table": decision_table}
LEARNERS: dict[str, Method] = {"classifier": classifier}
def folds_of(samples: typing.Sequence[Sample], count: int) -> list[tuple[list[Sample], list[Sample]]]:
"""count folds of the samples, dealt in turn. Each fold is the samples to learn from, which are all those its test leaves out, and the samples to test on."""
return [([found for place, found in enumerate(samples) if place % count != fold], [found for place, found in enumerate(samples) if place % count == fold]) for fold in range(count)]
def evaluate(method: Method, trained: typing.Sequence[Sample], tested: typing.Sequence[Sample]) -> Counts:
"""How often the method, learning from trained, decided each kind for each archived kind of tested; None where it left the verdict to the judge."""
decide = method(trained)
return collections.Counter((found.kind, decide(found.text)) for found in tested)
def plain(kind: Kind) -> str:
return kind.removeprefix("Verdict: ")
def offline_report(model: str, samples: typing.Sequence[Sample], rules: typing.Mapping[str, Method], learners: typing.Mapping[str, Method], folds: int = FOLDS, skipped: int = 0) -> str:
"""samples are in the order the verdicts were judged, oldest first, so the latest fifth is the newest verdicts."""
kinds = collections.Counter(found.kind for found in samples)
lines = [f"Replayed {len(samples)} archived verdicts of {model} projects offline, without sending anything to an outside service. The archive gives them as {', '.join(f'{count} {plain(kind)}' for kind, count in sorted(kinds.items(), key=lambda each: plain(each[0])))}."]
if skipped:
lines.append(f"Skipped {skipped} verdicts whose transcript could not be read.")
for name, rule in rules.items():
found = evaluate(rule, [], samples)
lines += [result_line(f"{name}, on the whole archive", found), *decides_lines(f"{name}, on the whole archive", found)]
split = len(samples) - max(1, len(samples) // LATEST)
for name, learner in learners.items():
held_out = sum((evaluate(learner, trained, tested) for trained, tested in folds_of(samples, folds)), Counts())
latest = evaluate(learner, samples[:split], samples[split:])
lines += [result_line(f"{name}, on held-out folds", held_out), result_line(f"{name}, on the latest fifth after learning from the rest", latest), *decides_lines(f"{name}, on both tests", held_out + latest)]
return "\n".join(lines)
def result_line(how: str, found: Counts) -> str:
decided = collections.Counter({kind: sum(count for (_, said), count in found.items() if said == kind) for kind in {said for _, said in found if said}})
missed = sum(count for (archived, said), count in found.items() if archived == INTERRUPTED and said not in (None, INTERRUPTED))
parts = [f"{plain(kind)} {count}{wrong_kinds(kind, found)}" for kind, count in sorted(decided.items(), key=lambda each: plain(each[0]))]
return f"{how}: decided {sum(decided.values())} of {sum(found.values())}{': ' + ', '.join(parts) if parts else ''}. Missed interrupts: {missed}."
def wrong_kinds(decided: Kind, found: Counts) -> str:
"""The kinds the archive gives the verdicts that were decided as decided, where the archive gives another kind than decided."""
wrong = sorted(((plain(archived), count) for (archived, said), count in found.items() if said == decided and archived != decided), key=lambda each: each[0])
return f" (of these, archived {', '.join(f'{kind} {count}' for kind, count in wrong)})" if wrong else ""
def decides_lines(how: str, found: Counts) -> list[str]:
"""For finished and for unfinished that the decider decided at all: whether it decided no archived interrupt as that kind."""
lines = []
for kind in (FINISHED, UNFINISHED):
decided = sum(count for (_, said), count in found.items() if said == kind)
if decided and not found[(INTERRUPTED, kind)]:
lines.append(f"{how}, decides {plain(kind)} with no missed interrupt.")
elif decided:
lines.append(f"{how}, does not decide {plain(kind)} with no missed interrupt: it decided {found[(INTERRUPTED, kind)]} archived interrupt(s) as {plain(kind)}.")
return lines
+1 -1
View File
@@ -6,7 +6,7 @@ import typing
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, judge_run_at, task_of, UNFINISHED
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from rung_replay.search import Replay
from model_routing.ladder import Rung
+47 -7
View File
@@ -9,6 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
@@ -16,9 +17,9 @@ from text_files import compressed
from project_config.test_project_config import configured
from loop_effects.effects import Effects
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from judge_replay.archived_prompt import grounds_of
from loop_claude.cycle.judge import judge_archived, JUDGE_RULES, Rejected, TASK_HEADING, TRANSCRIPT_HEADING
from agent_cycle.judge import judge_archived, judge_rules, Rejected, TASK_HEADING, transcript_heading
from judge_replay import main
from rung_replay.search import Miss, Replay, Tried
from model_routing.ladder import Rung
@@ -158,6 +159,7 @@ class Main(unittest.TestCase):
code, out, err = self.run_main(["claude-opus-5-5"], reply)
self.assertEqual(code, 0, err)
self.assertEqual([prompt for prompt in self.prompts if f"writing it into {ANSWER_DESTINATIONS}," not in prompt], [])
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"),
@@ -175,6 +177,44 @@ class Main(unittest.TestCase):
# The replay shows the judge the whole transcript, with no step-up marked in it.
self.assertNotIn("[step]", self.prompts[0])
def test_offline_replays_every_verdict_through_the_code_deciders_without_calling_the_judge(self):
code, out, err = self.run_main(["claude-opus-5-5", "--offline"], unused)
self.assertEqual(code, 0, err)
self.assertEqual(self.calls, [])
self.assertIn("Replayed 2 archived verdicts of claude-opus-5-5 projects offline, without sending anything to an outside service. The archive gives them as 1 finished, 1 interrupt.", out)
self.assertIn("\"?\" rule, on the whole archive: decided 2 of 2: finished 2 (of these, archived interrupt 1). Missed interrupts: 1.", out)
folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z"
self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out)
def test_offline_exits_1_where_no_transcript_can_be_read(self):
for path in (self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1").glob("*.jsonl"):
path.unlink()
code, out, err = self.run_main(["claude-opus-5-5", "--offline"], unused)
self.assertEqual((code, out), (1, ""))
self.assertEqual(err.splitlines()[-1], "judge-replay: no archived verdict has a transcript that can be read")
def test_offline_skips_each_verdict_whose_transcript_cannot_be_read_and_says_how_many_on_stderr_and_in_the_report(self):
kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1"
(kept / "t2.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:02Z {FINISHED}\n\nEvidence:\n> e\n")
(kept / "t0.jsonl").unlink()
code, out, err = self.run_main(["claude-opus-5-5", "--offline"], unused)
self.assertEqual(code, 0)
self.assertEqual(len(err.splitlines()), 2)
self.assertTrue(all(line.startswith("judge-replay: skipped a verdict: could not read the transcript ") for line in err.splitlines()))
self.assertIn("Replayed 1 archived verdicts of claude-opus-5-5 projects offline", out)
self.assertIn("Skipped 2 verdicts whose transcript could not be read.", out)
def test_offline_keeps_its_report_in_the_same_folder_wherever_the_flag_stands(self):
code, out, err = self.run_main(["--offline", "claude-opus-5-5"], unused)
self.assertEqual(code, 0, err)
folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z"
self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out)
def test_offline_says_the_usage_on_arguments_that_name_no_model(self):
code, out, err = self.run_main(["--offline"], unused)
self.assertEqual((code, out), (1, ""))
self.assertEqual(err, "judge-replay: cannot read the arguments --offline; usage: judge-replay <model> [--offline]; <model> is a model on the routing ladder\n")
def test_keeps_each_run_and_the_printed_report_in_one_folder_of_the_archive_beside_the_projects(self):
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
self.assertEqual(code, 0, err)
@@ -272,7 +312,7 @@ class Main(unittest.TestCase):
def test_prints_the_help(self):
code, out, _ = self.run_main(["-h"], unused)
self.assertEqual((code, out.splitlines()[2]), (0, "usage: judge-replay <model>"))
self.assertEqual((code, out.splitlines()[2]), (0, "usage: judge-replay <model> [--offline]"))
def test_the_launcher_prints_the_help(self):
ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True)
@@ -290,7 +330,7 @@ class Main(unittest.TestCase):
class JudgeArchivedRuns(unittest.TestCase):
"""judge_archived on a prompt as judge_prompt writes it: the premises, the task, the transcript the judge was shown, and the rules."""
PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{TRANSCRIPT_HEADING}Worker chose option B.\n[human] Use Postgres.\n\n{JUDGE_RULES}"
PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{transcript_heading(DRIVER)}Worker chose option B.\n[human] Use Postgres.\n\n{judge_rules(ANSWER_DESTINATIONS, DRIVER)}"
ENTRIES = [AssistantTurn(parts=(Text("Worker chose option B."),)), HumanTurn(text="Use Postgres."), LoopPrompt(text="Keep going.")]
def judged(self, prompt=PROMPT, **fields):
@@ -304,7 +344,7 @@ class JudgeArchivedRuns(unittest.TestCase):
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused)
grounds = grounds_of(prompt, self.ENTRIES)
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, effects)), cwds
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, DRIVER, effects)), cwds
def test_runs_in_the_projects_folder_and_stamps_the_verdict_with_the_entries_read(self):
verdict, cwds = self.judged()
@@ -323,11 +363,11 @@ class JudgeArchivedRuns(unittest.TestCase):
self.assertEqual((type(rejected), rejected.cost), (Rejected, 0.25))
def test_checks_neither_the_task_nor_the_rules_as_the_transcript_or_the_premises(self):
self.assertIsInstance(self.judged(evidence=JUDGE_RULES)[0], Rejected)
self.assertIsInstance(self.judged(evidence=judge_rules(ANSWER_DESTINATIONS, DRIVER))[0], Rejected)
self.assertIsInstance(self.judged(answer="Do it.", question="Which?")[0], Interrupt)
def test_splits_the_prompt_at_the_first_transcript_heading(self):
quoting = self.PROMPT.replace("Worker chose", f"Quoted: {TRANSCRIPT_HEADING}Worker chose", 1)
quoting = self.PROMPT.replace("Worker chose", f"Quoted: {transcript_heading(DRIVER)}Worker chose", 1)
self.assertIsInstance(self.judged(quoting, evidence="Quoted:")[0], Unfinished)
def test_splits_the_prompt_at_the_first_task_heading(self):
+190
View File
@@ -0,0 +1,190 @@
import collections
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
from claude_code.entries import AssistantTurn, HumanTurn, Text, ToolCall
from judge_replay.offline import averaged, classifier, decision_table, evaluate, final_message, folds_of, LEARNERS, logistic, offline_report, question_mark, RULES, Sample, words_of
def turn(*parts):
return AssistantTurn(parts=parts)
def sample(kind, text):
return Sample(kind, text)
class FinalMessage(unittest.TestCase):
def test_is_the_text_of_the_workers_last_turn_that_has_any(self):
entries = [turn(Text("first")), HumanTurn(text="ok"), turn(Text("Done. Merged."), ToolCall("1", "Bash", {})), turn(ToolCall("2", "Bash", {}))]
self.assertEqual(final_message(entries), "Done. Merged.")
def test_joins_the_texts_of_one_turn_on_separate_lines_and_leaves_out_blank_ones(self):
self.assertEqual(final_message([turn(Text("Merged."), Text(" "), Text("Which one?"))]), "Merged.\nWhich one?")
def test_is_empty_where_the_worker_wrote_no_text(self):
self.assertEqual(final_message([HumanTurn(text="hi"), turn(ToolCall("1", "Bash", {}))]), "")
class WordsOf(unittest.TestCase):
def test_is_each_lowercase_word_each_pair_of_neighbours_and_each_question_mark(self):
self.assertEqual(words_of("Which one? Yes"), {"which", "one", "?", "yes", "which one", "one ?", "? yes"})
class QuestionMark(unittest.TestCase):
def test_decides_interrupt_on_a_question_mark_and_finished_on_none(self):
decide = question_mark([])
self.assertEqual(decide("Which one?"), INTERRUPTED)
self.assertEqual(decide("Merged."), FINISHED)
class DecisionTable(unittest.TestCase):
def test_reads_the_workers_asking_for_the_humans_answer_as_an_interrupt(self):
decide = decision_table([])
for text in ("My recommendation is option 1.", "Your call: merge now or wait.", "The PR stays unmerged.", "Tell me which."):
with self.subTest(text=text):
self.assertEqual(decide(text), INTERRUPTED)
def test_reads_a_merge_with_no_ask_and_no_release_to_cut_as_finished(self):
decide = decision_table([])
self.assertEqual(decide("PR 12 merged and the worktree is removed."), FINISHED)
self.assertIsNone(decide("PR 12 merged. Release 0.3.0 is ready to cut."))
def test_leaves_any_other_message_to_the_judge(self):
self.assertIsNone(decision_table([])("I stopped at the gate."))
class Logistic(unittest.TestCase):
def test_gives_a_message_with_no_learned_word_about_the_share_of_interrupts(self):
chance = logistic([sample(INTERRUPTED, "")] * 10 + [sample(FINISHED, "")] * 30, 0)
self.assertAlmostEqual(chance(""), 0.25, delta=0.05)
def test_learns_a_word_found_in_as_few_messages_as_the_minimum(self):
chance = logistic([sample(INTERRUPTED, "ask")] * 3 + [sample(FINISHED, "")] * 3, 0)
self.assertGreater(chance("ask"), chance(""))
def test_averaged_is_the_mean_of_the_regressions_that_shuffle_in_each_seed_order(self):
samples = [sample(INTERRUPTED if n % 3 else FINISHED, f"word{n % 4} ask" if n % 3 else f"word{n % 4}") for n in range(30)]
mean = sum(logistic(samples, seed)("ask") for seed in range(5)) / 5
self.assertAlmostEqual(averaged(samples)("ask"), mean)
class Classifier(unittest.TestCase):
def trained(self, extra=()):
asking = [sample(INTERRUPTED, f"I recommend option {n}; tell me which of the options you want") for n in range(12)]
done = [sample(FINISHED, f"merged pull request {n} and removed the worktree, no findings left") for n in range(12)]
return classifier([*asking, *done, *extra])
def test_decides_a_message_like_each_kind_it_learned(self):
decide = self.trained()
self.assertEqual(decide("I recommend option 3; tell me which you want"), INTERRUPTED)
self.assertEqual(decide("merged pull request 99 and removed the worktree, no findings left"), FINISHED)
def test_decides_finished_on_a_message_of_words_only_finished_verdicts_held(self):
self.assertEqual(self.trained()("merged pull request"), FINISHED)
def test_abstains_where_it_learned_no_interrupt_or_no_other_kind(self):
self.assertIsNone(classifier([sample(FINISHED, "merged")])("merged"))
self.assertIsNone(classifier([sample(INTERRUPTED, "which?")])("which?"))
self.assertIsNone(classifier([])("anything"))
def test_decides_no_finished_where_an_interrupt_it_learned_looks_like_one(self):
lookalike = "merged pull request 7 and removed the worktree, no findings left"
decide = self.trained([sample(INTERRUPTED, lookalike)])
self.assertNotEqual(decide(lookalike), FINISHED)
def test_abstains_where_a_lookalike_of_each_kind_sits_in_the_samples_of_the_other(self):
decide = self.trained([sample(INTERRUPTED, "merged pull request 7 and removed the worktree, no findings left"), sample(FINISHED, "I recommend option 7; tell me which of the options you want")])
for text in ("merged pull request", "I recommend option", "zzz qqq"):
with self.subTest(text=text):
self.assertIsNone(decide(text))
class Folds(unittest.TestCase):
def test_deals_samples_to_folds_in_turn_so_each_is_tested_once(self):
samples = [sample(FINISHED, str(n)) for n in range(7)]
dealt = folds_of(samples, 3)
self.assertEqual([[found.text for found in tested] for _, tested in dealt], [["0", "3", "6"], ["1", "4"], ["2", "5"]])
self.assertEqual([found.text for found in dealt[1][0]], ["0", "2", "3", "5", "6"])
class Evaluate(unittest.TestCase):
def test_counts_each_archived_kind_by_what_the_method_decided_or_abstained(self):
tested = [sample(FINISHED, "merged"), sample(INTERRUPTED, "merged"), sample(UNFINISHED, "stopped"), sample(ANSWERED, "Which?")]
found = evaluate(decision_table, [], tested)
self.assertEqual(found, collections.Counter({(FINISHED, FINISHED): 1, (INTERRUPTED, FINISHED): 1, (UNFINISHED, None): 1, (ANSWERED, INTERRUPTED): 1}))
class Report(unittest.TestCase):
def samples(self):
return [sample(FINISHED, "Merged."), sample(FINISHED, "Merged. Release 1.0.0 is ready to cut."), sample(INTERRUPTED, "I recommend merging."), sample(INTERRUPTED, "Merged.")]
def test_counts_what_a_rule_decided_on_the_whole_archive_and_missed_by_kind(self):
text = offline_report("claude-opus-5-5", self.samples(), {"decision table": decision_table}, {})
self.assertIn("Replayed 4 archived verdicts of claude-opus-5-5 projects offline, without sending anything to an outside service. The archive gives them as 2 finished, 2 interrupt.", text)
self.assertIn("decision table, on the whole archive: decided 3 of 4: finished 2 (of these, archived interrupt 1), interrupt 1. Missed interrupts: 1.", text)
self.assertIn("decision table, on the whole archive, does not decide finished with no missed interrupt: it decided 1 archived interrupt(s) as finished.", text)
def test_says_a_method_that_decided_a_kind_and_missed_no_interrupt_decides_that_kind(self):
text = offline_report("claude-opus-5-5", [sample(FINISHED, "Merged."), sample(INTERRUPTED, "I recommend merging.")], {"decision table": decision_table}, {})
self.assertIn("Missed interrupts: 0.", text)
self.assertIn("decision table, on the whole archive, decides finished with no missed interrupt.", text)
def test_runs_a_learner_once_for_each_fold_and_once_on_the_latest_fifth_and_a_rule_only_on_the_whole_archive(self):
samples = [sample(INTERRUPTED if n % 2 else FINISHED, "I recommend it" if n % 2 else "merged it") for n in range(20)]
text = offline_report("m", samples, {"rule": question_mark}, {"classifier": classifier}, folds=4)
self.assertIn("classifier, on held-out folds: decided", text)
self.assertIn("classifier, on the latest fifth after learning from the rest: decided", text)
self.assertIn("rule, on the whole archive: decided 20 of 20", text)
self.assertNotIn("rule, on held-out", text)
self.assertNotIn("rule, on the latest fifth", text)
def test_words_the_whole_report_line_by_line_with_the_wrong_kinds_by_name(self):
answers = {"f": FINISHED, "i1": FINISHED, "i2": FINISHED, "u": FINISHED, "q": None}
samples = [sample(FINISHED, "f"), sample(INTERRUPTED, "i1"), sample(INTERRUPTED, "i2"), sample(UNFINISHED, "u"), sample(ANSWERED, "q")]
text = offline_report("m", samples, {"rule": lambda trained: lambda said: answers[said]}, {})
self.assertEqual(text.splitlines(), [
"Replayed 5 archived verdicts of m projects offline, without sending anything to an outside service. The archive gives them as 1 finished, 2 interrupt, 1 quoted answer, 1 unfinished.",
"rule, on the whole archive: decided 4 of 5: finished 4 (of these, archived interrupt 2, unfinished 1). Missed interrupts: 2.",
"rule, on the whole archive, does not decide finished with no missed interrupt: it decided 2 archived interrupt(s) as finished.",
])
def test_says_a_method_that_decided_nothing_decided_0_and_names_no_kind(self):
text = offline_report("m", self.samples(), {"rule": lambda trained: lambda said: None}, {})
self.assertEqual(text.splitlines()[1:], ["rule, on the whole archive: decided 0 of 4. Missed interrupts: 0."])
def test_tests_the_latest_fifth_of_the_samples_after_learning_from_the_earlier_ones(self):
trained = []
def learner(samples):
trained.append(len(samples))
return lambda said: FINISHED
text = offline_report("m", [sample(FINISHED, str(n)) for n in range(7)], {}, {"learner": learner}, folds=2)
self.assertEqual(trained, [3, 4, 6])
self.assertEqual(text.splitlines()[-2:], ["learner, on the latest fifth after learning from the rest: decided 1 of 1: finished 1. Missed interrupts: 0.", "learner, on both tests, decides finished with no missed interrupt."])
def test_says_a_learner_that_missed_an_interrupt_on_either_test_does_not_decide_the_kind(self):
def learner(samples):
return lambda said: FINISHED if said == "miss" else None
samples = [sample(FINISHED, "ok")] * 4 + [sample(INTERRUPTED, "miss")]
text = offline_report("m", samples, {}, {"learner": learner}, folds=2)
self.assertEqual(text.splitlines()[-1], "learner, on both tests, does not decide finished with no missed interrupt: it decided 2 archived interrupt(s) as finished.")
def test_counts_the_verdicts_it_skipped_only_where_it_skipped_some(self):
self.assertNotIn("Skipped", offline_report("m", self.samples(), {}, {}))
self.assertIn("Skipped 2 verdicts whose transcript could not be read.", offline_report("m", self.samples(), {}, {}, skipped=2))
def test_the_shipped_methods_are_the_question_mark_rule_the_table_and_the_classifier(self):
self.assertEqual(list(RULES), ['"?" rule', "decision table"])
self.assertEqual(list(LEARNERS), ["classifier"])
if __name__ == "__main__":
unittest.main()