Keep formats.py to Claude Code's shapes, with paths and file reads at their callers #135

Merged
lilleman merged 4 commits from formats-shapes into rebuild 2026-09-29 11:53:59 +02:00
6 changed files with 37 additions and 41 deletions
+14
View File
@@ -0,0 +1,14 @@
import json
from loop_claude.claude_code.formats import models_in
def offered_models(folder):
files = []
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
files.append(json.load(handle))
except (OSError, ValueError):
continue
return models_in(files)
+6 -27
View File
@@ -1,26 +1,9 @@
"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it."""
import glob
"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it."""
import json
import os
from loop_claude.outcome import Failure
def locations(home):
return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects"
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_path(claude_code_transcripts, session_id):
hit = glob.glob(os.path.join(glob.escape(str(claude_code_transcripts)), "*", 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)
@@ -101,7 +84,7 @@ def structured_output(stdout):
return (parse(stdout) or {}).get("structured_output")
# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config, roots):
projects = config.get("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
@@ -113,15 +96,11 @@ def mark_trusted(config, roots):
return {**config, "projects": {**projects, **marked}}, untrusted
# <model catalog>/*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def catalog(folder):
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files):
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest = {}
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
for data in files:
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
+7 -5
View File
@@ -1,38 +1,40 @@
import dataclasses
import glob
import os
import pathlib
import shutil
import sys
import uuid
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:
"""Exists while its transcript does."""
id: uuid.UUID
claude_code_transcripts: pathlib.Path
name: str
def session_for(project, 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} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session):
return transcript_path(session.claude_code_transcripts, session.id)
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
def delete_session(session):
path = transcript_file(session)
if not path:
return
for sibling in session_files(path):
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
+3 -6
View File
@@ -1,8 +1,6 @@
import dataclasses
import pathlib
from loop_claude.claude_code.formats import locations
@dataclasses.dataclass(frozen=True)
class Paths:
@@ -16,12 +14,11 @@ class Paths:
def paths_from(home, env):
claude = home / ".claude"
claude_json, model_catalog, claude_code_transcripts = locations(home)
return Paths(
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
claude_code_transcripts=claude_code_transcripts,
claude_json=claude_json,
claude_code_transcripts=claude / "projects",
claude_json=home / ".claude.json",
code=home / "code",
model_catalog=model_catalog,
model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json",
)
+2 -2
View File
@@ -3,7 +3,7 @@ import json
import sys
from loop_claude import human_needed
from loop_claude.claude_code.formats import catalog
from loop_claude.claude_code.catalog import offered_models
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Stop
@@ -60,7 +60,7 @@ def read_models(saved):
def ask_model(name, saved, folder):
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
return stop
offered = catalog(folder)
offered = offered_models(folder)
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr)
+5 -1
View File
@@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens
The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), capping dimension first:
- **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats.
- **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side.
- **Say at `written_by_human` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`.
- **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for.
@@ -21,3 +20,8 @@ The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), cappin
- **Show the judge's reply when `loop-claude` rejects its verdict.** Its stdout is discarded, so a judge that failed three times running leaves nothing to diagnose.
- **Back up `loop-claude`'s transcript archive to a destination other than this repo's remote.**
- **Make the contributor a standing member of every project's audience, dropped only where `## Audience` says maintainability does not matter.** `CLAUDE.md`'s premises rule states it; larv-review's comprehension floor names the contributor as the reader it serves, so the floor gates every chunk while the contributor stands and a project that drops them skips it.
- **Give `docs/decisions.md`'s comprehension-floor and vocabulary entries a premise that has not already expired, with the floor's rule first and its runs' scores as a table, and give the rebuild entry's warning placement its own heading and index line.** A prose pass found both "Valid until the next scoring run" outlived by three runs.
- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`, and inline in `review-findings.md` what a round is.** A prose pass found rejected alternatives at the rule, and a pointer back to `SKILL.md`, which points here.
- **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need.
- **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer.
- **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so.