From aca7594658c755bcb4c2e9055573af4af643d57d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:40:30 +0200 Subject: [PATCH] Archive each chunk in its own folder, and add a stop to a verdict already archived --- CHANGELOG.md | 2 +- bin/loop_claude/claude_code/transcript.py | 6 +++++ bin/loop_claude/cycle/archive.py | 27 ++++++++++++++++------- bin/loop_claude/cycle/run.py | 12 +++++----- bin/loop_claude/loop/main.py | 13 ++++++----- bin/test_loop_claude.py | 24 +++++++++++++++----- bin/test_loop_claude_black_box.py | 8 ++++--- todo.md | 1 - 8 files changed, 62 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f997fe4..25d51b66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,6 @@ - `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. -- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included. Each distinct transcript is kept once, named by its SHA-256, with `.verdict.md` beside it holding the verdict or why the loop stopped. The subagents' transcripts and the session's other files go in `/` beside them. `loop-claude` exits 1 when it cannot archive. +- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256, with `.verdict.md` beside it holding the verdict and why the loop stopped. The subagents' transcripts and the session's other files go in the same folder. `loop-claude` exits 1 when it cannot archive. - `loop-claude` exits 1 when it cannot delete a finished chunk's session, naming what to delete before rerunning; the next chunk would otherwise resume it. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index 93a3d173..64599c11 100644 --- a/bin/loop_claude/claude_code/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -14,6 +14,12 @@ def read_transcript(path: str) -> list[dict] | Failure: return Failure(f"could not read the transcript {path}: {failure.strerror}") +# The lines before it, such as the session's title, are the same for every chunk of a project. +def first_timestamped_line(raw: bytes) -> bytes: + lines = raw.splitlines() + return next((line for line in lines if "timestamp" in (parse_entry(line) or {})), lines[0] if lines else b"") + + def human_turns(entries: list[dict]) -> int: return sum(1 for entry in entries if human_text(entry) is not None) diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index d5925ee1..c7b45dcf 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -2,34 +2,45 @@ import hashlib import pathlib import sys +from loop_claude.claude_code.transcript import first_timestamped_line from loop_claude.failure import Failure from loop_claude.file_writes import make_private, replace_file from loop_claude.paths import Paths -def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | None: - folder = paths.transcript_archive / project_key +def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths) -> Failure | None: try: with open(path, "rb") as handle: raw = handle.read() + folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest() make_private(folder) except OSError as failure: return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") # / holds the subagents' transcripts and the tool results too long for the transcript. - session_folder = pathlib.Path(path.removesuffix(".jsonl")) - if unkept := mirror(session_folder, folder / session_folder.name): + if unkept := mirror(pathlib.Path(path.removesuffix(".jsonl")), folder): return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" - # The copy lands last, so a copy on disk always has its verdict and its session folder beside it. + verdict = copy.with_suffix(".verdict.md") if copy.exists(): - return None - for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)): + return add_outcome(verdict, outcome) + # The copy lands last, so a copy on disk always has its verdict and its session folder beside it. + for dest, data in ((verdict, f"Task: {task}\n\n{outcome}\n".encode()), (copy, raw)): if unwritten := replace_file(dest, data): return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}") print(f"transcript: {copy}", file=sys.stderr) return None +def add_outcome(verdict: pathlib.Path, outcome: str) -> Failure | None: + try: + outcomes = verdict.read_bytes() + except OSError as failure: + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") + if unwritten := replace_file(verdict, outcomes + f"\n{outcome}\n".encode()): + return Failure(f"could not archive the transcript: {verdict}: {unwritten.reason}") + return None + + def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: for file in sorted(source.rglob("*")): try: @@ -47,7 +58,7 @@ def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: return None -# Every chunk of a project reuses its session id, so an earlier chunk's file can share a name with this one's. +# Claude Code rewrites some files whole, such as custom-title.json, so a copy is replaced only by a file that grew from it. def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None: if not copy.is_file(): return copy diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 9acfa3cb..e06c12e0 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -35,16 +35,16 @@ def run_cycle(cycle: Cycle) -> Stop | None: while not isinstance(state, Ended): event = step(cycle, state) if isinstance(event, Stop): - return stopped(cycle, event) + return stopped(cycle, event, event.reason) state = transition(state, event) except KeyboardInterrupt: - return stopped(cycle, Stop(130, "")) + return stopped(cycle, Stop(130, ""), "Ctrl-C") return None -def stopped(cycle: Cycle, stop: Stop) -> Stop: +def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: path = transcript_file(cycle.session) - failure = archive(cycle.project_key, path, f"Task: {cycle.task}\n\nStopped: {'Ctrl-C' if stop.code == 130 else stop.reason}", cycle.paths) if path else None + failure = archive(cycle.project_key, path, cycle.task, f"Stopped: {why}", cycle.paths) if path else None # When the stop is itself a failed archive, archiving again fails the same way: say it once. return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop @@ -81,14 +81,14 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: # Archived now, so the transcript the question was asked on is kept with it; the interrupt appends the answer. - if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", cycle.paths): + if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}", cycle.paths): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: finished = isinstance(verdict, Finished) - if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: {'finished' if finished else 'unfinished'}", cycle.paths): + if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}", cycle.paths): return Stop(1, failure.reason) if finished and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index a6f64f57..67719af4 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -13,12 +13,13 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V Each project has one session, named "A loop-claude", where is the checkout's path relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is -copied to $LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default ~/.claude/loop-claude-transcripts), -named by its hash. Beside it, .verdict.md holds the verdict, or why the loop stopped. -Claude Code keeps a folder per session beside its transcript, holding the subagents' transcripts -among other files; those files are copied to //. A file there is replaced only by -a version that grew from it. A file with other content under the same name, such as one an earlier -chunk left, lands beside it as .. +copied to $LOOP_CLAUDE_TRANSCRIPTS///.jsonl (default +~/.claude/loop-claude-transcripts), named by its hash. is the hash of the transcript's first +line with a timestamp, the same for every cycle of a chunk. Beside the copy, .verdict.md +holds the verdict, and why the loop stopped when it did. Claude Code keeps a folder per session +beside its transcript, holding the subagents' transcripts among other files; those files are copied +into /. A file there is replaced only by a version that grew from it. A file Claude Code +rewrote lands beside its copy as .. Every claude loop-claude starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 05a9fcbe..cf86c2df 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -100,6 +100,8 @@ class Worker: path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a") as handle: + if flag == "--session-id": + handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid4())}) + "\n") handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n") return Streamed(0) @@ -149,7 +151,7 @@ class Cycles(unittest.TestCase): return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", root=str(self.home), session=self.session, task="Do it.") def archived_verdicts(self): - return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*.verdict.md")) + return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.verdict.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")]) @@ -174,27 +176,30 @@ class Cycles(unittest.TestCase): self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nStopped: Ctrl-C\n", "Task: Do it.\n\nStopped: the judge failed three times running: the judge exited 1\n"]) - def test_archives_the_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): + def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) (folder / "subagents" / "workflows").mkdir(parents=True) (folder / "subagents" / "agent-a.jsonl").write_text("a\n") (folder / "subagents" / "workflows" / "journal.jsonl").write_text("j\n") (folder / "custom-title.json").write_text("first") - kept = self.paths.transcript_archive / "proj" / str(self.session.id) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")]) self.assertIsNone(run.run_cycle(self.cycle(fake))) + [kept] = (self.paths.transcript_archive / "proj").iterdir() os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: handle.write("more\n") + (folder / "custom-title.json").write_text("second") self.assertIsNone(run.run_cycle(self.cycle(fake))) self.assertFalse(folder.exists()) self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n") self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0) + self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"]) self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600) folder.mkdir() - (folder / "custom-title.json").write_text("second") + (folder / "custom-title.json").write_text("third") self.assertIsNone(run.run_cycle(self.cycle(fake))) - self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"]) + [next_chunk] = set((self.paths.transcript_archive / "proj").iterdir()) - {kept} + self.assertEqual(sorted(path.read_text() for path in next_chunk.glob("custom-title.json*")), ["third"]) def test_an_interrupt_is_archived_answered_and_judged_again(self): def answer(args): @@ -220,7 +225,7 @@ class Cycles(unittest.TestCase): stop = run.run_cycle(self.cycle(fake)) self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")) self.assertTrue(session.session_open(self.session)) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) + self.assertEqual(self.archived_verdicts(), [f"Task: Do it.\n\nVerdict: finished\n\nStopped: {stop.reason}\n"]) def test_stops_when_the_worker_leaves_no_transcript(self): fake = FakeEffects(streams=[Streamed(0)]) @@ -306,6 +311,13 @@ class Render(unittest.TestCase): self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work') +class FirstTimestampedLine(unittest.TestCase): + def test_skips_the_lines_every_chunk_shares_and_else_takes_the_first(self): + self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\nnot JSON\n{"timestamp": "t"}\n{"timestamp": "u"}\n'), b'{"timestamp": "t"}') + self.assertEqual(transcript.first_timestamped_line(b'{"type": "custom-title"}\n[1]\n'), b'{"type": "custom-title"}') + self.assertEqual(transcript.first_timestamped_line(b""), b"") + + class HumanTurns(unittest.TestCase): def test_counts_typed_turns_and_not_tool_results(self): self.assertEqual(transcript.human_turns([ diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 0fe4f925..cffb2659 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -56,6 +56,8 @@ def append(*entries): if role == "worker": + if "--session-id" in argv and step.get("transcript", True): + append({{"type": "custom-title"}}, {{"type": "queue-operation", "timestamp": str(time.time_ns())}}) said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}} if step.get("transcript", True): append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}}) @@ -249,9 +251,9 @@ class Checkout: def archived(self): """Each archived transcript's verdict, after checking the copy is named by its content hash.""" verdicts = {} - for folder in (self.archive(), self.archive() / "proj"): + for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()): self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder) - for copy in sorted((self.archive() / "proj").glob("*.jsonl")): + for copy in sorted((self.archive() / "proj").glob("*/*.jsonl")): self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest()) verdict = copy.with_suffix(".verdict.md") for archived in (copy, verdict): @@ -457,7 +459,7 @@ class Interrupt(unittest.TestCase): self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"]) [(copy, verdict)] = checkout.archived().items() self.assertEqual(copy, (checkout.transcripts()[0]).read_text()) - self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n") + self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n\nStopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n") self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700) self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr) session = argument(run.calls[0], "--session-id") diff --git a/todo.md b/todo.md index c424e35a..96031902 100644 --- a/todo.md +++ b/todo.md @@ -58,6 +58,5 @@ - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - `docs/decisions.md`: order the entries and the `AGENTS.md` index by one key. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - - `docs/decisions.md`: have "the archive keeps the raw transcript" cover the session-folder copy, which keeps files by name and replaces one only with a version that grew from it. - `session.py`: say in `delete_session`'s comment that the `.superseded-*` and `.orphaned-*` names come from older Claude Code versions. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each.