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.