Archive each review-replay and judge-replay run's transcript beside its result
CI / tests (pull_request) Failing after 2m52s

This commit is contained in:
2026-11-17 01:49:49 +01:00
parent f2a4347d78
commit 5aabbc87bf
11 changed files with 221 additions and 17 deletions
+48
View File
@@ -0,0 +1,48 @@
"""Keeps what judge-replay and review-replay ran beside what they printed, so a replay that decided a rung can be read again, re-priced or re-scored once the decision is questioned: docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`."""
import dataclasses
import hashlib
import json
import pathlib
import re
import sys
import time
from claude_code.reply import Claude
from loop_effects.effects import Effects
# The run's file starts with this line: what claude read and where, none of which its stream carries. Its type is none claude writes.
HEADER = "replay_run"
RESULT = "result.md"
def replay_folder(root: pathlib.Path, tool: str, argv: list[str], now: float) -> pathlib.Path:
"""Where a replay of tool run with argv at now keeps its runs and its result, under the archive at root; no reader of loop-claude's archive takes a folder there for a project's."""
name = "-".join([tool, *(arg.lstrip("-") for arg in argv), time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(now))])
return root / "replays" / re.sub(r"[^A-Za-z0-9._-]", "_", name)
def archiving(effects: Effects, folder: pathlib.Path) -> Effects:
"""effects whose claude also writes each run into folder: a line with the arguments, the working directory and the prompt, then the stream claude printed. A run is kept whether it failed or not, and once where it repeats a run; a folder that cannot be written is said on stderr and costs the replay nothing."""
claude = effects.claude
def run(args: list[str], cwd: str, prompt: str):
proc = claude(args, cwd, prompt)
content = "\n".join([json.dumps({"type": HEADER, "args": args, "cwd": cwd, "prompt": prompt}, ensure_ascii=False), proc.stdout])
try:
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
(folder / f"{hashlib.sha256(content.encode()).hexdigest()}.jsonl").write_text(content, encoding="utf-8")
except OSError as failure:
print(f"could not keep the run in {folder}: {failure}", file=sys.stderr, flush=True)
return proc
return dataclasses.replace(effects, claude=run)
def print_report(folder: pathlib.Path, report: str) -> None:
"""Prints the report a replay ends with, and keeps it in folder, beside the runs."""
print(report)
try:
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
(folder / RESULT).write_text(report + "\n", encoding="utf-8")
except OSError as failure:
print(f"could not keep the result in {folder}: {failure}", file=sys.stderr, flush=True)
+73
View File
@@ -1,15 +1,20 @@
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 rung_replay.archive import archiving, print_report, replay_folder
from rung_replay.command import down_from
from failure import Failure
from rung_replay.search import first_reply, Miss, Replay, replayed, Tried
from claude_code.reply import Limited
from loop_effects.effects import Effects
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.ladder import Rung
@@ -79,5 +84,73 @@ class DownFrom(unittest.TestCase):
self.assertEqual(down_from(LADDER, REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
def effects(claude):
return Effects(claude=claude, **{name: unused for name in Effects.__dataclass_fields__ if name != "claude"})
def unused(*_):
raise AssertionError("not called")
class ArchivedRuns(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "replays" / "tool-1"
def run_archived(self, replies):
return archiving(effects(lambda args, cwd, prompt: replies.pop(0)), self.folder).claude
def kept(self):
return sorted(self.folder.glob("*.jsonl"))
def test_keeps_each_run_as_the_prompt_it_read_then_the_stream_it_printed_and_returns_claudes_process_as_it_was(self):
stream = '{"type": "system"}\n{"type": "result", "result": "ok"}\n'
proc = subprocess.CompletedProcess(["claude"], 0, stream, "")
run = self.run_archived([proc, subprocess.CompletedProcess(["claude"], 0, stream, "")])
self.assertIs(run(["-p", "--agent", "prose-reviewer"], "/clone", "Review it."), proc)
run(["-p", "--agent", "prose-reviewer"], "/clone", "Review that.")
first, second = (path.read_text(encoding="utf-8").splitlines() for path in self.kept())
prompts = sorted((json.loads(lines[0]) for lines in (first, second)), key=lambda header: header["prompt"])
self.assertEqual(prompts, [
{"type": "replay_run", "args": ["-p", "--agent", "prose-reviewer"], "cwd": "/clone", "prompt": prompt} for prompt in ("Review it.", "Review that.")
])
self.assertEqual(first[1:], stream.splitlines())
def test_keeps_a_run_that_failed_and_a_run_repeated_once(self):
failed = subprocess.CompletedProcess(["claude"], 1, "half a stream", "boom")
run = self.run_archived([failed, failed])
run([], "/r", "p")
run([], "/r", "p")
self.assertEqual(len(self.kept()), 1)
self.assertIn("half a stream", self.kept()[0].read_text(encoding="utf-8"))
def test_keeps_nothing_where_claude_did_not_start_and_says_where_it_could_not_keep_a_run(self):
def missing(args, cwd, prompt):
raise FileNotFoundError(2, "No such file or directory")
with self.assertRaises(FileNotFoundError):
archiving(effects(missing), self.folder).claude([], "/r", "p")
self.assertFalse(self.folder.exists())
# A file where the folder's parent should be.
self.folder.parent.parent.mkdir(exist_ok=True)
self.folder.parent.write_text("")
proc = subprocess.CompletedProcess(["claude"], 0, "{}", "")
err = io.StringIO()
with contextlib.redirect_stderr(err):
self.assertIs(self.run_archived([proc])([], "/r", "p"), proc)
self.assertIn(f"could not keep the run in {self.folder}: ", err.getvalue())
def test_prints_the_report_and_keeps_it_beside_the_runs(self):
out = io.StringIO()
with contextlib.redirect_stdout(out):
print_report(self.folder, "The report.")
self.assertEqual(out.getvalue(), "The report.\n")
self.assertEqual((self.folder / "result.md").read_text(encoding="utf-8"), "The report.\n")
def test_names_the_folder_by_the_tool_its_arguments_and_the_minute_in_utc_under_replays(self):
root = pathlib.Path("/archive")
self.assertEqual(replay_folder(root, "review-replay", ["stability", "claude-opus-5-5", "--omit-claude-md"], 1790000000.0), root / "replays" / "review-replay-stability-claude-opus-5-5-omit-claude-md-20260921T141320Z")
self.assertEqual(replay_folder(root, "judge-replay", ["a/b c"], 0.0), root / "replays" / "judge-replay-a_b_c-19700101T000000Z")
if __name__ == "__main__":
unittest.main()