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
+4
View File
@@ -3,6 +3,7 @@
<archive root>/<project key>/<chunk>/<sha256>.jsonl
<archive root>/<project key>/<chunk>/<sha256>.outcomes.md
<archive root>/<project key>/<chunk>/session/...
<archive root>/<project key>/<chunk>/judge/<sha256>.json
- The archive root is $LOOP_CLAUDE_TRANSCRIPTS, or ~/.claude/loop-claude-transcripts (location.archive_root).
- The project key is the checkout's path relative to ~/code, or to / outside it (project_key.project_key).
@@ -19,6 +20,9 @@
grew from it. A file Claude Code rewrote whole lands beside its copy as <name>.<hash of its content>
(write.copy_for).
- judge/ holds each judge run an outcome names on its `Judge run:` line: the prompt the judge read and claude's
json reply, named by the hash of that content (judge_run.JudgeRun). judge-replay reads the prompt back.
write.archive writes the layout, at every interrupt and as every cycle ends. read.py and the tools that
measure finished chunks read it.
"""
+32
View File
@@ -0,0 +1,32 @@
import dataclasses
import hashlib
import json
import pathlib
from failure import Failure
# The folder of a chunk's judge runs, beside its transcript copies.
FOLDER = "judge"
@dataclasses.dataclass(frozen=True)
class JudgeRun:
"""The prompt a judge run read and claude's json reply to it. The judge has no tools and one turn, so these two are its whole transcript."""
prompt: str
reply: dict
def content(self) -> bytes:
return json.dumps({"prompt": self.prompt, "reply": self.reply}, ensure_ascii=False, indent=1).encode()
@property
def file(self) -> str:
"""Where the archive keeps the run, relative to its chunk's folder. The name is the hash of the content, so a run archived twice is kept once."""
return f"{FOLDER}/{hashlib.sha256(self.content()).hexdigest()}.json"
@staticmethod
def read(path: pathlib.Path) -> "JudgeRun | Failure":
try:
kept = json.loads(path.read_text(encoding="utf-8"))
return JudgeRun(kept["prompt"], kept["reply"])
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read the archived judge run {path}: {failure}")
+26 -13
View File
@@ -5,6 +5,7 @@ from model_routing.prices import PRICES
from text_files.markdown_text import quoted
from text_files.utc_stamp import STAMPED
from claude_code.tokens import Tokens
from transcript_archive.judge_run import JudgeRun
from model_routing.route import WorkerLine
TASK = "Task: "
@@ -29,6 +30,9 @@ JUDGE = "Judge: "
# What the judge's run cost, in dollars, on the line after JUDGE; absent where the verdict recorded none.
JUDGE_COST = "Judge cost: "
JUDGE_COST_AT = re.compile(rf"^{re.escape(JUDGE)}(.+)\n{re.escape(JUDGE_COST)}([0-9.]+)$", re.MULTILINE)
# The judge run the verdict came from, as a path in the chunk's folder (judge_run.JudgeRun.file), on the line after the judge's rung and cost; absent where the archive kept none.
JUDGE_RUN = "Judge run: "
JUDGE_RUN_AT = re.compile(rf"^{re.escape(JUDGE_RUN)}(.+)$", re.MULTILINE)
# The claude-config release and commit that ran the cycle, on the line before JUDGE, such as `Config: v0.8.0 (<sha>)`.
@@ -84,9 +88,18 @@ def spent_stamps(outcomes: str) -> list[str]:
return [stamp for stamp, outcome in each_outcome(outcomes) if f"\n{SPENT}" in outcome]
def judge_lines(judge: str, judge_cost: float) -> str:
"""The judge's rung, and what its run cost where that is known."""
return f"{JUDGE}{judge}" + (f"\n{JUDGE_COST}{judge_cost:.4f}" if judge_cost else "")
def judge_lines(judge: str, judge_cost: float, judge_run: JudgeRun | None) -> str:
"""The judge's rung, what its run cost where that is known, and the archived run where there is one."""
return f"{JUDGE}{judge}" + (f"\n{JUDGE_COST}{judge_cost:.4f}" if judge_cost else "") + (f"\n{JUDGE_RUN}{judge_run.file}" if judge_run else "")
def judge_run_at(outcomes: str, stamp: str) -> str | None:
"""The path of the judge run that the outcome stamped stamp names; None where it names none."""
for found, outcome in each_outcome(outcomes):
# The last such line: an interrupt's question, which comes first, may hold one.
if found == stamp and (named := JUDGE_RUN_AT.findall(outcome)):
return named[-1]
return None
def judge_costs(outcomes: str) -> list[tuple[str, float]]:
@@ -98,31 +111,31 @@ def escalation_block(escalation: str) -> str:
return f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
def finished(worker: WorkerLine, evidence: str, judge: str, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
def finished(worker: WorkerLine, evidence: str, judge: str, judge_cost: float = 0.0, annotation: Annotation = Annotation(), judge_run: JudgeRun | None = None) -> str:
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{annotation_lines(annotation)}{judge_lines(judge, judge_cost, judge_run)}\n{WORKER}{worker}"
def unfinished(worker: WorkerLine, evidence: str, judge: str, escalation: str, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
def unfinished(worker: WorkerLine, evidence: str, judge: str, escalation: str, judge_cost: float = 0.0, annotation: Annotation = Annotation(), judge_run: JudgeRun | None = None) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none."""
escalated = escalation_block(escalation)
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost, judge_run)}\n{WORKER}{worker}"
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation(), judge_run: JudgeRun | None = None) -> str:
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the line naming the route the worker ran on until the interrupt."""
escalated = escalation_block(escalation)
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost, judge_run)}\n{WORKER}{worker}"
def answered(*, question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation()) -> str:
def answered(*, question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0, annotation: Annotation = Annotation(), judge_run: JudgeRun | None = None) -> str:
"""escalation and worker are as on interrupted. Every parameter is keyword-only, since a swap of two str ones would still type-check."""
escalated = escalation_block(escalation)
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{annotation_lines(annotation)}{judge_lines(judge, judge_cost, judge_run)}\n{WORKER}{worker}"
def rejected(why: str, reply: str, judge: str, judge_cost: float = 0.0) -> str:
def rejected(why: str, reply: str, judge: str, judge_cost: float = 0.0, judge_run: JudgeRun | None = None) -> str:
"""A judge reply loop-claude rejected, with the reason and the reply as json."""
return f"{REJECTED}: {why}\n\nReply:\n{quoted(reply)}\n\n{judge_lines(judge, judge_cost)}"
return f"{REJECTED}: {why}\n\nReply:\n{quoted(reply)}\n\n{judge_lines(judge, judge_cost, judge_run)}"
def stepped_up(worker: WorkerLine) -> str:
@@ -1,6 +1,7 @@
import contextlib
import hashlib
import io
import json
import pathlib
import sys
import tempfile
@@ -11,6 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.project_key import checkout_of, project_key
from failure import Failure
from transcript_archive import outcomes, read, write
from transcript_archive.judge_run import JudgeRun
from transcript_archive.location import project_archive
from text_files.utc_stamp import utc
@@ -31,6 +33,49 @@ class Archive(unittest.TestCase):
self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: m\n")
class JudgeRuns(unittest.TestCase):
judged = JudgeRun("The prompt.", {"structured_output": {"finished": True}, "total_cost_usd": 0.5})
def test_a_run_is_kept_once_in_the_chunk_folder_under_the_hash_of_its_content(self):
with tempfile.TemporaryDirectory() as root:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
with contextlib.redirect_stderr(io.StringIO()):
for offset in (0, 1):
outcome = outcomes.finished("w", "merged", "j", judge_run=self.judged)
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcome, NOW + offset, judge_run=self.judged))
(folder,) = kept.glob("*/")
(file,) = folder.glob("judge/*")
self.assertEqual(file, folder / self.judged.file)
self.assertEqual(file.name, hashlib.sha256(file.read_bytes()).hexdigest() + ".json")
self.assertEqual(json.loads(file.read_text()), {"prompt": "The prompt.", "reply": {"structured_output": {"finished": True}, "total_cost_usd": 0.5}})
self.assertEqual(JudgeRun.read(file), self.judged)
def test_names_the_run_on_the_line_after_the_judge_lines_and_reads_the_name_back(self):
outcome = outcomes.finished("w", "e", "j", judge_cost=0.5, judge_run=self.judged)
self.assertEqual(outcome, f"Verdict: finished\n\nEvidence:\n> e\n\nJudge: j\nJudge cost: 0.5000\nJudge run: {self.judged.file}\nWorker: w")
self.assertEqual(outcomes.rejected("why", "{}", "j", judge_run=self.judged), f"Judge reply rejected: why\n\nReply:\n> {{}}\n\nJudge: j\nJudge run: {self.judged.file}")
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcome}\n"), [(utc(NOW), "w")])
self.assertEqual(outcomes.judge_costs(f"{utc(NOW)} {outcome}\n"), [("j", 0.5)])
kept = f"Task: Do it.\n\n{utc(NOW)} {outcomes.stopped('w', 'Ctrl-C')}\n\n{utc(NOW + 1)} {outcome}\n\n{utc(NOW + 2)} {outcomes.finished('w', 'e', 'j')}\n"
self.assertEqual(outcomes.judge_run_at(kept, utc(NOW + 1)), self.judged.file)
self.assertIsNone(outcomes.judge_run_at(kept, utc(NOW + 2)))
def test_writes_no_outcome_where_the_run_cannot_be_kept(self):
with tempfile.TemporaryDirectory() as root:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "x"), NOW))
(folder,) = kept.glob("*/")
(folder / "judge").write_text("a file where the folder should be")
failure = write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "e", "j", judge_run=self.judged), NOW + 1, judge_run=self.judged)
self.assertIsInstance(failure, Failure)
self.assertNotIn("Verdict: finished", next(folder.glob("*.outcomes.md")).read_text())
class CopyFor(unittest.TestCase):
def test_skips_a_version_already_kept_beside_its_copy(self):
with tempfile.TemporaryDirectory() as temp:
+18 -2
View File
@@ -4,6 +4,7 @@ import pathlib
import typing
from transcript_archive.location import chunk_folder, outcomes_of
from transcript_archive.judge_run import JudgeRun
from failure import Failure
from text_files.file_writes import make_private, replace_file
from claude_code.session import session_files
@@ -11,8 +12,8 @@ from transcript_archive.outcomes import TASK
from text_files.utc_stamp import utc
def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None) -> Failure | None:
"""Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new. Where a new copy lands, note is told where."""
def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None, judge_run: JudgeRun | None = None) -> Failure | None:
"""Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new. Where a new copy lands, note is told where. A judge_run the outcome names is kept first, so the outcome never names a run the archive lacks."""
try:
with open(path, "rb") as handle:
raw = handle.read()
@@ -23,6 +24,8 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a
for sibling in session_files(path):
if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))):
return unkept
if judge_run and (unkept := keep_judge_run(folder, judge_run)):
return unkept
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
outcomes = outcomes_of(copy)
stamped = f"{utc(at)} {outcome}"
@@ -36,6 +39,19 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a
return None
def keep_judge_run(folder: pathlib.Path, run: JudgeRun) -> Failure | None:
kept = folder / run.file
if kept.exists():
return None
try:
make_private(kept.parent)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
if unwritten := replace_file(kept, run.content()):
return unarchived(kept, unwritten.reason)
return None
def unarchived(where: object, why: str | None) -> Failure:
return Failure(f"could not archive the transcript: {where}: {why}")