Keep models another loop saved, exit when the save fails, and survive a malformed catalog

This commit is contained in:
2026-09-26 19:53:11 +02:00
parent 99dc0cf0da
commit 17960e9bf3
2 changed files with 56 additions and 31 deletions
+41 -29
View File
@@ -10,12 +10,12 @@ interrupt: `claude --resume` on the terminal, every worktree first marked truste
An unfinished chunk resumes the same session next cycle; a finished one 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, an unreadable models file, claude leaves no transcript, a reload with
unreadable state, or the worker or the judge fails three times running. A worker fails when claude
exits non-zero, is killed, or ends without a result event; a judge when its verdict misses a field
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, or the interrupt ended without
them typing anything. Rerunning resumes any open session.
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times
running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a
judge when its verdict misses a field 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, or the interrupt ended without them typing anything. Rerunning resumes any open session.
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
@@ -238,27 +238,35 @@ def project(root):
def project_model(root):
saved = os.path.expanduser("~/.claude/loop-claude-models.json")
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
except FileNotFoundError:
models = {}
except (OSError, ValueError) as failure:
sys.exit(f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
sys.exit(f"could not read {saved}: not an object mapping projects to model names")
name = project(root)
if name in models:
return models[name]
models[name] = ask_model(name, saved)
staged = f"{saved}.staged"
if chosen := read_models(saved).get(name):
return chosen
chosen = ask_model(name, saved)
# Reread: another loop may have saved its project while this one waited on the human.
models = {**read_models(saved), name: chosen}
staged = f"{saved}.{os.getpid()}"
try:
with open(staged, "w", encoding="utf-8") as handle:
json.dump(models, handle, indent="\t", sort_keys=True)
os.replace(staged, saved)
except OSError as failure:
print(f"could not save the model in {saved}: {failure.strerror}", file=sys.stderr)
return models[name]
if os.path.exists(staged):
os.remove(staged)
sys.exit(f"could not save the model in {saved}: {failure.strerror}")
return chosen
def read_models(saved):
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
except FileNotFoundError:
return {}
except (OSError, ValueError) as failure:
sys.exit(f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
sys.exit(f"could not read {saved}: not an object mapping projects to model names")
return models
def ask_model(name, saved):
@@ -267,19 +275,21 @@ def ask_model(name, saved):
sys.exit(2)
offered = catalog()
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
for number, (id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({id})", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr)
while True:
try:
answer = input("A number, or any name claude --model takes: ").strip()
except EOFError:
print("\nno model picked", file=sys.stderr)
sys.exit(2)
if answer.isdigit():
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
elif answer:
if not answer:
continue
if not answer.isdecimal():
return answer
if 1 <= int(answer) <= len(offered):
return offered[int(answer) - 1][0]
print(f"pick 1 to {len(offered)}", file=sys.stderr)
def catalog():
@@ -292,8 +302,10 @@ def catalog():
continue
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest.get("catalog", {}).get("config", {}).get("models", []) if newest else []
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)]
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 []
# The transcript file