Group loop_claude's modules into claude_code, claude_runs and project, and move the findings document beside larv-review

This commit is contained in:
2026-09-28 21:28:41 +02:00
parent 6a1a1d9027
commit 998cc3ac85
26 changed files with 39 additions and 35 deletions
+144
View File
@@ -0,0 +1,144 @@
"""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()
def locations(home):
return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects"
# <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/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
def session_files(transcript):
return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")
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 []
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
def assistant_parts(entry):
return parts(entry) if entry.get("type") == "assistant" 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": "system", "message": {"content": "<task-notification>..."}}
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
if isinstance(text := content(entry), str):
source = entry.get("promptSource")
return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN
texts = [part_text(part) for part in parts(entry)]
if not texts:
return UserEntryKind.EMPTY
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
if None in texts:
return UserEntryKind.NON_TEXT
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
if any(text.startswith("[Request interrupted") for text in texts):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
def human_text(entry):
"""What the human wrote in the entry, or None where Claude Code wrote it."""
if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN:
return None
text = content(entry)
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
# {"type": "text", "text": "ok"}
def part_text(part):
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part):
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
# 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", ...}]}}}
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 []
+40
View File
@@ -0,0 +1,40 @@
import dataclasses
import os
import pathlib
import shutil
import sys
import uuid
from loop_claude.project.checkout import project_name
from loop_claude.claude_code.formats import session_files, transcript_path
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@dataclasses.dataclass(frozen=True)
class Session:
id: uuid.UUID
name: str
projects: pathlib.Path
def session_for(root, paths):
"""Exists while its transcript does."""
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project_name(root, paths.code)} loop-claude"
return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects)
def transcript_file(session):
return transcript_path(session.projects, session.id)
def delete_session(session):
path = transcript_file(session)
if not path:
return
for sibling in session_files(path):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
+34
View File
@@ -0,0 +1,34 @@
import json
from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call
from loop_claude.outcome import Failure
def read(path):
try:
with open(path, "rb") as handle:
return [entry for raw in handle if (entry := parse(raw))]
except OSError as failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def human_turns(entries):
return sum(1 for entry in entries if human_text(entry) is not None)
def render(entries):
lines = []
for entry in entries:
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
if (text := human_text(entry)) is not None:
lines.append("[human] " + text)
return "\n\n".join(lines)
def part_line(part, limit=400):
if (text := part_text(part)) and text.strip():
return text
if call := tool_call(part):
name, arguments = call
return f"[tool {name}] {json.dumps(arguments)[:limit]}"
return ""
+26
View File
@@ -0,0 +1,26 @@
import json
import sys
from loop_claude.claude_code.formats import mark_trusted, trust_records
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Failure
def trust(config, roots):
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError) as failure:
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
return
projects = trust_records(data)
if isinstance(projects, Failure):
print(f"could not read {config}: {projects.reason}", file=sys.stderr)
return
untrusted = mark_trusted(projects, roots)
if not untrusted:
return
if failure := replace_json(config, data, indent=2):
print(f"could not write {config}: {failure.reason}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)