Keep models another loop saved, exit when the save fails, and survive a malformed catalog
This commit is contained in:
+41
-29
@@ -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
|
||||
|
||||
+15
-2
@@ -165,8 +165,12 @@ class ProjectModel(unittest.TestCase):
|
||||
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
|
||||
self.assertEqual(typed.call_count, 3)
|
||||
self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue())
|
||||
self.assertIn("pick 1 to 2", sys.stderr.getvalue())
|
||||
self.assertNotIn("claude-opus-5)", sys.stderr.getvalue())
|
||||
typed.side_effect = ["opus[1m]"]
|
||||
def saved_elsewhere_while_asking(prompt):
|
||||
saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"}))
|
||||
return "opus[1m]"
|
||||
typed.side_effect = saved_elsewhere_while_asking
|
||||
self.assertEqual(loop.project_model("/srv/b"), "opus[1m]")
|
||||
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
|
||||
self.assertEqual(typed.call_count, 4)
|
||||
@@ -174,7 +178,16 @@ class ProjectModel(unittest.TestCase):
|
||||
with self.assertRaises(SystemExit) as stopped:
|
||||
loop.project_model("/srv/c")
|
||||
self.assertEqual(stopped.exception.code, 2)
|
||||
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]"})
|
||||
typed.side_effect = ["sonnet"]
|
||||
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), self.assertRaises(SystemExit) as stopped:
|
||||
loop.project_model("/srv/c")
|
||||
self.assertEqual(stopped.exception.code, f"could not save the model in {saved}: Permission denied")
|
||||
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
|
||||
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
|
||||
for shape in ({"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}):
|
||||
catalog.joinpath("new.json").write_text(json.dumps(shape))
|
||||
with self.subTest(shape=shape):
|
||||
self.assertEqual(loop.catalog(), [])
|
||||
for broken in ("{", "[]", '{"srv/a": 1}'):
|
||||
saved.write_text(broken)
|
||||
with self.subTest(broken=broken), self.assertRaises(SystemExit) as stopped:
|
||||
|
||||
Reference in New Issue
Block a user