From 5aabbc87bf98c9f03ca148269f98b10e8ef39f63 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 01:49:49 +0100 Subject: [PATCH 1/9] Archive each review-replay and judge-replay run's transcript beside its result --- README.md | 2 +- bin/claude_code/reply.py | 12 ++-- bin/claude_code/test_claude_code.py | 6 +- bin/judge_replay/main.py | 9 ++- bin/judge_replay/test_judge_replay.py | 12 +++- bin/review_replay/main.py | 9 ++- bin/review_replay/test_review_replay.py | 12 +++- bin/rung_replay/archive.py | 48 ++++++++++++++++ bin/rung_replay/test_rung_replay.py | 73 +++++++++++++++++++++++++ docs/decisions.md | 4 +- docs/reading-cost.md | 51 +++++++++++++++++ 11 files changed, 221 insertions(+), 17 deletions(-) create mode 100644 bin/rung_replay/archive.py diff --git a/README.md b/README.md index e1fdcc17..a22d9084 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts. - `command-patterns [] [--calls ]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls ` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys. - `deploy-release [--cut] []` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says. -- `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. +- `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. `judge-replay` and `review-replay` keep each run's prompt and stream, and the report they print, in a `replays/` folder of loop-claude's archive. - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. - `loop-claude ` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract. - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. diff --git a/bin/claude_code/reply.py b/bin/claude_code/reply.py index db2f6a1b..767ee3e2 100644 --- a/bin/claude_code/reply.py +++ b/bin/claude_code/reply.py @@ -1,4 +1,4 @@ -"""One `claude -p --output-format json` run, as loop-claude's judge and the replays start it.""" +"""One `claude -p --output-format stream-json` run, as loop-claude's judge and the replays start it.""" import dataclasses import subprocess import typing @@ -17,18 +17,18 @@ class Limited: said: str -# The json reply claude_reply parses; no persistence, so its runs stay out of the session picker; no permission prompt, as no one answers it. -HEADLESS = ["--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"] +# stream-json, whose last line claude_reply parses and whose every line a caller may keep as the run's transcript, which --no-session-persistence has Claude Code not write; -p needs --verbose with it. No permission prompt, as no one answers it. +HEADLESS = ["--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"] def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited: - """claude's json reply to `claude -p ` and HEADLESS, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a reply that is no json.""" + """claude's reply to `claude -p ` and HEADLESS, the result event that ends its stream, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a stream that ends in no json object.""" try: proc = claude(["-p", *args, *HEADLESS], cwd, prompt) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") - reply = json_object(proc.stdout) - # The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time. + reply = json_object(proc.stdout.strip().rpartition("\n")[2]) + # The result event names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time. if reply is not None and hit_limit(reply): return Limited(None, limit_said(reply)) if proc.returncode != 0: diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index 6e67a355..ebbe4de1 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -199,7 +199,11 @@ class ClaudeReply(unittest.TestCase): return subprocess.CompletedProcess(args, 0, "{}", "") reply.claude_reply(run, ["--tools", ""], "/r", "p", "the judge") - self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"], "/r", "p")]) + self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"], "/r", "p")]) + + def test_reads_the_reply_from_the_streams_last_line(self): + stream = "\n".join(json.dumps(event) for event in ({"type": "system", "subtype": "init"}, {"type": "assistant"}, {"type": "result", "result": "ok"})) + self.assertEqual(reply.claude_reply(self.claude((0, stream + "\n", "")), [], "/r", "p", "the judge"), {"type": "result", "result": "ok"}) def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self): self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"}) diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index f5035103..eb0b9291 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -5,7 +5,7 @@ usage: judge-replay 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 15 of each kind, finished, unfinished, interrupt and quoted answer. Where the archive kept the judge's own -prompt (docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run`), the +prompt (docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`), the replay hands the judge that prompt, which holds what the judge read then. For a verdict from before the archive kept it, the replay builds the prompt from the transcript copy beside the verdict, with the task, premises and records each project holds now. @@ -27,6 +27,8 @@ JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge. j 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. +Each run is kept with the report it ended in: `replays/--/` in loop-claude's archive holds a `.jsonl` file per run, its prompt then claude's stream, and `result.md`, the printed report. + Like the loop, it tries a judge three times running before it counts the reply as failed. 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, @@ -37,6 +39,7 @@ import typing 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 judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind @@ -75,12 +78,14 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff if not cases: return failed(TOOL, f"no archived verdicts of projects on {project.model} in {archive_root(home, env)}; run loop-claude on a project on that model first") cases = sample(cases, PER_KIND) + folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now()) + effects = archiving(effects, folder) reference = Rung(project.model, REFERENCE_EFFORT) # The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge. replay = replayed(cases, reference, down_from(ladder, project, ladder.lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(ladder, project, reference)) if isinstance(replay, Limited): return limited_exit(TOOL, replay) - print(report(project.model, reference, cases, replay)) + print_report(folder, report(project.model, reference, cases, replay)) return 0 diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 7054e9de..6bd96aa8 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -139,7 +139,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - 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=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) + 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, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) @@ -174,6 +174,14 @@ 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_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) + folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-20260921T141320Z" + self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) + runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")] + self.assertEqual({run["prompt"] for run in runs}, set(self.prompts)) + def test_hands_the_judge_the_prompt_the_archive_kept_and_rebuilds_the_prompt_of_a_verdict_with_none(self): kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" prompt = "From the goals file, OLD premises\n\nThe records: none\n\nThe task the worker was given:\nDo it.\n\nWhat the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\nsaid Verdict: finished\n\nOLD rules" @@ -286,7 +294,7 @@ class JudgeArchivedRuns(unittest.TestCase): cwds.append(cwd) return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "") - 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=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) + 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, 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 diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index f5386cb2..6bd9bf1d 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -45,6 +45,8 @@ replay, and runs no SubagentStart hook there. So the replay without CLAUDE.md tu instruction files off in its settings and opens the prompt with what the hook hands a reviewer, and closes it with the header's line on the project principles. +Each run, the reviewer's tool calls included, is kept with the report it ended in: `replays/--/` in loop-claude's archive holds a `.jsonl` file per run, its prompt then claude's stream, and `result.md`, the printed report. + Like the loop, it tries claude three times running before it counts a reply as failed. A failed review or match leaves its round out, except on a rung below the project's, where it finds none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived @@ -56,6 +58,7 @@ import typing from transcript_archive.location import archive_root from review_replay.rounds import archived_rounds, Round, sample +from rung_replay.archive import archiving, print_report, replay_folder from rung_replay.command import arguments_or_exit, failed, limited_exit from review_replay.replay import codes_found, findings_replayed from review_replay.omit_comparison import compared @@ -89,11 +92,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff if not codes: return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find") chosen = sample(list(codes), LATEST) + folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now()) + effects = archiving(effects, folder) if without: report = compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare)) if isinstance(report, Limited): return limited_exit(TOOL, report) - print(report) + print_report(folder, report) return 0 def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited: @@ -105,7 +110,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds") if isinstance(recall, Limited): return limited_exit(TOOL, recall) - print(recall_report(reviewed, project, recall)) + print_report(folder, recall_report(reviewed, project, recall)) return 0 diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 32ed8595..eee7c86e 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -267,12 +267,22 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) return code, out.getvalue(), err.getvalue() + def test_keeps_each_reviewer_and_match_run_and_the_printed_report_in_one_folder_of_the_archive(self): + code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}) + self.assertEqual(code, 0, err) + folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "review-replay-stability-claude-opus-5-5-20260921T141320Z" + self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) + runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")] + # A run that repeats another word for word, as the fakes' do, is kept once. + self.assertEqual({run["prompt"] for run in runs if "--agent" in run["args"]}, {prompt for *_, prompt, _ in self.reviews}) + self.assertTrue(any("--json-schema" in run["args"] for run in runs)) + def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self): finds = iter(([0, 1], [0], [0, 1], [1])) code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)}) diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py new file mode 100644 index 00000000..54080e19 --- /dev/null +++ b/bin/rung_replay/archive.py @@ -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) diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 23a8b816..1731a684 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -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() diff --git a/docs/decisions.md b/docs/decisions.md index e0e58e3a..0b8fb771 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -182,9 +182,9 @@ Valid while `~/.claude` is a checkout of this repo. Valid while claude takes `--session-id` and resumes by it, and the human runs loop-claude where tmux is installed. -## loop-claude: the archive keeps the raw transcript and each judge run, and a failed archive stops the loop +## loop-claude: the archive keeps the raw transcript and each judge run, a failed archive stops the loop, and judge-replay and review-replay keep each run and their report under its replays/ folder -2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. The judge's runs are archived too, as `judge/.json` in the chunk's folder: the prompt it read and its json reply. Together they are its whole transcript, since it runs with no tools and one turn. A run is kept whole and deduplicated by hash, and the outcome of the verdict, interrupt or rejected reply it produced names it on a `Judge run:` line. Keeping it whole costs little: a prompt is at most `JUDGE_PROMPT_CHARS`, 400,000 characters. Measured 2026-11-17, the archive's 911 judge lines come to at most 0.36 GB of prompts, against 3.5 GB in its 1,211 transcript copies, the largest 23.4 MB. The judge is still priced from its `Judge cost:` line, which is claude's own total for the run, and the Spent block counts the live reply's tokens; the archived reply keeps its `usage` for a later reader, and nothing reads it back. `judge-replay` replays a verdict on its archived prompt where there is one. Valid while transcripts, and the judge's prompts, stay small enough to copy whole. +2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. The judge's runs are archived too, as `judge/.json` in the chunk's folder: the prompt it read and its json reply. Together they are its whole transcript, since it runs with no tools and one turn. A run is kept whole and deduplicated by hash, and the outcome of the verdict, interrupt or rejected reply it produced names it on a `Judge run:` line. Keeping it whole costs little: a prompt is at most `JUDGE_PROMPT_CHARS`, 400,000 characters. Measured 2026-11-17, the archive's 911 judge lines come to at most 0.36 GB of prompts, against 3.5 GB in its 1,211 transcript copies, the largest 23.4 MB. The judge is still priced from its `Judge cost:` line, which is claude's own total for the run, and the Spent block counts the live reply's tokens; the archived reply keeps its `usage` for a later reader, and nothing reads it back. `judge-replay` replays a verdict on its archived prompt where there is one. The replays keep their own runs, since each decides which rung a review pass or the judge may run on and so must stay checkable and re-priceable once the decision is questioned (2026-11-17, item 304): `replays/--/` in the archive's root holds one `.jsonl` per run, whether it failed or not, and `result.md`, the report the tool printed. A run's file is a header line with claude's arguments, working directory and prompt, then claude's stream-json output as printed, whose last line is the reply the replay read; a reviewer's tool calls and a judge's reply are in it. `claude_reply` takes stream-json in place of json for every caller, so the judge's runs are streams too, and its archive keeps the `JudgeRun` it did. A run that repeats another word for word is kept once. A folder that cannot be written is said on stderr and doesn't stop the replay. Valid while transcripts, and the judge's prompts, stay small enough to copy whole. ## loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 2574733f..f240976b 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2345,3 +2345,54 @@ Read most (opens and searches): - `bin/larv_review/test_larv_review.py` 3 - `bin/project_config/main.py` 3 - `bin/release_plan/formula.py` 3 + +## Reading cost, chunk 093397894c39, finished 2026-11-16T23:09:28Z + +71806 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/todo_item/main.py` 10 +- `bin/todo_item/test_todo_item.py` 10 +- `README.md` 5 +- `bin/project_config/test_project_config.py` 4 +- `bin/chunk_pr/main.py` 3 +- `CLAUDE.md` 2 +- `bin/plan_store/fakes.py` 2 +- `bin/plan_store/stores.py` 2 +- `bin/project_config/settings.py` 2 +- `docs/decisions.md` 2 + +## Reading cost, chunk 7cd3e6d607bf, finished 2026-11-16T23:18:20Z + +89486 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/deploy_release/test_deploy_release.py` 11 +- `bin/chunk_preflight/test_chunk_preflight.py` 5 +- `.gitignore` 4 +- `bin/chunk_preflight/gathered.py` 4 +- `bin/deploy_release/cut.py` 3 +- `bin/forge/pulls.py` 3 +- `docs/decisions.md` 3 +- `README.md` 2 +- `bin/chunk_pr/main.py` 2 +- `bin/chunk_preflight/main.py` 2 + +## Reading cost, chunk 080dc175f969, finished 2026-11-17T00:45:04Z + +139513 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/loop_claude/test_loop_claude.py` 13 +- `README.md` 8 +- `bin/loop_claude/cycle/run.py` 5 +- `bin/judge_replay/main.py` 4 +- `bin/loop_claude/cycle/judge.py` 4 +- `bin/judge_replay/test_judge_replay.py` 3 +- `bin/transcript_archive/outcomes.py` 3 +- `bin/transcript_archive/test_transcript_archive.py` 3 +- `skills/larv-review/SKILL.md` 3 +- `bin/loop_claude/loop/close.py` 2 -- 2.52.0 From cc519017172c3c54fb9b9001ad5ce892d7658d5a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 01:52:05 +0100 Subject: [PATCH 2/9] Sort the test's imports and type the archiving run --- bin/rung_replay/archive.py | 4 ++-- bin/rung_replay/test_rung_replay.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py index 54080e19..8b9f586c 100644 --- a/bin/rung_replay/archive.py +++ b/bin/rung_replay/archive.py @@ -4,10 +4,10 @@ import hashlib import json import pathlib import re +import subprocess 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. @@ -25,7 +25,7 @@ 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): + def run(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[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: diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 1731a684..ea92de86 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -11,10 +11,10 @@ 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 loop_effects.effects import Effects 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 -- 2.52.0 From 4c0378c2d0106e4a02187f58940b78e6e9ad5e3e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:09:27 +0100 Subject: [PATCH 3/9] Kill the archive's mode, encoding and report-failure mutants --- bin/rung_replay/test_rung_replay.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index ea92de86..96d32011 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -115,6 +115,11 @@ class ArchivedRuns(unittest.TestCase): ]) self.assertEqual(first[1:], stream.splitlines()) + def test_keeps_the_runs_private_and_the_prompt_readable(self): + self.run_archived([subprocess.CompletedProcess(["claude"], 0, "{}", "")])([], "/r", "Läs den.") + self.assertEqual(self.folder.stat().st_mode & 0o777, 0o700) + self.assertIn("Läs den.", self.kept()[0].read_text(encoding="utf-8")) + 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]) @@ -146,6 +151,15 @@ class ArchivedRuns(unittest.TestCase): self.assertEqual(out.getvalue(), "The report.\n") self.assertEqual((self.folder / "result.md").read_text(encoding="utf-8"), "The report.\n") + def test_says_on_stderr_where_it_could_not_keep_the_report_and_still_prints_it(self): + self.folder.parent.parent.mkdir(exist_ok=True) + self.folder.parent.write_text("") + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + print_report(self.folder, "The report.") + self.assertEqual(out.getvalue(), "The report.\n") + self.assertIn(f"could not keep the result in {self.folder}: ", err.getvalue()) + 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") -- 2.52.0 From 4f766f7ab2487faace00fee4de25550d495b9e0b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:17:50 +0100 Subject: [PATCH 4/9] Kill the report folder's mode mutant --- bin/rung_replay/test_rung_replay.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 96d32011..78fcd710 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -150,6 +150,7 @@ class ArchivedRuns(unittest.TestCase): 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") + self.assertEqual(self.folder.stat().st_mode & 0o777, 0o700) def test_says_on_stderr_where_it_could_not_keep_the_report_and_still_prints_it(self): self.folder.parent.parent.mkdir(exist_ok=True) -- 2.52.0 From 5d10871ab501109f0e9c91f8ebc18c6707b8ca73 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:18:36 +0100 Subject: [PATCH 5/9] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20no=20findin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From c7248165db01c5668cbff95a0ebfdb582723fbc6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:33:04 +0100 Subject: [PATCH 6/9] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20the=20comme?= =?UTF-8?q?nt=20on=20a=20usage=20limit's=20reset=20time=20says=20the=20str?= =?UTF-8?q?eam=20holds=20it,=20and=20the=20no-json=20message=20quotes=20th?= =?UTF-8?q?e=20last=20line=20only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/claude_code/reply.py | 11 ++++++----- bin/claude_code/test_claude_code.py | 7 +++++-- bin/loop_claude/test_black_box.py | 2 +- bin/rung_replay/archive.py | 2 +- bin/rung_replay/test_rung_replay.py | 2 +- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/bin/claude_code/reply.py b/bin/claude_code/reply.py index 767ee3e2..92130f67 100644 --- a/bin/claude_code/reply.py +++ b/bin/claude_code/reply.py @@ -17,22 +17,23 @@ class Limited: said: str -# stream-json, whose last line claude_reply parses and whose every line a caller may keep as the run's transcript, which --no-session-persistence has Claude Code not write; -p needs --verbose with it. No permission prompt, as no one answers it. +# --no-session-persistence keeps the runs out of the session picker, and Claude Code then writes no transcript; stream-json prints one, so a caller may keep it, and claude_reply reads the reply from its last line. -p needs --verbose with stream-json. No permission prompt, as no one answers it. HEADLESS = ["--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"] def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited: - """claude's reply to `claude -p ` and HEADLESS, the result event that ends its stream, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a stream that ends in no json object.""" + """claude's reply to `claude -p ` and HEADLESS, the result event that ends its stream, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a last line that isn't a json object.""" try: proc = claude(["-p", *args, *HEADLESS], cwd, prompt) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") - reply = json_object(proc.stdout.strip().rpartition("\n")[2]) - # The result event names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time. + last = proc.stdout.strip().rpartition("\n")[2] + reply = json_object(last) + # The result event names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time; the stream's rate_limit_event holds it as a time, which nothing reads here yet. if reply is not None and hit_limit(reply): return Limited(None, limit_said(reply)) if proc.returncode != 0: return Failure(proc.stderr.strip() or f"{who} exited {proc.returncode}") if reply is None: - return Failure(f"{who} printed no json reply; it printed: {proc.stdout.strip() or 'nothing'}") + return Failure(f"{who} printed no json reply; its last line was: {last or 'nothing'}") return reply diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index ebbe4de1..f012f115 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -205,10 +205,13 @@ class ClaudeReply(unittest.TestCase): stream = "\n".join(json.dumps(event) for event in ({"type": "system", "subtype": "init"}, {"type": "assistant"}, {"type": "result", "result": "ok"})) self.assertEqual(reply.claude_reply(self.claude((0, stream + "\n", "")), [], "/r", "p", "the judge"), {"type": "result", "result": "ok"}) + def test_a_stream_that_ends_in_no_json_names_only_its_last_line(self): + self.assertEqual(reply.claude_reply(self.claude((0, '{"type": "system"}\nWarning: bye\n', "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: Warning: bye")) + def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self): self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"}) - self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: Warning: hook said hi")) - self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: nothing")) + self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: Warning: hook said hi")) + self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; its last line was: nothing")) limit = json.dumps({"type": "result", "api_error_status": 429, "result": "You've hit your limit"}) self.assertEqual(reply.claude_reply(self.claude((1, limit, "")), [], "/r", "p", "the judge"), reply.Limited(None, "You've hit your limit")) self.assertEqual(reply.claude_reply(self.claude((2, "", " ")), [], "/r", "p", "the judge"), Failure("the judge exited 2")) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 8f5a8eb0..ffc0f683 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -699,7 +699,7 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.sleeps, [60, 60]) self.assertIn("retrying the judge in a minute: judge down", run.stderr) - self.assertIn("retrying the judge in a minute: the judge printed no json reply; it printed: nothing\n", run.stderr) + self.assertIn("retrying the judge in a minute: the judge printed no json reply; its last line was: nothing\n", run.stderr) self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string') def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self): diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py index 8b9f586c..07db1335 100644 --- a/bin/rung_replay/archive.py +++ b/bin/rung_replay/archive.py @@ -16,7 +16,7 @@ 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.""" + """The folder a replay of tool, run with argv at now, keeps its runs and its result in, under the archive at root. It holds no outcomes file, so no reader of loop-claude's archive takes it for a chunk'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) diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 78fcd710..72252265 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -161,7 +161,7 @@ class ArchivedRuns(unittest.TestCase): self.assertEqual(out.getvalue(), "The report.\n") self.assertIn(f"could not keep the result in {self.folder}: ", err.getvalue()) - def test_names_the_folder_by_the_tool_its_arguments_and_the_minute_in_utc_under_replays(self): + def test_names_the_folder_by_the_tool_its_arguments_and_the_second_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") -- 2.52.0 From 48e69063b8f0ea2b8332b7ed9e5e2da9bd3475f2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:33:12 +0100 Subject: [PATCH 7/9] =?UTF-8?q?Answer=20product-owner=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20a=20kept=20?= =?UTF-8?q?run's=20header=20records=20claude's=20exit=20code=20and=20stder?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/rung_replay/archive.py | 2 +- bin/rung_replay/test_rung_replay.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py index 07db1335..92ecc91f 100644 --- a/bin/rung_replay/archive.py +++ b/bin/rung_replay/archive.py @@ -27,7 +27,7 @@ def archiving(effects: Effects, folder: pathlib.Path) -> Effects: def run(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[str]: proc = claude(args, cwd, prompt) - content = "\n".join([json.dumps({"type": HEADER, "args": args, "cwd": cwd, "prompt": prompt}, ensure_ascii=False), proc.stdout]) + content = "\n".join([json.dumps({"type": HEADER, "args": args, "cwd": cwd, "prompt": prompt, "returncode": proc.returncode, "stderr": proc.stderr}, 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") diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 72252265..f22a5082 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -111,7 +111,7 @@ class ArchivedRuns(unittest.TestCase): 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.") + {"type": "replay_run", "args": ["-p", "--agent", "prose-reviewer"], "cwd": "/clone", "prompt": prompt, "returncode": 0, "stderr": ""} for prompt in ("Review it.", "Review that.") ]) self.assertEqual(first[1:], stream.splitlines()) @@ -126,7 +126,8 @@ class ArchivedRuns(unittest.TestCase): 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")) + kept = self.kept()[0].read_text(encoding="utf-8").splitlines() + self.assertEqual((json.loads(kept[0])["returncode"], json.loads(kept[0])["stderr"], kept[1]), (1, "boom", "half a stream")) def test_keeps_nothing_where_claude_did_not_start_and_says_where_it_could_not_keep_a_run(self): def missing(args, cwd, prompt): -- 2.52.0 From b8a1a13ad0ab0ff60b0f152471dfbbfef8a26c1f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:33:40 +0100 Subject: [PATCH 8/9] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20the=20help?= =?UTF-8?q?=20texts=20say=20where=20the=20runs=20go,=20the=20decision=20ge?= =?UTF-8?q?ts=20its=20own=20dated=20paragraph,=20and=20the=20comments=20re?= =?UTF-8?q?read?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- bin/claude_code/reply.py | 2 +- bin/judge_replay/main.py | 5 ++++- bin/review_replay/main.py | 5 ++++- bin/rung_replay/archive.py | 6 +++--- docs/decisions.md | 12 ++++++++++-- 6 files changed, 24 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a22d9084..cc050da9 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts. - `command-patterns [] [--calls ]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls ` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys. - `deploy-release [--cut] []` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says. -- `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. `judge-replay` and `review-replay` keep each run's prompt and stream, and the report they print, in a `replays/` folder of loop-claude's archive. +- `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. - `loop-claude ` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract. - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. @@ -219,7 +219,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. -- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. +- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. - `test_env.py` serves the tests. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. diff --git a/bin/claude_code/reply.py b/bin/claude_code/reply.py index 92130f67..3250478d 100644 --- a/bin/claude_code/reply.py +++ b/bin/claude_code/reply.py @@ -17,7 +17,7 @@ class Limited: said: str -# --no-session-persistence keeps the runs out of the session picker, and Claude Code then writes no transcript; stream-json prints one, so a caller may keep it, and claude_reply reads the reply from its last line. -p needs --verbose with stream-json. No permission prompt, as no one answers it. +# No persistence, so these runs stay out of the session picker; Claude Code then writes no transcript, so stream-json, which prints one, lets a caller keep it. claude_reply reads the reply from the stream's last line. -p needs --verbose with stream-json. No permission prompt, as no one answers it. HEADLESS = ["--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"] diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index eb0b9291..44d57d17 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -27,7 +27,10 @@ JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge. j 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. -Each run is kept with the report it ended in: `replays/--/` in loop-claude's archive holds a `.jsonl` file per run, its prompt then claude's stream, and `result.md`, the printed report. +It keeps each run and the report it prints in loop-claude's archive, in +replays/judge-replay--/ under ~/.claude/loop-claude-transcripts or $LOOP_CLAUDE_TRANSCRIPTS. +A run's .jsonl file starts with a line holding claude's arguments, working directory, prompt, exit code and +stderr, then holds claude's stream-json output; result.md holds the report. Like the loop, it tries a judge three times running before it counts the reply as failed. A verdict whose project, transcript or archived judge run cannot be read replays as failed too. Exit 1, saying why, on diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 6bd9bf1d..fa2dc5c3 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -45,7 +45,10 @@ replay, and runs no SubagentStart hook there. So the replay without CLAUDE.md tu instruction files off in its settings and opens the prompt with what the hook hands a reviewer, and closes it with the header's line on the project principles. -Each run, the reviewer's tool calls included, is kept with the report it ended in: `replays/--/` in loop-claude's archive holds a `.jsonl` file per run, its prompt then claude's stream, and `result.md`, the printed report. +It keeps each run, a reviewer's tool calls included, and the report it prints in loop-claude's archive, in +replays/review-replay--[-omit-claude-md]-/ under ~/.claude/loop-claude-transcripts +or $LOOP_CLAUDE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working +directory, prompt, exit code and stderr, then holds claude's stream-json output; result.md holds the report. Like the loop, it tries claude three times running before it counts a reply as failed. A failed review or match leaves its round out, except on a rung below the project's, where it finds diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py index 92ecc91f..8ee9b28e 100644 --- a/bin/rung_replay/archive.py +++ b/bin/rung_replay/archive.py @@ -1,4 +1,4 @@ -"""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, …`.""" +"""Keeps each run of judge-replay and review-replay, and the report each prints, in loop-claude's archive: docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`.""" import dataclasses import hashlib import json @@ -10,7 +10,7 @@ import time 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. +# The type of the first line of a run's file, which holds what the stream lacks: claude's arguments, working directory, prompt, exit code and stderr. No event claude writes has this type. HEADER = "replay_run" RESULT = "result.md" @@ -22,7 +22,7 @@ def replay_folder(root: pathlib.Path, tool: str, argv: list[str], now: float) -> 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.""" + """effects whose claude also writes each run into folder: a header line, then the stream claude printed. A run is kept whether it failed or not, and a run that repeats another word for word is kept once. A folder that can't be written is reported on stderr, and the replay goes on.""" claude = effects.claude def run(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[str]: diff --git a/docs/decisions.md b/docs/decisions.md index 0b8fb771..6aeef3cf 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -182,9 +182,17 @@ Valid while `~/.claude` is a checkout of this repo. Valid while claude takes `--session-id` and resumes by it, and the human runs loop-claude where tmux is installed. -## loop-claude: the archive keeps the raw transcript and each judge run, a failed archive stops the loop, and judge-replay and review-replay keep each run and their report under its replays/ folder +## loop-claude: the archive keeps the raw transcript and each judge run, a failed archive stops the loop, and a replay keeps its runs and report in a replays/ folder of the archive -2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. The judge's runs are archived too, as `judge/.json` in the chunk's folder: the prompt it read and its json reply. Together they are its whole transcript, since it runs with no tools and one turn. A run is kept whole and deduplicated by hash, and the outcome of the verdict, interrupt or rejected reply it produced names it on a `Judge run:` line. Keeping it whole costs little: a prompt is at most `JUDGE_PROMPT_CHARS`, 400,000 characters. Measured 2026-11-17, the archive's 911 judge lines come to at most 0.36 GB of prompts, against 3.5 GB in its 1,211 transcript copies, the largest 23.4 MB. The judge is still priced from its `Judge cost:` line, which is claude's own total for the run, and the Spent block counts the live reply's tokens; the archived reply keeps its `usage` for a later reader, and nothing reads it back. `judge-replay` replays a verdict on its archived prompt where there is one. The replays keep their own runs, since each decides which rung a review pass or the judge may run on and so must stay checkable and re-priceable once the decision is questioned (2026-11-17, item 304): `replays/--/` in the archive's root holds one `.jsonl` per run, whether it failed or not, and `result.md`, the report the tool printed. A run's file is a header line with claude's arguments, working directory and prompt, then claude's stream-json output as printed, whose last line is the reply the replay read; a reviewer's tool calls and a judge's reply are in it. `claude_reply` takes stream-json in place of json for every caller, so the judge's runs are streams too, and its archive keeps the `JudgeRun` it did. A run that repeats another word for word is kept once. A folder that cannot be written is said on stderr and doesn't stop the replay. Valid while transcripts, and the judge's prompts, stay small enough to copy whole. +2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. The judge's runs are archived too, as `judge/.json` in the chunk's folder: the prompt it read and its json reply. Together they are its whole transcript, since it runs with no tools and one turn. A run is kept whole and deduplicated by hash, and the outcome of the verdict, interrupt or rejected reply it produced names it on a `Judge run:` line. Keeping it whole costs little: a prompt is at most `JUDGE_PROMPT_CHARS`, 400,000 characters. Measured 2026-11-17, the archive's 911 judge lines come to at most 0.36 GB of prompts, against 3.5 GB in its 1,211 transcript copies, the largest 23.4 MB. The judge is still priced from its `Judge cost:` line, which is claude's own total for the run, and the Spent block counts the live reply's tokens; the archived reply keeps its `usage` for a later reader, and nothing reads it back. `judge-replay` replays a verdict on its archived prompt where there is one. Valid while transcripts, and the judge's prompts, stay small enough to copy whole. + +2026-11-17, lilleman, todo item 304. Serves goals 1.4 and 3. `judge-replay` and `review-replay` each decide which rung a review pass or the judge may run on, so their runs stay checkable and re-priceable once a decision is questioned. They keep their runs in `replays/--/` in the archive's root: + +- One `.jsonl` file per run, whether it failed or not. It starts with a header line holding claude's arguments, working directory, prompt, exit code and stderr, and goes on with claude's stream-json output as printed, whose last line is the reply the replay read. A reviewer's tool calls are in it. +- `result.md`, the report the tool printed. +- A run that repeats another word for word is kept once. A folder that can't be written is reported on stderr and doesn't stop the replay. + +`claude_reply` reads stream-json for every caller, so the judge's runs are streams too; the archive's `JudgeRun` stays as it was, since a judge has no tools and one turn. Valid while transcripts stay small enough to copy whole. ## loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation -- 2.52.0 From 97af00ef3503f599210cbcd1a831f21b4940100f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 17 Nov 2026 02:35:27 +0100 Subject: [PATCH 9/9] Finish item 304 in the plan --- CHANGELOG.md | 1 + todo.md | 17 ----------------- 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6abb71b0..b230ee41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- review-replay and judge-replay keep each run, with its prompt, claude's exit code and stream, and the report they print, in a `replays/--/` folder of loop-claude's archive, so a replay that decided a rung can be checked and re-priced later; claude's json replies are now stream-json, whose last line is the reply. - loop-claude's archive keeps each judge run's prompt and json reply in a judge/ folder beside its chunk's transcripts, and names the run on a `Judge run:` line of the outcome it produced; judge-replay replays a verdict on its archived prompt where the archive holds one. - A plan kept as a Jira epic takes no changelog bullet: `todo-item finish` there needs neither `--changelog` nor `--no-changelog`, and refuses `--changelog`, since the issues' history is the changelog. diff --git a/todo.md b/todo.md index e8e8eaaa..1bc3a4c8 100644 --- a/todo.md +++ b/todo.md @@ -13,7 +13,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 306 | 0.12.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 | -| 304 | 0.12.0 | | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 3.8 | | 387 | 0.12.0 | | | **Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 2.9 | | 338 | 0.12.0 | | owner | **Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.3 | | 288 | 0.12.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.2 | @@ -98,22 +97,6 @@ Touches: - `skills/larv-review/SKILL.md`: `## 6. Wrap up` (small) - `README.md`: `## Install` (small) -### 304. Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later. - -Today `review-replay` and `judge-replay` leave no transcript: both run claude through `claude_reply` in `bin/claude_code/reply.py`, whose `--no-session-persistence` makes Claude Code write no session file, as item 303 describes for the judge. A replay decides which rung a review pass or the judge may run on (`routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows…`, and the judge's rung on `JUDGE_REPLAYED`), so the runs behind a routing decision can't be read again, re-priced or re-scored once the decision is questioned. Goal 3 asks for the transcripts of unattended runs, the bench's included, to be backed up; `workflow-bench/bench.py` already keeps its claude stream in `logs/`. - -Unlike the judge, a replayed reviewer uses tools over several turns, so its transcript is more than its prompt and reply. Recommended: have `claude_reply` take `--output-format stream-json --verbose` in place of `json`, keep `--no-session-persistence`, write the stream where the replay keeps its result, and read the reply from the stream's last `result` event. That also gives item 303 the judge's stream for free, so build on 303's archive layout and do both callers through the one runner. - -Touches: - -- `bin/claude_code/reply.py`: `claude_reply` -- `bin/claude_code/test_claude_code.py` -- `bin/review_replay/replay.py`: `reviewed_in`, `match`, `copy_reports` -- `bin/review_replay/test_review_replay.py` -- `bin/judge_replay/main.py`: `rule` -- `bin/judge_replay/test_judge_replay.py` -- `bin/loop_claude/cycle/judge.py`: `judge_args`, `run_judge` (small) - ### 387. Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both. Filed by PR #553, which made the routing ladder a file a project may replace. Its stability round 1 found two places the comprehension seats name as hard, touched and no easier to read: `bin/loop_claude/routing.py` `unfinished_route` took `ladder` as a fourth parameter, and `Cycle` in `bin/loop_claude/cycle/run.py` gained the field `ladder`. The patch threaded the ladder as an argument, since a wider change did not fit a patch cut during an outage. -- 2.52.0