Run loop-claude on a model saved per project, asking for it on the first run

This commit is contained in:
2026-09-26 19:45:33 +02:00
parent 7d99d49ffb
commit 99dc0cf0da
3 changed files with 144 additions and 33 deletions
+1 -1
View File
@@ -11,6 +11,6 @@
- `loop-claude` says why when it cannot read `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
- `loop-claude` takes an edit to itself at the next cycle boundary once the edited file answers `--help`, and exits 1 when the edited file cannot read the running loop's state.
- `loop-claude --help` names the Claude Code version its transcript, session and trust handling were observed on; check it first when an upgrade breaks a cycle.
- `loop-claude` runs the model each project's settings pick; `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL` override it.
- `loop-claude` runs every claude it starts, the interrupt included, on the project's model, saved in `~/.claude/loop-claude-models.json` and asked for from Claude Code's model catalog on a project's first run; `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL` override it.
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
+88 -20
View File
@@ -10,21 +10,24 @@ 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, claude leaves no transcript, a reload with
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 and stdin or stdout is not a terminal, or the interrupt ended without
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
$LOOP_CLAUDE_TRANSCRIPTS/<path>/ (default ~/.claude/loop-claude-transcripts) whenever the human is
asked and when the chunk finishes. LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL override the
model the project's Claude Code settings pick. A change to this file takes effect at the next cycle
boundary, once the new file answers --help.
asked and when the chunk finishes.
Claude Code internals this rests on, observed on 2.1.282:
Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json
and read each cycle; the first run in a project asks for it. LOOP_CLAUDE_JUDGE_MODEL and
LOOP_CLAUDE_WORKER_MODEL override it. A change to this file takes effect at the next cycle boundary,
once the new file answers --help.
Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283:
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
folder and <session-id>.superseded-*/ and .orphaned-*.jsonl siblings belong to the same session.
- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one
@@ -34,6 +37,8 @@ Claude Code internals this rests on, observed on 2.1.282:
- `claude -p --output-format json --json-schema` returns the verdict under "structured_output".
- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words.
- ~/.claude.json holds projects.<path>.hasTrustDialogAccepted per checkout.
- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest
file has the highest fetchedAt.
"""
import glob
import json
@@ -100,7 +105,7 @@ def main():
premises = read_premises(root)
name = session_name(root)
print(f"\n=== cycle {cycle_number} ===", flush=True)
failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name))
failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), project_model(root))
if not failure:
failures = 0
continue
@@ -111,19 +116,19 @@ def main():
time.sleep(60)
def run_cycle(root, task, premises, name, session_id):
if failure := run_worker(root, worker_args(task, name, session_id, resuming=session_open(session_id))):
def run_cycle(root, task, premises, name, session_id, chosen):
if failure := run_worker(root, worker_args(task, name, session_id, chosen, resuming=session_open(session_id))):
return failure
path = session_file(session_id)
if not path:
sys.exit(f"claude left no transcript for session {session_id}")
verdict = judge(root, task, premises, render(entries(path)))
verdict = judge(root, task, premises, render(entries(path)), chosen)
while verdict["ask"]:
archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if failure := interrupt(root, session_id, path, verdict["question"]):
if failure := interrupt(root, session_id, chosen, path, verdict["question"]):
print(failure, file=sys.stderr)
sys.exit(2)
verdict = judge(root, task, premises, render(entries(path)))
verdict = judge(root, task, premises, render(entries(path)), chosen)
if verdict["finished"]:
archive(root, path, f"Task: {task}\n\nVerdict: finished")
delete_transcript_files(path)
@@ -220,14 +225,77 @@ def make_private(folder):
os.umask(mask)
def model(variable):
return ["--model", os.environ[variable]] if os.environ.get(variable) else []
def model(variable, chosen):
return ["--model", os.environ.get(variable) or chosen]
def project(root):
return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/")
# ~/.claude/loop-claude-models.json
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"
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]
def ask_model(name, saved):
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print(f"{name} has no model in {saved} to run, and stdin or stdout is not a terminal to ask on", file=sys.stderr)
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)
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:
return answer
def catalog():
newest = {}
for path in glob.glob(os.path.expanduser("~/.claude/cache/model-catalog/*.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.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)]
# The transcript file
@@ -302,7 +370,7 @@ def run_worker(root, args):
return "" if done else "claude exited 0 without a result event"
def worker_args(task, name, session_id, resuming):
def worker_args(task, name, session_id, chosen, resuming):
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
else:
@@ -312,7 +380,7 @@ def worker_args(task, name, session_id, resuming):
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
*model("LOOP_CLAUDE_WORKER_MODEL"),
*model("LOOP_CLAUDE_WORKER_MODEL", chosen),
]
@@ -339,11 +407,11 @@ def said(part, limit=400):
# --json-schema verdicts
def judge(root, task, premises, transcript):
def judge(root, task, premises, transcript, chosen):
args = [
"-p",
"--json-schema", json.dumps(JUDGE_SCHEMA),
*model("LOOP_CLAUDE_JUDGE_MODEL"),
*model("LOOP_CLAUDE_JUDGE_MODEL", chosen),
"--no-session-persistence",
"--output-format", "json",
"--permission-mode", "bypassPermissions",
@@ -389,13 +457,13 @@ def grounded(verdict, transcript):
# ~/.claude.json
def interrupt(root, session_id, path, question):
def interrupt(root, session_id, chosen, path, question):
print(f"\n{question}", file=sys.stderr)
if not (sys.stdin.isatty() and sys.stdout.isatty()):
return "stdin or stdout is not a terminal"
trust(checkouts(root))
before = human_turns(entries(path))
subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
subprocess.run(["claude", *model("LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
+55 -12
View File
@@ -124,26 +124,65 @@ class Project(unittest.TestCase):
class WorkerArgs(unittest.TestCase):
def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self):
args = loop.worker_args("the task", "A name", SESSION_ID, resuming=False)
args = loop.worker_args("the task", "A name", SESSION_ID, "m", resuming=False)
self.assertIn("--session-id", args)
self.assertEqual(args[args.index("--name") + 1], "A name")
self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR"))
def test_a_resumed_cycle_reuses_the_session(self):
args = loop.worker_args("paint the fence", "A name", SESSION_ID, resuming=True)
args = loop.worker_args("paint the fence", "A name", SESSION_ID, "m", resuming=True)
self.assertEqual(args[args.index("--resume") + 1], SESSION_ID)
self.assertNotIn("--name", args)
self.assertNotIn("paint the fence", args[1])
def test_the_project_settings_pick_the_model_unless_the_environment_names_one(self):
def test_the_project_model_runs_unless_the_environment_names_one(self):
with unittest.mock.patch.dict(os.environ):
os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None)
self.assertNotIn("--model", loop.worker_args("t", "n", SESSION_ID, resuming=False))
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}):
args = loop.worker_args("t", "n", SESSION_ID, resuming=False)
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1")
class ProjectModel(unittest.TestCase):
def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()):
saved = pathlib.Path(home, ".claude", "loop-claude-models.json")
catalog = pathlib.Path(home, ".claude", "cache", "model-catalog")
catalog.mkdir(parents=True)
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
with unittest.mock.patch("sys.stdin.isatty", return_value=False), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/a")
self.assertEqual(stopped.exception.code, 2)
self.assertFalse(saved.exists())
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed,
):
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.assertNotIn("claude-opus-5)", sys.stderr.getvalue())
typed.side_effect = ["opus[1m]"]
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)
typed.side_effect = EOFError
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]"})
for broken in ("{", "[]", '{"srv/a": 1}'):
saved.write_text(broken)
with self.subTest(broken=broken), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/a")
self.assertTrue(stopped.exception.code.startswith(f"could not read {saved}: "))
self.assertEqual(saved.read_text(), broken)
class JudgePrompt(unittest.TestCase):
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
prompt = loop.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
@@ -198,18 +237,19 @@ class Interrupt(unittest.TestCase):
transcript = os.path.join(root, "session.jsonl")
open(transcript, "w").write("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "stdin or stdout is not a terminal")
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "stdin or stdout is not a terminal")
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything")
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "the interrupt ended without the human typing anything")
mocks["checkouts"].assert_called_with(root)
self.assertEqual(run.call_args.kwargs["cwd"], root)
self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m")
run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n")
self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "")
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "")
class Trust(unittest.TestCase):
@@ -321,10 +361,10 @@ class RunCycle(unittest.TestCase):
environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts}
with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False):
for _ in range(3):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID), "")
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID)
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
self.assertEqual(stopped.exception.code, 2)
said = "".join(str(call.args[0]) for call in stderr.write.call_args_list)
self.assertIn(f"transcript: {loop.ARCHIVE}", said)
@@ -332,7 +372,7 @@ class RunCycle(unittest.TestCase):
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
open(verdicts, "w").write(plan)
with self.assertRaises(SystemExit) as stopped:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID)
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
self.assertTrue(stopped.exception.code.startswith("the judge "))
if plan.startswith("unquoted"):
self.assertIn("asking: q?", stopped.exception.code)
@@ -342,6 +382,7 @@ class RunCycle(unittest.TestCase):
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(sleep.call_count, 6)
self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, open(calls))}, {"claude-opus-5-5"})
class Reload(unittest.TestCase):
@@ -368,7 +409,7 @@ class Main(unittest.TestCase):
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
def test_resumes_the_root_and_counters_a_reload_handed_over(self):
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle")]
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
with contextlib.ExitStack() as stack:
mocks = [stack.enter_context(patch) for patch in patches]
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]))
@@ -380,6 +421,8 @@ class Main(unittest.TestCase):
mocks[1].assert_called_once_with("/r")
mocks[2].assert_called_once_with("/r", "do it", 3, 2)
self.assertEqual(mocks[3].call_args.args[0], "/r")
mocks[4].assert_called_once_with("/r")
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"]))
mocks[0].return_value = "/s"
with self.assertRaises(SystemExit):