Gather every Claude Code format loop-claude reads into claude_code.py, verified on 2.1.284

This commit is contained in:
2026-09-28 20:17:39 +02:00
parent b7538bd21d
commit 80629fc6d9
9 changed files with 158 additions and 114 deletions
+133
View File
@@ -0,0 +1,133 @@
"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it."""
import enum
import glob
import json
import os
from loop_claude.outcome import Failure
class UserEntryKind(enum.Enum):
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind."""
COMMAND = enum.auto()
CTRL_C = enum.auto()
EMPTY = enum.auto()
HUMAN = enum.auto()
META = enum.auto()
NON_TEXT = enum.auto()
SDK_PROMPT = enum.auto()
# <projects>/-home-me-code-log/<session id>.jsonl
def transcript_path(projects, session_id):
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
return hit[0] if hit else ""
# <session id>.jsonl, <session id>/subagents/, <session id>.superseded-1789290815002/
def session_files(transcript):
return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")
# One line of a transcript or of stream-json, or --output-format json's whole output.
def parse(raw):
try:
entry = json.loads(raw)
except ValueError:
return None
return entry if isinstance(entry, dict) else None
# {"type": "user", "message": {"role": "user", "content": "merge it"}}
def content(entry):
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
# {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
def parts(entry):
found = content(entry)
return found if isinstance(found, list) else []
def user_entry_kind(entry):
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
if entry.get("isMeta"):
return UserEntryKind.META
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
if entry.get("promptSource") == "sdk":
return UserEntryKind.SDK_PROMPT
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
if isinstance(text := content(entry), str):
return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN
if not parts(entry):
return UserEntryKind.EMPTY
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)):
return UserEntryKind.NON_TEXT
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
if any(part["text"].startswith("[Request interrupted") for part in parts(entry)):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
def typed(entry):
return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN
# An "assistant" entry's part, alike in the transcript and in stream-json:
# {"type": "text", "text": "ok"}, {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def said(part, limit=400):
kind = part.get("type") if isinstance(part, dict) else None
if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip():
return part["text"]
if kind == "tool_use":
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
return ""
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event):
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout):
return (parse(stdout) or {}).get("structured_output")
# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def trust_records(config):
projects = config.setdefault("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
return projects
def mark_trusted(projects, roots):
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
for path in untrusted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
return untrusted
# <model catalog>/*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
# The newest file has the highest fetchedAt.
def catalog(folder):
newest = {}
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
+3 -4
View File
@@ -2,9 +2,9 @@ import itertools
import json
import subprocess
from loop_claude.claude_code import structured_output
from loop_claude.outcome import Failure
from loop_claude.strike import strike
from loop_claude.transcript import parse
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -40,7 +40,7 @@ JUDGE_SCHEMA = {
def judge(root, task, premises, transcript, model):
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
# Without --bare, Claude Code 2.1.282's claude -p loads the project's and ~/.claude's CLAUDE.md.
# Without --bare, claude -p loads the project's and ~/.claude's CLAUDE.md.
args = [
"-p",
"--json-schema", json.dumps(JUDGE_SCHEMA),
@@ -72,8 +72,7 @@ def run_judge(root, args, prompt):
return Failure(f"could not start claude: {failure.strerror}")
if proc.returncode != 0:
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
# Where Claude Code 2.1.282 puts the --json-schema output.
return (parse(proc.stdout) or {}).get("structured_output")
return structured_output(proc.stdout)
def judge_prompt(task, premises, transcript):
+1 -17
View File
@@ -4,6 +4,7 @@ import sys
from loop_claude import human
from loop_claude.checkout import project_name
from loop_claude.claude_code import catalog
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Stop
@@ -79,20 +80,3 @@ def ask_model(name, saved, folder):
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
print(f"pick 1 to {len(offered)}", file=sys.stderr)
# Claude Code 2.1.283's model cache; the newest file has the highest fetchedAt.
def catalog(folder):
newest = {}
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
+3 -6
View File
@@ -1,5 +1,4 @@
import dataclasses
import glob
import os
import pathlib
import shutil
@@ -7,6 +6,7 @@ import sys
import uuid
from loop_claude.checkout import project_name
from loop_claude.claude_code import session_files, transcript_path
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@@ -27,17 +27,14 @@ def session_for(root, paths):
def transcript_file(session):
# Where Claude Code 2.1.282 writes a session's transcript.
hit = glob.glob(os.path.join(glob.escape(str(session.projects)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
return transcript_path(session.projects, session.id)
def delete_session(session):
path = transcript_file(session)
if not path:
return
# Claude Code 2.1.282 also keeps a <id>/ folder and <id>.superseded-*/ and <id>.orphaned-*.jsonl siblings.
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
for sibling in session_files(path):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
+1 -64
View File
@@ -1,21 +1,7 @@
import enum
import json
from loop_claude.claude_code import content, parse, parts, said, typed
from loop_claude.outcome import Failure
class UserEntryKind(enum.Enum):
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind."""
COMMAND = enum.auto()
CTRL_C = enum.auto()
EMPTY = enum.auto()
HUMAN = enum.auto()
META = enum.auto()
NON_TEXT = enum.auto()
SDK_PROMPT = enum.auto()
def read(path):
try:
with open(path, "rb") as handle:
@@ -24,45 +10,6 @@ def read(path):
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def parse(raw):
try:
entry = json.loads(raw)
except ValueError:
return None
return entry if isinstance(entry, dict) else None
def content(entry):
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry):
found = content(entry)
return found if isinstance(found, list) else []
# Claude Code 2.1.282 writes "user" entries of its own, a claude -p prompt among them.
def user_entry_kind(entry):
if entry.get("isMeta"):
return UserEntryKind.META
if entry.get("promptSource") == "sdk":
return UserEntryKind.SDK_PROMPT
if isinstance(text := content(entry), str):
return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN
if not parts(entry):
return UserEntryKind.EMPTY
if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)):
return UserEntryKind.NON_TEXT
if any(part["text"].startswith("[Request interrupted") for part in parts(entry)):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
def typed(entry):
return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN
def human_turns(entries):
return sum(1 for entry in entries if typed(entry))
@@ -76,13 +23,3 @@ def render(entries):
text = content(entry)
lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text)))
return "\n\n".join(lines)
# An "assistant" entry's parts, alike in the transcript and in stream-json on Claude Code 2.1.282.
def said(part, limit=400):
kind = part.get("type") if isinstance(part, dict) else None
if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip():
return part["text"]
if kind == "tool_use":
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
return ""
+6 -10
View File
@@ -1,7 +1,9 @@
import json
import sys
from loop_claude.claude_code import mark_trusted, trust_records
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Failure
def trust(config, roots):
@@ -11,19 +13,13 @@ def trust(config, roots):
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
return
projects = data.setdefault("projects", {}) if isinstance(data, dict) else None
if not isinstance(projects, dict):
print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr)
projects = trust_records(data)
if isinstance(projects, Failure):
print(f"could not read {config}: {projects.reason}", file=sys.stderr)
return
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr)
return
# Where Claude Code 2.1.282 keeps a checkout's trust.
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
untrusted = mark_trusted(projects, roots)
if not untrusted:
return
for path in untrusted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
if failure := replace_json(config, data, indent=2):
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
return
+2 -3
View File
@@ -1,7 +1,7 @@
import subprocess
from loop_claude.outcome import Failure
from loop_claude.transcript import parse, parts, said
from loop_claude.claude_code import ends_stream, parse, parts, said
def run_worker(root, args):
@@ -13,8 +13,7 @@ def run_worker(root, args):
done = False
for raw in proc.stdout:
event = parse(raw) or {}
# Claude Code 2.1.282's stream-json ends with a "result" event.
if event.get("type") == "result":
if ends_stream(event):
done = True
elif event.get("type") == "assistant":
for part in parts(event):
+8 -8
View File
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import file_writes, judge, main, premises, transcript
from loop_claude import claude_code, file_writes, judge, main, premises, transcript
from loop_claude.outcome import Stop
CWD = pathlib.Path("/c")
@@ -58,17 +58,17 @@ class HumanTurns(unittest.TestCase):
class Said(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi")
self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "")
self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.said("not a part"), "")
self.assertEqual(claude_code.said({"type": "text", "text": "hi"}), "hi")
self.assertEqual(claude_code.said({"type": "text", "text": " \n"}), "")
self.assertEqual(claude_code.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(claude_code.said("not a part"), "")
class Parse(unittest.TestCase):
def test_yields_only_json_objects(self):
self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(transcript.parse("not json"))
self.assertIsNone(transcript.parse("[1, 2]"))
self.assertEqual(claude_code.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(claude_code.parse("not json"))
self.assertIsNone(claude_code.parse("[1, 2]"))
class Grounded(unittest.TestCase):
+1 -2
View File
@@ -8,14 +8,13 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba
The panel on `rebuild` at 37edc9a scored Self-sufficiency 6.5, Locality 6.63 and Shape 6.88 (`docs/decisions.md`). The places its seats named, capping dimension first:
- **Gather every Claude Code format loop-claude parses into one adapter, each shown by a sample of what it reads, under one verified version.** All four seats: `transcript.py` `user_entry_kind`, the stream-json result (`worker.py`), the trust key (`trust.py`), `structured_output` (`judge.py`), the model cache (`models.py` `catalog`); today eight comments pin 2.1.282 and `models.py` 2.1.283.
- **State in larv-review's §3 what a pass's run is, and whether a Stage 0 rerun, a panel rerun after a floor fix, an auto-reviewer re-review and a 🔀 escalation each count against the round cap.** Four seats reread the re-entry rule with the table, `principles/review-findings.md` → "Rounds" and the Vocabulary open; round and run name one thing.
- **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input).
- **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn, which nothing at `cycle.py` says.
- **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three.
- **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats.
- **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`).
- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; the adapter above is the first group.
- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group.
- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the last 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`).
## 0.2.0