From 990963d586b84e73dd052b4a3bb504cf535f1a13 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:00:14 +0200 Subject: [PATCH 01/10] Archive every cycle's transcript and its session folder, however the cycle ends --- CHANGELOG.md | 2 +- bin/loop_claude/cycle/archive.py | 34 ++++++++++++++++++++++---- bin/loop_claude/cycle/run.py | 34 +++++++++++++++++--------- bin/loop_claude/cycle/states.py | 7 +++--- bin/loop_claude/loop/main.py | 7 +++--- bin/test_loop_claude.py | 40 +++++++++++++++++++++++++------ bin/test_loop_claude_black_box.py | 8 ++++--- todo.md | 2 -- 8 files changed, 98 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf75fbdc..e13bb5d6 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`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. +- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and a failure included: one copy per distinct transcript, named by its SHA-256, with the verdict or the stop beside it in `.verdict.md`, and the session folder's files, the subagents' transcripts among them, in `/`; a transcript it cannot archive exits 1. - `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/cycle/archive.py b/bin/loop_claude/cycle/archive.py index b7702eda..f48e31ef 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -1,4 +1,5 @@ import hashlib +import pathlib import sys from loop_claude.failure import Failure @@ -14,11 +15,34 @@ def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | N 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): + return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" - # The copy lands last, so a copy on disk always has its verdict beside it. - if not copy.exists(): - for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)): - if unwritten := replace_file(dest, data): - return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}") + # The copy lands last, so a copy on disk always has its verdict and its session folder beside it. + if copy.exists(): + return None + for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\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 + + +# Claude Code only appends to a session folder's files, so overwriting a copy loses nothing. +def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: + for file in sorted(source.rglob("*")): + copy = dest / file.relative_to(source) + try: + if not file.is_file(): + continue + data = file.read_bytes() + if copy.is_file() and copy.read_bytes() == data: + continue + make_private(copy.parent) + except OSError as failure: + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") + if unwritten := replace_file(copy, data): + return Failure(f"could not archive the transcript: {copy}: {unwritten.reason}") + return None diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 8b1b4206..17a0ec20 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -8,6 +8,7 @@ from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.cycle.retry import retried from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition +from loop_claude.cycle.verdicts import Finished, Unfinished from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.effects import Effects from loop_claude.failure import Failure @@ -30,14 +31,24 @@ class Cycle: def run_cycle(cycle: Cycle) -> Stop | None: state: State = Working() - while not isinstance(state, Ended): - event = step(cycle, state) - if isinstance(event, Stop): - return event - state = transition(state, event) + try: + while not isinstance(state, Ended): + event = step(cycle, state) + if isinstance(event, Stop): + return stopped(cycle, event) + state = transition(state, event) + except KeyboardInterrupt: + return stopped(cycle, Stop(130, "")) return None +def stopped(cycle: Cycle, stop: Stop) -> 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 + # A stop for a failed archive has just failed the same way again. + return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop + + def step(cycle: Cycle, state: Active) -> Event | Stop: match state: case Working(): @@ -46,8 +57,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: return rule(cycle, transcript_path) case Interrupting(transcript_path, question): return ask(cycle, transcript_path, question) - case Finishing(transcript_path): - return close(cycle, transcript_path) + case Finishing(transcript_path, verdict): + return close(cycle, transcript_path, verdict) case _: typing.assert_never(state) @@ -69,15 +80,16 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: - # The interrupt appends to this transcript, so it is archived at each question. + # Archived before the interrupt appends to the transcript, so the copy carries the question beside it. if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: 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) -> Archived | Stop: - if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): +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): return Stop(1, failure.reason) - if failure := delete_session(cycle.session): + if finished and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) return Archived() diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 14d8a36a..fc176ad6 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -22,6 +22,7 @@ class Interrupting: @dataclasses.dataclass(frozen=True) class Finishing: transcript_path: str + verdict: Finished | Unfinished @dataclasses.dataclass(frozen=True) @@ -62,10 +63,8 @@ def transition(state: State, event: Event) -> State: return Judging(transcript_path) case Judging(transcript_path), Ruled(Interrupt(question=question)): return Interrupting(transcript_path, question) - case Judging(transcript_path), Ruled(Finished()): - return Finishing(transcript_path) - case Judging(), Ruled(Unfinished()): - return Ended() + case Judging(transcript_path), Ruled(Finished() | Unfinished() as verdict): + return Finishing(transcript_path, verdict) # The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves. case Interrupting(transcript_path), Answered(): return Judging(transcript_path) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 6cdd1cff..aa0e0c2a 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -12,9 +12,10 @@ 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 when the chunk finishes, the session's transcript is copied to -$LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default ~/.claude/loop-claude-transcripts), the -verdict beside it in .verdict.md. +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), +the verdict or the stop beside it in .verdict.md, and the files of its session folder, the +subagents' transcripts among them, to //. 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 78effad3..8a726053 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -3,6 +3,7 @@ import dataclasses import json import os import pathlib +import stat import subprocess import sys import tempfile @@ -119,15 +120,15 @@ class Transitions(unittest.TestCase): legal = ( (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), - (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")), - (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Ended()), + (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t", Finished("e"))), + (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Finishing("/t", Unfinished("e"))), (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), - (states.Finishing("/t"), states.Archived(), states.Ended()), + (states.Finishing("/t", Finished("e")), states.Archived(), states.Ended()), ) for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Finishing("/t"), states.Ended()) + every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Finishing("/t", Finished("e")), states.Ended()) every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived()) for state in every_state: for event in every_event: @@ -156,7 +157,7 @@ class Cycles(unittest.TestCase): self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertIsNone(session.transcript_file(self.session)) - def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self): + def test_an_unfinished_chunk_is_archived_and_keeps_its_session_and_the_next_cycle_resumes_it(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2) self.assertIsNone(run.run_cycle(self.cycle(fake))) self.assertTrue(session.transcript_file(self.session)) @@ -164,7 +165,31 @@ class Cycles(unittest.TestCase): workers = fake.made("stream_claude") self.assertIn("--session-id", workers[0]) self.assertIn("--resume", workers[1]) - self.assertFalse((self.paths.transcript_archive / "proj").exists()) + self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: unfinished\n"] * 2) + + def test_a_stopped_or_interrupted_cycle_archives_what_its_session_holds(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) + self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) + 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_and_overwrites_only_a_changed_copy(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") + kept = self.paths.transcript_archive / "proj" / str(self.session.id) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished"), judged("finished")]) + self.assertIsNone(run.run_cycle(self.cycle(fake))) + os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) + with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: + handle.write("more\n") + 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(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600) def test_an_interrupt_is_archived_answered_and_judged_again(self): def answer(args): @@ -173,7 +198,7 @@ class Cycles(unittest.TestCase): return 0 fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()]) self.assertIsNone(run.run_cycle(self.cycle(fake))) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"]) + self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n", "Task: Do it.\n\nVerdict: unfinished\n"]) self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) prompts = [stdin for args, stdin in fake.made("claude")] self.assertEqual(len(prompts), 2) @@ -376,6 +401,7 @@ class ExitContract(unittest.TestCase): ("cycle/interrupt.py", "interrupt", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), ("cycle/interrupt.py", "interrupt", "1", "f'could not tell whether you typed anything:", read), ("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), + ("cycle/run.py", "stopped", "1", "f'{failure.reason}", read), ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), ("cycle/run.py", "rule", "1", "entries.reason", read), ("cycle/run.py", "ask", "1", "failure.reason", read), diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index fda16a3a..15cdd976 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -344,9 +344,10 @@ class Cycles(unittest.TestCase): self.assertNotIn("landed-it", run.calls[5]["stdin"]) self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name]) self.assertIn("=== cycle 3 ===", run.stdout) - [(copy, verdict)] = checkout.archived().items() - self.assertIn('"text": "landed-it"', copy) - self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: finished\n") + copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()} + self.assertEqual(sorted(copies), ["Stopped: Ctrl-C\n", "Verdict: finished\n", "Verdict: unfinished\n"]) + self.assertIn('"text": "landed-it"', copies["Verdict: finished\n"]) + self.assertIn('"text": "next chunk"', copies["Stopped: Ctrl-C\n"]) def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self): checkout = Checkout(self) @@ -427,6 +428,7 @@ class Cycles(unittest.TestCase): checkout = Checkout(self) run = checkout.run([worker(unreadable=True)]) self.assertEqual((run.code, run.roles()), (1, ["worker"])) + self.assertRegex(run.stderr.strip().splitlines()[-2], r"^could not archive the transcript: .*\.jsonl: Permission denied$") self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not read the transcript .*\.jsonl: Permission denied$") def test_retries_a_worker_claude_cannot_start(self): diff --git a/todo.md b/todo.md index 2c88b4d2..4f201da0 100644 --- a/todo.md +++ b/todo.md @@ -2,8 +2,6 @@ ## 0.1.0 -- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. Goal 2. -- **Archive a finished chunk's subagent transcripts before `delete_session` removes them.** Today only `.jsonl` is copied, so every reviewer's full run in an unattended chunk is lost. Goal 2. - **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Goal 2. - **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. - **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4. From b9f65aac208745e1663c8538a0dee243c7a45bc4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:04:47 +0200 Subject: [PATCH 02/10] Answer the stability and product-owner reviews' first round --- CHANGELOG.md | 2 +- bin/loop_claude/cycle/archive.py | 16 +++++++++++++--- bin/loop_claude/cycle/run.py | 4 ++-- bin/loop_claude/cycle/states.py | 8 ++++---- bin/loop_claude/loop/main.py | 3 ++- bin/test_loop_claude.py | 17 +++++++++++------ bin/test_loop_claude_black_box.py | 1 + todo.md | 2 +- 8 files changed, 35 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e13bb5d6..47648c7b 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 a failure included: one copy per distinct transcript, named by its SHA-256, with the verdict or the stop beside it in `.verdict.md`, and the session folder's files, the subagents' transcripts among them, in `/`; a transcript it cannot archive exits 1. +- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and a failure included: one copy per distinct transcript, named by its SHA-256, with the verdict or the stop beside it in `.verdict.md`, and the session folder's files, the subagents' transcripts among them, in `/` beside them; a transcript it cannot archive exits 1. - `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/cycle/archive.py b/bin/loop_claude/cycle/archive.py index f48e31ef..695c504b 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -30,15 +30,14 @@ def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | N return None -# Claude Code only appends to a session folder's files, so overwriting a copy loses nothing. def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: for file in sorted(source.rglob("*")): - copy = dest / file.relative_to(source) try: if not file.is_file(): continue data = file.read_bytes() - if copy.is_file() and copy.read_bytes() == data: + copy = copy_for(dest / file.relative_to(source), data) + if copy is None: continue make_private(copy.parent) except OSError as failure: @@ -46,3 +45,14 @@ def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: if unwritten := replace_file(copy, data): return Failure(f"could not archive the transcript: {copy}: {unwritten.reason}") return None + + +# Every chunk of a project reuses its session id, so a name can recur with other content: only a file that grew from its copy replaces it. +def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None: + if not copy.is_file(): + return copy + kept = copy.read_bytes() + if data.startswith(kept): + return copy if data != kept else None + beside = copy.with_name(f"{copy.name}.{hashlib.sha256(data).hexdigest()}") + return None if beside.exists() else beside diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 17a0ec20..074e4ec6 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -7,7 +7,7 @@ from loop_claude.cycle.archive import archive from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.cycle.retry import retried -from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition +from loop_claude.cycle.states import Active, Answered, Archived, Closing, Ended, Event, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition from loop_claude.cycle.verdicts import Finished, Unfinished from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.effects import Effects @@ -57,7 +57,7 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: return rule(cycle, transcript_path) case Interrupting(transcript_path, question): return ask(cycle, transcript_path, question) - case Finishing(transcript_path, verdict): + case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: typing.assert_never(state) diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index fc176ad6..ad0f5b11 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -20,7 +20,7 @@ class Interrupting: @dataclasses.dataclass(frozen=True) -class Finishing: +class Closing: transcript_path: str verdict: Finished | Unfinished @@ -30,7 +30,7 @@ class Ended: """The cycle is over.""" -Active = Working | Judging | Interrupting | Finishing +Active = Working | Judging | Interrupting | Closing State = Active | Ended @@ -64,10 +64,10 @@ def transition(state: State, event: Event) -> State: case Judging(transcript_path), Ruled(Interrupt(question=question)): return Interrupting(transcript_path, question) case Judging(transcript_path), Ruled(Finished() | Unfinished() as verdict): - return Finishing(transcript_path, verdict) + return Closing(transcript_path, verdict) # The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves. case Interrupting(transcript_path), Answered(): return Judging(transcript_path) - case Finishing(), Archived(): + case Closing(), Archived(): return Ended() raise ValueError(f"no transition from {state} on {event}") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index aa0e0c2a..3dcef6c1 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -15,7 +15,8 @@ relative to ~/code, or to / outside it. The session is deleted when its chunk fi 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), the verdict or the stop beside it in .verdict.md, and the files of its session folder, the -subagents' transcripts among them, to //. +subagents' transcripts among them, to //; a file that does not extend its earlier +copy, such as one an earlier chunk left, lands beside it 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 8a726053..ca07529e 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -120,15 +120,15 @@ class Transitions(unittest.TestCase): legal = ( (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), - (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t", Finished("e"))), - (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Finishing("/t", Unfinished("e"))), + (states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), + (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), - (states.Finishing("/t", Finished("e")), states.Archived(), states.Ended()), + (states.Closing("/t", Finished("e")), states.Archived(), states.Ended()), ) for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Finishing("/t", Finished("e")), states.Ended()) + every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Closing("/t", Finished("e")), states.Ended()) every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived()) for state in every_state: for event in every_event: @@ -174,13 +174,14 @@ 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_and_overwrites_only_a_changed_copy(self): + def test_archives_the_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)] * 2, claude=[judged("unfinished"), judged("finished")]) + 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))) os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: @@ -190,6 +191,10 @@ class Cycles(unittest.TestCase): 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(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600) + folder.mkdir() + (folder / "custom-title.json").write_text("second") + self.assertIsNone(run.run_cycle(self.cycle(fake))) + self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"]) def test_an_interrupt_is_archived_answered_and_judged_again(self): def answer(args): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 15cdd976..0fe4f925 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -356,6 +356,7 @@ class Cycles(unittest.TestCase): run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")]) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$") + self.assertEqual(run.stderr.count("could not archive the transcript"), 1) session = argument(run.calls[0], "--session-id") checkout.archive().unlink() run = checkout.run([worker(), judge(finished=True)]) diff --git a/todo.md b/todo.md index 4f201da0..0d753c45 100644 --- a/todo.md +++ b/todo.md @@ -19,7 +19,7 @@ - **Move the judge's transcript rendering from `claude_code/transcript.py` into `cycle/`.** `render`, `part_line` and `JUDGED_TOOL_INPUT` shape what the judge sees, so what the judge sees is shaped in two packages: those three in `claude_code/`, and `JUDGED_TRANSCRIPT_TAIL` in `cycle/judge.py`; and `claude_code/` no longer holds only Claude Code's shapes as its docstring says. Goal 4.1. - **Make `JUDGE_RULES` and the Claude Code flags `loop-claude` passes readable without `CLAUDE.md` or Claude Code's docs open.** The 2026-10-02 scoring runs on PR #191 named both under Self-sufficiency: the judge's rules use "chunk" and "a release ready to cut" from `CLAUDE.md` with no link, and `--resume`, `--session-id`, `--no-session-persistence`, `--json-schema` and stream-json's result event go unexplained in `worker.py` and `judge.py`. Goal 4.1. - **Encode, decode and check the reload handover in `loop/reload.py` alone.** `reload.py` encodes `LoopRun` and decodes it, but `main.py`'s `loop_run_from` checks the decoded fields and words the error, so changing `LoopRun`'s fields means editing both files. The 2026-10-02 scoring runs on PR #191 named it under Locality. Goal 4.1. -- **Give each cycle phase one name across its state, step and event.** Today `Judging` runs `rule` and yields `Ruled`, and `Finishing` runs `close`, which also deletes the session, and yields `Archived`. Goal 4.1. +- **Give each cycle phase one name across its state, step and event.** Today `Judging` runs `rule` and yields `Ruled`, and `Closing` runs `close`, which also deletes a finished chunk's session, and yields `Archived`. Goal 4.1. - **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** No machine has it enabled, so every chunk that fires the pass skips it. Goal 4.1. - **Give `settings.json`'s model one writer, and sort its keys.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3. - **Say in `systems-architect.md` that a REST API's `/v1/` prefix is not versioning machinery to defer.** Its "defer the versioning story" can be read against `principles/rest-apis.md`, which requires the prefix from the start. Goal 4.3. From 8aa09a8f2b6c2549efdb9f658b6855029b24cf2b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:07:04 +0200 Subject: [PATCH 03/10] Say which copy keeps a reused name --- bin/loop_claude/loop/main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 3dcef6c1..740b5113 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -16,7 +16,8 @@ interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's copied to $LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default ~/.claude/loop-claude-transcripts), the verdict or the stop beside it in .verdict.md, and the files of its session folder, the subagents' transcripts among them, to //; a file that does not extend its earlier -copy, such as one an earlier chunk left, lands beside it as .. +copy, such as one an earlier chunk left, lands beside it as ., and keeps the +first copy. 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 From 236ee08a59b04b971c2109268c9a5dab46c13419 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:09:39 +0200 Subject: [PATCH 04/10] Answer the prose review's first round --- CHANGELOG.md | 2 +- bin/loop_claude/cycle/archive.py | 2 +- bin/loop_claude/cycle/run.py | 4 ++-- bin/loop_claude/loop/main.py | 9 +++++---- bin/test_loop_claude.py | 4 ++-- todo.md | 2 ++ 6 files changed, 13 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47648c7b..6f997fe4 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 a failure included: one copy per distinct transcript, named by its SHA-256, with the verdict or the stop beside it in `.verdict.md`, and the session folder's files, the subagents' transcripts among them, in `/` beside them; a transcript it cannot archive exits 1. +- `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` 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/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 695c504b..d5925ee1 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -47,7 +47,7 @@ def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: return None -# Every chunk of a project reuses its session id, so a name can recur with other content: only a file that grew from its copy replaces it. +# Every chunk of a project reuses its session id, so an earlier chunk's file can share a name with this one's. 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 074e4ec6..9acfa3cb 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -45,7 +45,7 @@ def run_cycle(cycle: Cycle) -> Stop | None: def stopped(cycle: Cycle, stop: Stop) -> 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 - # A stop for a failed archive has just failed the same way again. + # 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 @@ -80,7 +80,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: - # Archived before the interrupt appends to the transcript, so the copy carries the question beside it. + # 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): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 740b5113..a6f64f57 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -14,10 +14,11 @@ Each project has one session, named "A loop-claude", where is the ch 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), -the verdict or the stop beside it in .verdict.md, and the files of its session folder, the -subagents' transcripts among them, to //; a file that does not extend its earlier -copy, such as one an earlier chunk left, lands beside it as ., and keeps the -first copy. +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 .. 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 ca07529e..05a9fcbe 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -157,7 +157,7 @@ class Cycles(unittest.TestCase): self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertIsNone(session.transcript_file(self.session)) - def test_an_unfinished_chunk_is_archived_and_keeps_its_session_and_the_next_cycle_resumes_it(self): + def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2) self.assertIsNone(run.run_cycle(self.cycle(fake))) self.assertTrue(session.transcript_file(self.session)) @@ -167,7 +167,7 @@ class Cycles(unittest.TestCase): self.assertIn("--resume", workers[1]) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: unfinished\n"] * 2) - def test_a_stopped_or_interrupted_cycle_archives_what_its_session_holds(self): + def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) diff --git a/todo.md b/todo.md index 0d753c45..c424e35a 100644 --- a/todo.md +++ b/todo.md @@ -58,4 +58,6 @@ - **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. From aca7594658c755bcb4c2e9055573af4af643d57d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 16:40:30 +0200 Subject: [PATCH 05/10] 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. From 6ccd5b190f8463a5ff3efaed32518c71cdf1b04b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 17:03:44 +0200 Subject: [PATCH 06/10] File naming chunk folders by start time --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index 96031902..7ff93b79 100644 --- a/todo.md +++ b/todo.md @@ -5,6 +5,7 @@ - **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Goal 2. - **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. - **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4. +- **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Goal 2. - **Key a project on its checkout's full path, and refuse to start while another session uses that key.** The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. - **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match. Goal 4.2. From 4620d2e29bacf3b27a72914614029e719de34165 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 17:10:03 +0200 Subject: [PATCH 07/10] Answer the principles audit: keep every session file under session/, and stop on a folder the archive cannot read --- CHANGELOG.md | 2 +- bin/loop_claude/claude_code/session.py | 8 +++-- bin/loop_claude/cycle/archive.py | 42 ++++++++++++++++++-------- bin/loop_claude/cycle/run.py | 4 +-- bin/loop_claude/loop/main.py | 4 +-- bin/test_loop_claude.py | 35 ++++++++++++++++++--- bin/test_loop_claude_black_box.py | 1 + todo.md | 8 +++-- 8 files changed, 76 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25d51b66..f5a6a651 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, 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` 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 its `session/` subfolder. `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/session.py b/bin/loop_claude/claude_code/session.py index d881fa1e..54d4c73f 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -35,14 +35,18 @@ def session_open(session: Session) -> bool: return transcript_file(session) is not None +# .jsonl, /subagents/, and from older Claude Code versions .superseded-1789290815002/ and .orphaned-*.jsonl +def session_files(transcript: str) -> list[str]: + return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")) + + def delete_session(session: Session) -> Failure | None: path = transcript_file(session) if path is None: return None stem = path.removesuffix(".jsonl") - # .jsonl, /subagents/, and from older versions .superseded-1789290815002/ and .orphaned-*.jsonl # The transcript goes last: a failed delete leaves a session that session_open still sees, never a new session with this id beside the old one's files. - for sibling in sorted(glob.glob(glob.escape(stem) + "*"), key=lambda sibling: sibling == path): + for sibling in sorted(session_files(path), key=lambda sibling: sibling == path): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) except OSError as failure: diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index c7b45dcf..118b44d8 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -1,7 +1,9 @@ import hashlib +import os import pathlib import sys +from loop_claude.claude_code.session import session_files 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 @@ -12,52 +14,66 @@ def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths) try: with open(path, "rb") as handle: raw = handle.read() + # Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh. 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. - if unkept := mirror(pathlib.Path(path.removesuffix(".jsonl")), folder): - return unkept + return unarchived(failure.filename, failure.strerror) + for kept in session_files(path): + if kept != path and (unkept := mirror(pathlib.Path(kept), folder / "session" / os.path.basename(kept))): + return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" verdict = copy.with_suffix(".verdict.md") if copy.exists(): return add_outcome(verdict, outcome) - # The copy lands last, so a copy on disk always has its verdict and its session folder beside it. + # The copy lands last, so a copy on disk always has its verdict and its session's files 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}") + return unarchived(dest, unwritten.reason) print(f"transcript: {copy}", file=sys.stderr) return None +def unarchived(where: object, why: str | None) -> Failure: + return Failure(f"could not archive the transcript: {where}: {why}") + + 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}") + return unarchived(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 unarchived(verdict, unwritten.reason) return None def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: - for file in sorted(source.rglob("*")): + try: + files = [source] if source.is_file() else files_under(source) + except OSError as failure: + return unarchived(failure.filename, failure.strerror) + for file in files: try: - if not file.is_file(): - continue data = file.read_bytes() copy = copy_for(dest / file.relative_to(source), data) if copy is None: continue make_private(copy.parent) except OSError as failure: - return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") + return unarchived(failure.filename, failure.strerror) if unwritten := replace_file(copy, data): - return Failure(f"could not archive the transcript: {copy}: {unwritten.reason}") + return unarchived(copy, unwritten.reason) return None +# Path.rglob skips a folder it cannot read; os.walk with onerror reports it. +def files_under(folder: pathlib.Path) -> list[pathlib.Path]: + def fail(error: OSError) -> None: + raise error + return sorted(pathlib.Path(root, name) for root, _, names in os.walk(folder, onerror=fail) for name in names) + + # 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(): diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index e06c12e0..2c1eb4cc 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -45,7 +45,7 @@ def run_cycle(cycle: Cycle) -> Stop | None: def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: path = transcript_file(cycle.session) 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. + # A failed archive exits 1 whatever stopped the loop; one that is the stop itself fails the same way again, so say it once. return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop @@ -80,7 +80,7 @@ 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. + # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. 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() diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 67719af4..5deaadc2 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -17,8 +17,8 @@ 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 +beside its transcript, holding the subagents' transcripts among other files; it and every other file +named after the session are copied into /session/. 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 diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index cf86c2df..53f38c5f 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,5 +1,6 @@ import ast import dataclasses +import hashlib import json import os import pathlib @@ -15,7 +16,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude import file_writes, paths from loop_claude.claude_code import entries, session, transcript, trust -from loop_claude.cycle import interrupt, judge, retry, run, states, worker +from loop_claude.cycle import archive, interrupt, judge, retry, run, states, worker from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished from loop_claude.effects import Effects from loop_claude.failure import Failure @@ -101,7 +102,7 @@ class Worker: 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({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n") handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n") return Streamed(0) @@ -182,9 +183,12 @@ class Cycles(unittest.TestCase): (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") + (folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n") 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() + [chunk] = (self.paths.transcript_archive / "proj").iterdir() + kept = chunk / "session" / str(self.session.id) + self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n") os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: handle.write("more\n") @@ -198,8 +202,17 @@ class Cycles(unittest.TestCase): folder.mkdir() (folder / "custom-title.json").write_text("third") self.assertIsNone(run.run_cycle(self.cycle(fake))) - [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"]) + [next_chunk] = set((self.paths.transcript_archive / "proj").iterdir()) - {chunk} + self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"]) + + @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable folder") + def test_stops_on_a_session_folder_it_cannot_read_whole(self): + locked = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" + locked.mkdir(parents=True) + locked.chmod(0) + self.addCleanup(locked.chmod, 0o700) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied")) def test_an_interrupt_is_archived_answered_and_judged_again(self): def answer(args): @@ -311,6 +324,18 @@ 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 CopyFor(unittest.TestCase): + def test_skips_a_version_already_kept_beside_its_copy(self): + with tempfile.TemporaryDirectory() as temp: + copy = pathlib.Path(temp, "custom-title.json") + copy.write_bytes(b"first") + beside = archive.copy_for(copy, b"second") + self.assertEqual(beside, copy.with_name(f"custom-title.json.{hashlib.sha256(b'second').hexdigest()}")) + beside.write_bytes(b"second") + self.assertIsNone(archive.copy_for(copy, b"second")) + self.assertEqual(archive.copy_for(copy, b"first, grown"), copy) + + 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"}') diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index cffb2659..2174f736 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -350,6 +350,7 @@ class Cycles(unittest.TestCase): self.assertEqual(sorted(copies), ["Stopped: Ctrl-C\n", "Verdict: finished\n", "Verdict: unfinished\n"]) self.assertIn('"text": "landed-it"', copies["Verdict: finished\n"]) self.assertIn('"text": "next chunk"', copies["Stopped: Ctrl-C\n"]) + self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1) def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self): checkout = Checkout(self) diff --git a/todo.md b/todo.md index 7ff93b79..85017877 100644 --- a/todo.md +++ b/todo.md @@ -5,7 +5,7 @@ - **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Goal 2. - **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. - **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4. -- **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Goal 2. +- **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. Goal 2. - **Key a project on its checkout's full path, and refuse to start while another session uses that key.** The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. - **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" to match. Goal 4.2. @@ -54,10 +54,12 @@ - Return a `Failure` from `replace_file` when removing the staged file fails too. - Say so when a catalog file cannot be read; today the prompt says no catalog is cached. - Sort `transcript_file`'s glob, and delete a session's files under every project folder that holds its id. + - Warn when `git worktree list` fails; today `worktrees` falls back to the root alone in silence, and the interrupt lands in Claude Code's trust dialog with no line saying why. + - Show the judge's stderr when its `claude` exits 0; today `run_judge` drops it. + - Find Claude Code's files under `CLAUDE_CONFIG_DIR` when it is set; today `paths_from` reads `~/.claude` alone, so every cycle exits 1 with "claude left no transcript". - Type `decode_handed` for `LoopRun`, its one caller's type, and drop the type variable `T`. - **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. - **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. - - `session.py`: say in `delete_session`'s comment that the `.superseded-*` and `.orphaned-*` names come from older Claude Code versions. + - `docs/decisions.md`: give the comprehension-floor entry a premise that has not expired. It says "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. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. From d104ea0b33130edd896916917c6fa41a4bed745b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 17:10:09 +0200 Subject: [PATCH 08/10] Rewrap the archive paragraph of --help --- bin/loop_claude/loop/main.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 5deaadc2..32d88d4e 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -18,8 +18,9 @@ copied to $LOOP_CLAUDE_TRANSCRIPTS///.jsonl (default 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; it and every other file -named after the session are copied into /session/. A file there is replaced only by a version that grew from it. A file Claude Code -rewrote lands beside its copy as .. +named after the session are copied into /session/. 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 From b436d2756d2fdf7088c17fbea8d9ca85abcf60a9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 17:20:15 +0200 Subject: [PATCH 09/10] Record the scoring runs, and name a session's sibling files apart from kept copies --- bin/loop_claude/cycle/archive.py | 4 ++-- docs/decisions.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 118b44d8..987fa3a1 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -19,8 +19,8 @@ def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths) make_private(folder) except OSError as failure: return unarchived(failure.filename, failure.strerror) - for kept in session_files(path): - if kept != path and (unkept := mirror(pathlib.Path(kept), folder / "session" / os.path.basename(kept))): + for sibling in session_files(path): + if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))): return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" verdict = copy.with_suffix(".verdict.md") diff --git a/docs/decisions.md b/docs/decisions.md index ec7d57c8..99a5a2e4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes From 872ffd3f67e2352fa58d276a4bd36abf30db2d2d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 17:22:00 +0200 Subject: [PATCH 10/10] Answer the prose review's third round, and file the human's two answers --- CHANGELOG.md | 2 +- bin/loop_claude/claude_code/session.py | 2 +- bin/loop_claude/cycle/run.py | 2 +- bin/loop_claude/loop/main.py | 8 ++++---- todo.md | 3 ++- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a6a651..805952a2 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, 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 its `session/` subfolder. `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 chunk folder's `session/` subfolder. `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/session.py b/bin/loop_claude/claude_code/session.py index 54d4c73f..a04ff067 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -35,7 +35,7 @@ def session_open(session: Session) -> bool: return transcript_file(session) is not None -# .jsonl, /subagents/, and from older Claude Code versions .superseded-1789290815002/ and .orphaned-*.jsonl +# .jsonl, /subagents/, and from older Claude Code versions .superseded-*/ and .orphaned-*.jsonl def session_files(transcript: str) -> list[str]: return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")) diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 2c1eb4cc..d889ec1f 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -45,7 +45,7 @@ def run_cycle(cycle: Cycle) -> Stop | None: def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: path = transcript_file(cycle.session) failure = archive(cycle.project_key, path, cycle.task, f"Stopped: {why}", cycle.paths) if path else None - # A failed archive exits 1 whatever stopped the loop; one that is the stop itself fails the same way again, so say it once. + # A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once. return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 32d88d4e..8939ed85 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -16,10 +16,10 @@ interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's 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; it and every other file -named after the session are copied into /session/. A file there is replaced only by a -version that grew from it. A file Claude Code rewrote lands beside its copy as +holds the verdict, and why the loop stopped. Claude Code keeps a folder per session beside its +transcript, holding the subagents' transcripts among other files; that folder, and every other file +named after the session except the transcript, are copied into /session/. 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 diff --git a/todo.md b/todo.md index 85017877..f6d2279c 100644 --- a/todo.md +++ b/todo.md @@ -2,7 +2,7 @@ ## 0.1.0 -- **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Goal 2. +- **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read. Goals 2 and 3. - **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. - **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4. - **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. Goal 2. @@ -58,6 +58,7 @@ - Show the judge's stderr when its `claude` exits 0; today `run_judge` drops it. - Find Claude Code's files under `CLAUDE_CONFIG_DIR` when it is set; today `paths_from` reads `~/.claude` alone, so every cycle exits 1 with "claude left no transcript". - Type `decode_handed` for `LoopRun`, its one caller's type, and drop the type variable `T`. +- **Allow stderr in `principles/logging.md` → "Infrastructure": OTLP, stdout or stderr.** A CLI keeps stdout for its output, as `loop-claude` does for the worker's stream; the rule's point is no log files. Goal 4.3. - **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. - **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.