Archive each judge run's prompt and json reply beside the verdict it gave, and replay from the archived prompt
CI / tests (pull_request) Failing after 2m45s

This commit is contained in:
2026-11-16 23:42:36 +01:00
parent 5bb49dc623
commit e1d2eae7f4
14 changed files with 248 additions and 46 deletions
+23 -7
View File
@@ -9,6 +9,7 @@ from loop_effects.effects import Effects
from claude_code.entries import Entry, structured_output
from loop_claude import escalation_mark
from failure import Failure
from transcript_archive.judge_run import JudgeRun
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from claude_code.transcript import human_answers
from loop_claude.quotes import plain, verbatim
@@ -64,6 +65,8 @@ FINISHED_RULES = (
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
# Opens the transcript in the prompt; the premises, the records and the task come before it, the rules after the transcript.
TRANSCRIPT_HEADING = "What the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
@dataclasses.dataclass(frozen=True)
@@ -94,10 +97,15 @@ JUDGE_SCHEMA = {
@dataclasses.dataclass(frozen=True)
class Rejected(Failure):
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json, and cost is what the run cost in dollars, 0 where its reply records none."""
reply: str
"""A judge reply loop-claude rejected: reason says why, run holds the prompt and the reply, and cost is what the run cost in dollars, 0 where its reply records none."""
run: JudgeRun
cost: float = 0.0
@property
def reply(self) -> str:
"""The reply as json."""
return json.dumps(self.run.reply, ensure_ascii=False)
class Grounds(typing.NamedTuple):
"""The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order."""
@@ -155,6 +163,14 @@ def judge_once(root: str, brief: Brief, rung: Rung, effects: Effects) -> Verdict
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(brief.entries))
def judge_archived(root: str, prompt: str, entries: list[Entry], rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on a prompt the archive kept from an earlier run, as judge-replay replays it: the judge reads what it read then, and its quotes are checked against that prompt's own text, in place of the records of today. The prompt's rules count as part of the transcript, a slack that lets an evidence quote the rules pass."""
head, _, shown = prompt.partition(TRANSCRIPT_HEADING)
grounds = Grounds(shown, escalation_mark.after_mark(entries, 0), head, tuple(human_answers(entries, typed_answer)))
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
return verdict if isinstance(verdict, Failure | Limited) else escalation_mark.stamped(verdict, len(entries))
def judge_args(rung: Rung) -> list[str]:
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
# No tools, so the verdict rests on the transcript grounded() checks it against.
@@ -172,14 +188,14 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
return reply
output = structured_output(reply)
verdict = verdict_from(output)
replied = json.dumps(reply, ensure_ascii=False)
run = JudgeRun(prompt, reply)
cost = cost_of(reply)
if isinstance(verdict, Failure):
return Rejected(verdict.reason, replied, cost)
return Rejected(verdict.reason, run, cost)
checked = quotes_checked(verdict, grounds)
if isinstance(checked, Failure):
return Rejected(checked.reason, replied, cost)
return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed)))
return Rejected(checked.reason, run, cost)
return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed), run))
def reversal_of(output: object, typed: tuple[str, ...]) -> str:
@@ -256,7 +272,7 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
f"From the goals file, {brief.premises}\n\n"
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{brief.records or 'none'}\n\n"
f"The task the worker was given:\n{brief.task}\n\n"
"What the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\n"
f"{TRANSCRIPT_HEADING}"
)
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
transcript = escalation_mark.transcript(brief.entries, brief.escalated_at, typed_answer)
+12 -11
View File
@@ -3,6 +3,7 @@ import pathlib
import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, to_the_human, transition, TypedAnswer, WorkerRan, Working
from transcript_archive.judge_run import JudgeRun
from transcript_archive.write import archive
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
from loop_claude.cycle.judge import Brief, judge, Rejected
@@ -98,9 +99,9 @@ def archived_stop(project_archive: pathlib.Path, session: Session, task: str, ro
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects) -> Failure | None:
def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects, judge_run: JudgeRun | None = None) -> Failure | None:
"""transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it."""
return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects))
return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run)
def judge_of(cycle: Cycle) -> Rung:
@@ -167,7 +168,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
if isinstance(annotation, Failure):
return Stop(1, annotation.reason)
stepped = ruling_step_up(cycle, verdict)
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped):
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped, verdict.judged.run):
return Stop(1, failure.reason)
return Ruled(verdict, stepped.after if stepped else None)
@@ -187,13 +188,13 @@ def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judg
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> str:
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from the premises or the records."""
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, annotation)
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation, judge_run=ruling.judged.run)
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, annotation, ruling.judged.run)
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects):
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost, rejected.run), cycle.effects, rejected.run):
return Stop(1, unkept.reason)
return None
@@ -211,9 +212,9 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
return HumanTyped(TypedAnswer(ruling.question, answer))
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None, judge_run: JudgeRun | None) -> Failure | None:
"""Archives the outcome of a ruling and the judge run that gave it, then the step-up it made, if it made one. The first failure is returned."""
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects, judge_run):
return failure
return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects)
@@ -236,8 +237,8 @@ def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) ->
annotation = entries if isinstance(entries, Failure) else annotation_of(cycle, transcript_path, entries, verdict.judged)
if isinstance(annotation, Failure):
return Stop(1, annotation.reason)
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, annotation) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, annotation)
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, annotation, verdict.judged.run) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, annotation, verdict.judged.run)
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects, verdict.judged.run):
return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
return Stop(1, failure.reason)
+3 -1
View File
@@ -342,7 +342,9 @@ class Checkout:
for archived in (copy, kept):
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
outcomes[copy.read_text()] = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE)
configured = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE)
# The judge's run is named by the hash of its prompt, which test_loop_claude.py checks.
outcomes[copy.read_text()] = re.sub(r"^Judge run: judge/[0-9a-f]{64}\.json\n", "", configured, flags=re.MULTILINE)
return outcomes
+31 -1
View File
@@ -174,6 +174,9 @@ def ran(stdout="", code=0, stderr=""):
return subprocess.CompletedProcess([], code, stdout, stderr)
JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE)
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""):
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed}
return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})}))
@@ -289,7 +292,8 @@ class Cycles(unittest.TestCase):
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", plan=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
"""Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt: the tests of the judge's runs check them."""
return sorted(JUDGE_RUN_LINE.sub("", path.read_text()) for path in self.archive.glob("*/*.outcomes.md"))
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
@@ -383,6 +387,32 @@ Worker: {OFF_LADDER}
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_archives_each_judge_runs_prompt_and_reply_beside_the_rejection_interrupt_and_verdict_it_gave(self):
rejected, interrupted, finished = ran(json.dumps({"structured_output": {"interrupt": False}})), judged("interrupt", cost=0.25), judged("finished")
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[rejected, interrupted, finished], inputs=["Use B."])
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
prompts = [stdin for args, stdin in fake.made("claude")[:3]]
[chunk] = self.archive.iterdir()
kept = "\n".join(path.read_text() for path in sorted(chunk.glob("*.outcomes.md"), key=lambda path: path.stat().st_mtime_ns))
named = re.findall(r"^Judge run: (judge/[0-9a-f]{64}\.json)$", kept, re.MULTILINE)
self.assertEqual(len(named), 3, kept)
runs = [json.loads((chunk / name).read_text()) for name in named]
self.assertEqual([found["prompt"] for found in runs], prompts)
self.assertEqual([found["reply"] for found in runs], [json.loads(reply.stdout) for reply in (rejected, interrupted, finished)])
self.assertEqual(sorted(path.name for path in (chunk / "judge").iterdir()), sorted(name.removeprefix("judge/") for name in named))
def test_stops_when_a_judge_run_cannot_be_archived(self):
self.archive.mkdir(parents=True)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
def replace_file(path, data):
return Failure("disk full") if "/judge/" in str(path) else real_replace_file(path, data)
real_replace_file = write.replace_file
with unittest.mock.patch("transcript_archive.write.replace_file", replace_file):
stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop.code, 1)
self.assertRegex(stop.reason, r"^could not archive the transcript: .*/judge/[0-9a-f]{64}\.json: disk full$")
def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self):
for first, then, inputs in (
(judged("interrupt", cost=0.25), judged("finished"), ["Use B."]),
+3
View File
@@ -2,6 +2,7 @@
import dataclasses
from claude_code.tokens import Tokens
from transcript_archive.judge_run import JudgeRun
@dataclasses.dataclass(frozen=True)
@@ -22,6 +23,8 @@ class Judged:
tokens: Tokens = Tokens()
# The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote.
reversed: str = ""
# The prompt it read and its reply, which the archive keeps beside the verdict. Left out of comparisons and reprs, so that equal verdicts stay equal whatever prompt they came from.
run: JudgeRun | None = dataclasses.field(default=None, compare=False, repr=False)
@dataclasses.dataclass(frozen=True)