diff --git a/CHANGELOG.md b/CHANGELOG.md index 66b2b001..cae8c26f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,4 +9,5 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. +- `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` 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.py b/bin/loop_claude/cycle.py index c5b5e163..9c5a144c 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,9 +1,8 @@ -import os +import hashlib import sys -import time from loop_claude.checkout import project_name -from loop_claude.file_writes import make_private +from loop_claude.file_writes import make_private, replace_file from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop @@ -20,7 +19,7 @@ def run_cycle(root, task, premises, models, paths): path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") - # The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote. + # The interrupt appends to this transcript, so each pass judges and archives it anew. while True: entries = read(path) if isinstance(entries, Failure): @@ -30,30 +29,30 @@ def run_cycle(root, task, premises, models, paths): return verdict if not verdict["interrupt"]: break - archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) + if failure := archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): + return Stop(1, failure.reason) if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop if verdict["finished"]: - archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) + if failure := archive(root, path, f"Task: {task}\n\nVerdict: finished", paths): + return Stop(1, failure.reason) delete_session(session) return Continue() def archive(root, path, note, paths): - # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. - name = project_name(root, paths.code) - folder = paths.archive / name + folder = paths.archive / project_name(root, paths.code) try: - stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) + with open(path, "rb") as handle: + raw = handle.read() make_private(folder) - dest = folder / f"{stamp}.md" - if not os.path.exists(dest): - entries = read(path) - if isinstance(entries, Failure): - print(f"could not archive the transcript: {entries.reason}", file=sys.stderr) - return - with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: - copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries)}\n") - print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: - print(f"could not archive the transcript: {failure}", file=sys.stderr) + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") + 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 failure := replace_file(dest, data): + return Failure(f"could not archive the transcript: {dest}: {failure.strerror}") + print(f"transcript: {copy}", file=sys.stderr) + return None diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 44cf070e..0654c309 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -11,12 +11,16 @@ def make_private(folder): def replace_json(path, data, **dump): + return replace_file(path, json.dumps(data, **dump).encode()) + + +def replace_file(path, data): staged = f"{path}.{os.getpid()}" try: mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 - with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as handle: os.fchmod(handle.fileno(), mode) - json.dump(data, handle, **dump) + handle.write(data) os.replace(staged, path) except OSError as failure: if os.path.exists(staged): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 3e0d48f4..973307cc 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -11,19 +11,19 @@ its session next cycle; the next chunk starts a fresh session. Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with -unreadable state, or the worker or the judge fails three times running. A worker fails when claude -cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot -start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, -or quotes nothing in the transcript. +leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a +reload with unreadable state, or the worker or the judge fails three times running. A worker fails +when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when +claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a +question, or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, -or to / outside it, deleted when the chunk finishes. Its transcript is archived under -$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and -when the chunk finishes. +or to / outside it, deleted when the chunk finishes. At every interrupt and when the chunk finishes +its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default +~/.claude/loop-claude-transcripts), the verdict beside it in .verdict.md. Every claude it 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 run, is asked for one. diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 432645f9..5e4fef8d 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -224,19 +224,22 @@ class JudgePrompt(unittest.TestCase): class Archive(unittest.TestCase): - def test_keeps_the_copy_and_every_folder_it_creates_as_private_as_the_transcript(self): + def test_keeps_one_copy_per_content_and_every_folder_it_creates_as_private_as_the_transcript(self): with tempfile.TemporaryDirectory() as root: transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")}) - cycle.archive("/srv/a/b", transcript, "note", paths) - [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] - self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) - folder = os.path.dirname(copy) + with unittest.mock.patch("sys.stderr"): + for _ in range(2): + self.assertIsNone(cycle.archive("/srv/a/b", transcript, "note", paths)) + copies = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] + self.assertEqual(len(copies), 2) + for copy in copies: + self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) + folder = os.path.dirname(copies[0]) while folder != root: self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder) folder = os.path.dirname(folder) - self.assertIn("said", pathlib.Path(copy).read_text()) class Said(unittest.TestCase): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 51f84aff..8ca5735b 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -1,4 +1,5 @@ import dataclasses +import hashlib import json import os import pathlib @@ -229,8 +230,19 @@ class Checkout: def transcripts(self): return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) + def archive(self): + return self.home / ".claude" / "loop-claude-transcripts" + def archived(self): - return sorted((self.home / ".claude" / "loop-claude-transcripts" / "proj").glob("*")) + """Each archived transcript's verdict, after checking the copy is named by its content hash.""" + verdicts = {} + 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): + self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) + verdicts[copy.read_text()] = verdict.read_text() + return verdicts def argument(call, flag): @@ -292,9 +304,22 @@ class Cycles(unittest.TestCase): self.assertIn("landed-it", run.calls[3]["stdin"]) self.assertNotIn("landed-it", run.calls[5]["stdin"]) self.assertIn("=== cycle 3 ===", run.stdout) - self.assertTrue(checkout.archived()) - for archived in checkout.archived(): - self.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) + [(copy, verdict)] = checkout.archived().items() + self.assertIn('"text": "landed-it"', copy) + self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: finished\n") + + def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self): + checkout = Checkout(self) + checkout.archive().parent.mkdir(parents=True) + checkout.archive().write_text("in the way") + 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$") + session = argument(run.calls[0], "--session-id") + checkout.archive().unlink() + run = checkout.run([worker(), judge(finished=True)]) + self.assertEqual(argument(run.calls[0], "--resume"), session) + self.assertEqual(len(checkout.archived()), 1) def test_stops_after_three_failures_running_retrying_a_minute_apart(self): checkout = Checkout(self) @@ -377,11 +402,14 @@ class Interrupt(unittest.TestCase): run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) 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"]) - self.assertTrue(checkout.archived()) + [(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") session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) + self.assertEqual(len(checkout.archived()), 2) self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): diff --git a/docs/decisions.md b/docs/decisions.md index 598eb123..1ce66849 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -70,7 +70,7 @@ ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp collapses two states. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. ## loop-claude: the rebuild keeps main's `--reloaded` state diff --git a/todo.md b/todo.md index 5d0c0702..0731d05d 100644 --- a/todo.md +++ b/todo.md @@ -6,11 +6,11 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. +- **Link the archive decision in `docs/decisions.md` to a goal that covers it.** It cites goal 2, but the archive is git-ignored and goal 3 keeps transcripts off the remote, so it backs nothing up; goal 4 (reviewing unattended runs) is the nearest, and the human picks. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 run, and open its PR into main for the human.** ⚠️ Leave that PR ready and unmerged: only the human merges it, after approving the whole rebuild. A dimension under the floor gets its places filed above this item. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`).