Archive the raw transcript by content hash with its verdict, and stop on a failed archive

This commit is contained in:
2026-09-28 16:57:24 +02:00
parent 5e3b66232b
commit 6e31e0a833
7 changed files with 75 additions and 41 deletions
+1
View File
@@ -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` 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 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 exit-2 message says what the human is needed for.
- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per content under its SHA-256, with the verdict beside it in `<sha256>.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. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
+19 -20
View File
@@ -1,9 +1,8 @@
import os import hashlib
import sys import sys
import time
from loop_claude.checkout import project_name 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.interrupt import interrupt
from loop_claude.judge import judge from loop_claude.judge import judge
from loop_claude.outcome import Continue, Failure, Retry, Stop 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) path = transcript_file(session)
if not path: if not path:
return Stop(1, f"claude left no transcript for session {session.id}") 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: while True:
entries = read(path) entries = read(path)
if isinstance(entries, Failure): if isinstance(entries, Failure):
@@ -30,30 +29,30 @@ def run_cycle(root, task, premises, models, paths):
return verdict return verdict
if not verdict["interrupt"]: if not verdict["interrupt"]:
break 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): if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths):
return stop return stop
if verdict["finished"]: 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) delete_session(session)
return Continue() return Continue()
def archive(root, path, note, paths): def archive(root, path, note, paths):
# Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. folder = paths.archive / project_name(root, paths.code)
name = project_name(root, paths.code)
folder = paths.archive / name
try: 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) 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: except OSError as failure:
print(f"could not archive the transcript: {failure}", file=sys.stderr) return Failure(f"could not archive the transcript {path}: {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 {path}: {failure.strerror}")
print(f"transcript: {copy}", file=sys.stderr)
return None
+6 -2
View File
@@ -11,12 +11,16 @@ def make_private(folder):
def replace_json(path, data, **dump): 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()}" staged = f"{path}.{os.getpid()}"
try: try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 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) os.fchmod(handle.fileno(), mode)
json.dump(data, handle, **dump) handle.write(data)
os.replace(staged, path) os.replace(staged, path)
except OSError as failure: except OSError as failure:
if os.path.exists(staged): if os.path.exists(staged):
+7 -7
View File
@@ -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". 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 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 leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a
unreadable state, or the worker or the judge fails three times running. A worker fails when claude reload with unreadable state, or the worker or the judge fails three times running. A worker fails
cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when
start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, 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. 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 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 terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
open session. open session.
Each project has one session, "A <path> loop-claude", <path> being the checkout relative to ~/code, Each project has one session, "A <path> loop-claude", <path> being the checkout relative to ~/code,
or to / outside it, deleted when the chunk finishes. Its transcript is archived under or to / outside it, deleted when the chunk finishes. At every interrupt and when the chunk finishes
$LOOP_CLAUDE_TRANSCRIPTS/<path>/ (default ~/.claude/loop-claude-transcripts) at every interrupt and its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS/<path>/<sha256>.jsonl (default
when the chunk finishes. ~/.claude/loop-claude-transcripts), the verdict beside it in <sha256>.verdict.md.
Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json
and read each cycle; a project without an entry, as on its first run, is asked for one. and read each cycle; a project without an entry, as on its first run, is asked for one.
+9 -6
View File
@@ -224,19 +224,22 @@ class JudgePrompt(unittest.TestCase):
class Archive(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: with tempfile.TemporaryDirectory() as root:
transcript = os.path.join(root, "session.jsonl") transcript = os.path.join(root, "session.jsonl")
pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") 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")}) paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")})
cycle.archive("/srv/a/b", transcript, "note", paths) with unittest.mock.patch("sys.stderr"):
[copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] for _ in range(2):
self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) self.assertIsNone(cycle.archive("/srv/a/b", transcript, "note", paths))
folder = os.path.dirname(copy) 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: while folder != root:
self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder) self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder)
folder = os.path.dirname(folder) folder = os.path.dirname(folder)
self.assertIn("said", pathlib.Path(copy).read_text())
class Said(unittest.TestCase): class Said(unittest.TestCase):
+33 -5
View File
@@ -1,4 +1,5 @@
import dataclasses import dataclasses
import hashlib
import json import json
import os import os
import pathlib import pathlib
@@ -229,8 +230,19 @@ class Checkout:
def transcripts(self): def transcripts(self):
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
def archive(self):
return self.home / ".claude" / "loop-claude-transcripts"
def archived(self): 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): def argument(call, flag):
@@ -292,9 +304,22 @@ class Cycles(unittest.TestCase):
self.assertIn("landed-it", run.calls[3]["stdin"]) self.assertIn("landed-it", run.calls[3]["stdin"])
self.assertNotIn("landed-it", run.calls[5]["stdin"]) self.assertNotIn("landed-it", run.calls[5]["stdin"])
self.assertIn("=== cycle 3 ===", run.stdout) self.assertIn("=== cycle 3 ===", run.stdout)
self.assertTrue(checkout.archived()) [(copy, verdict)] = checkout.archived().items()
for archived in checkout.archived(): self.assertIn('"text": "landed-it"', copy)
self.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) 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 .*\.jsonl: ")
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): def test_stops_after_three_failures_running_retrying_a_minute_apart(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -377,11 +402,14 @@ class Interrupt(unittest.TestCase):
run = checkout.run(steps) run = checkout.run(steps)
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) 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.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") session = argument(run.calls[0], "--session-id")
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
self.assertEqual(argument(run.calls[0], "--resume"), session) 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") 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): def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
-1
View File
@@ -6,7 +6,6 @@
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`. 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.** - **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`. - **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. - **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.