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.