Move the judge, the interrupt, trust and model resolution into their own modules
This commit is contained in:
@@ -9,7 +9,6 @@ Decisions live in `docs/decisions.md`:
|
||||
- loop-claude: one session per project, at a fixed id
|
||||
- loop-claude: the trust file is rewritten before an interrupt
|
||||
- loop-claude: every worktree of the checkout is trusted before an interrupt
|
||||
- loop-claude: a wrong-shape trust file gets one message, naming the shape
|
||||
- bin/: the Python floor is README's Install prerequisite
|
||||
- bin/: host python, no container
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it
|
||||
|
||||
+3
-1
@@ -5,6 +5,8 @@
|
||||
- First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does.
|
||||
- `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.
|
||||
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
|
||||
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog.
|
||||
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
|
||||
- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1.
|
||||
- `loop-claude`'s exit-2 message says what the human is needed for.
|
||||
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
|
||||
|
||||
+9
-239
@@ -1,53 +1,21 @@
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from loop_claude.checkout import checkouts, project_name
|
||||
from loop_claude.checkout import project_name
|
||||
from loop_claude.interrupt import interrupt
|
||||
from loop_claude.judge import judge
|
||||
from loop_claude.outcome import Continue, Failure, Retry, Stop
|
||||
from loop_claude.private_file import make_private
|
||||
from loop_claude.session import delete_session, session_for, transcript_file
|
||||
from loop_claude.strike import strike
|
||||
from loop_claude.transcript import human_turns, parse, read, render
|
||||
from loop_claude.transcript import read, render
|
||||
from loop_claude.worker import run_worker, worker_args
|
||||
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
|
||||
"- it carried on under an assumption that decides the deliverable and that the human could "
|
||||
"reasonably reject; a caveat about transient state it then handled is not one\n"
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
|
||||
"ready to cut, a choice outside the repo\n"
|
||||
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
|
||||
"- it chose between alternatives the README text does not discriminate between - it does not "
|
||||
"rule the rejected one out - and the choice materially changes the deliverable\n"
|
||||
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there.\n"
|
||||
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
||||
"wording; never construct another from facts it stated.\n"
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
||||
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
|
||||
"not yet run, CI not yet reported."
|
||||
)
|
||||
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {
|
||||
"evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"},
|
||||
"finished": {"type": "boolean"},
|
||||
"interrupt": {"type": "boolean"},
|
||||
"question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"},
|
||||
},
|
||||
"required": ["evidence", "finished", "interrupt", "question"],
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
def run_cycle(root, task, premises, chosen, paths, env):
|
||||
def run_cycle(root, task, premises, models, paths):
|
||||
session = session_for(root, paths)
|
||||
resuming = bool(transcript_file(session))
|
||||
if failure := run_worker(root, worker_args(task, session, model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), resuming)):
|
||||
if failure := run_worker(root, worker_args(task, session, models.worker, resuming)):
|
||||
return Retry(failure.reason)
|
||||
path = transcript_file(session)
|
||||
if not path:
|
||||
@@ -57,13 +25,13 @@ def run_cycle(root, task, premises, chosen, paths, env):
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(root, task, premises, render(entries), chosen, env)
|
||||
verdict = judge(root, task, premises, render(entries), models.judge)
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if not verdict["interrupt"]:
|
||||
break
|
||||
archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths)
|
||||
if stop := interrupt(root, session.id, chosen, path, verdict["question"], paths, env):
|
||||
if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths):
|
||||
return stop
|
||||
if verdict["finished"]:
|
||||
archive(root, path, f"Task: {task}\n\nVerdict: finished", paths)
|
||||
@@ -89,201 +57,3 @@ def archive(root, path, note, paths):
|
||||
print(f"transcript: {dest}", file=sys.stderr)
|
||||
except OSError as failure:
|
||||
print(f"could not archive the transcript: {failure}", file=sys.stderr)
|
||||
|
||||
|
||||
def make_private(folder):
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
finally:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def replace_json(path, data, **dump):
|
||||
staged = f"{path}.{os.getpid()}"
|
||||
try:
|
||||
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
|
||||
with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:
|
||||
os.fchmod(handle.fileno(), mode)
|
||||
json.dump(data, handle, **dump)
|
||||
os.replace(staged, path)
|
||||
except OSError as failure:
|
||||
if os.path.exists(staged):
|
||||
os.remove(staged)
|
||||
return failure
|
||||
return None
|
||||
|
||||
|
||||
def model_for(env, variable, chosen):
|
||||
return env.get(variable) or chosen
|
||||
|
||||
|
||||
# ~/.claude/loop-claude-models.json
|
||||
|
||||
|
||||
def project_model(root, paths, env):
|
||||
if env.get("LOOP_CLAUDE_JUDGE_MODEL") and env.get("LOOP_CLAUDE_WORKER_MODEL"):
|
||||
return ""
|
||||
saved = paths.models_file
|
||||
name = project_name(root, paths.code)
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if chosen := models.get(name):
|
||||
return chosen
|
||||
chosen = ask_model(name, saved, paths.model_catalog)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.strerror}")
|
||||
print(f"{name} runs on {chosen}", file=sys.stderr)
|
||||
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:
|
||||
return Stop(1, 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()):
|
||||
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
|
||||
return models
|
||||
|
||||
|
||||
def ask_model(name, saved, folder):
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"<model>\"}} into {saved}")
|
||||
offered = catalog(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)
|
||||
if not offered:
|
||||
print(f" no model catalog cached in {folder}", file=sys.stderr)
|
||||
while True:
|
||||
try:
|
||||
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return Stop(2, "no model picked")
|
||||
if not answer:
|
||||
continue
|
||||
if not (offered and 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(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 []
|
||||
|
||||
|
||||
# --json-schema verdicts
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript, chosen, env):
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
args = [
|
||||
"-p",
|
||||
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
||||
"--model", model_for(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen),
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
for failures in itertools.count(1):
|
||||
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
|
||||
verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None
|
||||
if not complete(verdict):
|
||||
failure = proc.stderr.strip() or "the judge returned no verdict"
|
||||
elif not grounded(verdict, transcript):
|
||||
failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}"
|
||||
else:
|
||||
return verdict
|
||||
if stop := strike("judge", failures, failure):
|
||||
return stop
|
||||
|
||||
|
||||
def judge_prompt(task, premises, transcript):
|
||||
return (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The task an agent was given:\n{task}\n\n"
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
|
||||
f"{JUDGE_RULES}"
|
||||
)
|
||||
|
||||
|
||||
def complete(verdict):
|
||||
return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys()
|
||||
|
||||
|
||||
def grounded(verdict, transcript):
|
||||
if not verdict["interrupt"]:
|
||||
return True
|
||||
evidence = verdict["evidence"]
|
||||
return evidence.strip() != "" and evidence in transcript
|
||||
|
||||
|
||||
# ~/.claude.json
|
||||
|
||||
|
||||
def interrupt(root, session_id, chosen, path, question, paths, env):
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
return Stop(2, "stdin or stdout is not a terminal")
|
||||
trust(paths.claude_json, checkouts(root))
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
if human_turns(entries) <= before:
|
||||
return Stop(2, "the interrupt ended without the human typing anything")
|
||||
return None
|
||||
|
||||
|
||||
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 = data.setdefault("projects", {}) if isinstance(data, dict) else None
|
||||
if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()):
|
||||
print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr)
|
||||
return
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
if not untrusted:
|
||||
return
|
||||
for path in untrusted:
|
||||
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
|
||||
if failure := replace_json(config, data, indent=2):
|
||||
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import sys
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def needed(to, but):
|
||||
return Stop(2, f"the human is needed to {to}, but {but}")
|
||||
|
||||
|
||||
def off_terminal(to):
|
||||
if sys.stdin.isatty() and sys.stdout.isatty():
|
||||
return None
|
||||
return needed(to, "stdin or stdout is not a terminal")
|
||||
@@ -0,0 +1,31 @@
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from loop_claude import human
|
||||
from loop_claude.checkout import checkouts
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.transcript import human_turns, read
|
||||
from loop_claude.trust import trust
|
||||
|
||||
TO = "answer the question above"
|
||||
|
||||
|
||||
def interrupt(root, session_id, model, path, question, paths):
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := human.off_terminal(TO):
|
||||
return stop
|
||||
trust(paths.claude_json, checkouts(root))
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
try:
|
||||
subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not start claude: {failure.strerror}")
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
if human_turns(entries) <= before:
|
||||
return human.needed(TO, "the interrupt ended without you typing anything")
|
||||
return None
|
||||
@@ -0,0 +1,95 @@
|
||||
import itertools
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.strike import strike
|
||||
from loop_claude.transcript import parse
|
||||
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
|
||||
"- it carried on under an assumption that decides the deliverable and that the human could "
|
||||
"reasonably reject; a caveat about transient state it then handled is not one\n"
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
|
||||
"ready to cut, a choice outside the repo\n"
|
||||
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
|
||||
"- it chose between alternatives the README text does not discriminate between - it does not "
|
||||
"rule the rejected one out - and the choice materially changes the deliverable\n"
|
||||
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there.\n"
|
||||
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
||||
"wording; never construct another from facts it stated.\n"
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
||||
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
|
||||
"not yet run, CI not yet reported."
|
||||
)
|
||||
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {
|
||||
"evidence": {"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining.", "type": "string"},
|
||||
"finished": {"type": "boolean"},
|
||||
"interrupt": {"type": "boolean"},
|
||||
"question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"},
|
||||
},
|
||||
"required": ["evidence", "finished", "interrupt", "question"],
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript, model):
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
args = [
|
||||
"-p",
|
||||
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
||||
"--model", model,
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
for failures in itertools.count(1):
|
||||
verdict = run_judge(root, args, prompt)
|
||||
if isinstance(verdict, Failure):
|
||||
failure = verdict.reason
|
||||
elif not complete(verdict):
|
||||
failure = "the judge returned no verdict"
|
||||
elif not grounded(verdict, transcript):
|
||||
failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "")
|
||||
else:
|
||||
return verdict
|
||||
if stop := strike("judge", failures, failure):
|
||||
return stop
|
||||
|
||||
|
||||
def run_judge(root, args, prompt):
|
||||
try:
|
||||
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
||||
return (parse(proc.stdout) or {}).get("structured_output")
|
||||
|
||||
|
||||
def judge_prompt(task, premises, transcript):
|
||||
return (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The task an agent was given:\n{task}\n\n"
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
|
||||
f"{JUDGE_RULES}"
|
||||
)
|
||||
|
||||
|
||||
def complete(verdict):
|
||||
return isinstance(verdict, dict) and all(
|
||||
isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"]
|
||||
)
|
||||
|
||||
|
||||
def grounded(verdict, transcript):
|
||||
evidence = verdict["evidence"]
|
||||
return evidence.strip() != "" and evidence in transcript
|
||||
+12
-10
@@ -11,12 +11,13 @@ its session next cycle; the next chunk 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, a models file it cannot read or write, claude
|
||||
leaves no transcript or one it cannot read, a reload with unreadable state, or the worker or the
|
||||
judge fails three times running. A worker fails when claude cannot start, 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.
|
||||
leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with
|
||||
unreadable state, or the worker or the judge fails three times running. A worker fails when claude
|
||||
cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot
|
||||
start or exits non-zero, or 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.
|
||||
terminal, the input ends, 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
|
||||
@@ -48,7 +49,8 @@ import dataclasses
|
||||
import sys
|
||||
|
||||
from loop_claude.checkout import checkout_root
|
||||
from loop_claude.cycle import project_model, run_cycle
|
||||
from loop_claude.cycle import run_cycle
|
||||
from loop_claude.models import project_models
|
||||
from loop_claude.outcome import Continue, Retry, Stop
|
||||
from loop_claude.premises import read_premises
|
||||
from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited
|
||||
@@ -84,11 +86,11 @@ def run_loop(argv, env, paths, launcher, cwd):
|
||||
premises = read_premises(state.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
chosen = project_model(state.root, paths, env)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
models = project_models(state.root, paths, env)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||
match run_cycle(state.root, state.task, premises, chosen, paths, env):
|
||||
match run_cycle(state.root, state.task, premises, models, paths):
|
||||
case Stop() as stop:
|
||||
return stop
|
||||
case Retry(failure):
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude import human
|
||||
from loop_claude.checkout import project_name
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.private_file import replace_json
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Models:
|
||||
judge: str
|
||||
worker: str
|
||||
|
||||
|
||||
def project_models(root, paths, env):
|
||||
"""LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL, each falling back to the project's saved model."""
|
||||
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
|
||||
if judge and worker:
|
||||
return Models(judge, worker)
|
||||
chosen = project_model(project_name(root, paths.code), paths)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
return Models(judge or chosen, worker or chosen)
|
||||
|
||||
|
||||
def project_model(name, paths):
|
||||
saved = paths.models_file
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if chosen := models.get(name):
|
||||
return chosen
|
||||
chosen = ask_model(name, saved, paths.model_catalog)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.strerror}")
|
||||
print(f"{name} runs on {chosen}", file=sys.stderr)
|
||||
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:
|
||||
return Stop(1, 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()):
|
||||
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
|
||||
return models
|
||||
|
||||
|
||||
def ask_model(name, saved, folder):
|
||||
if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}"):
|
||||
return stop
|
||||
offered = catalog(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)
|
||||
if not offered:
|
||||
print(f" no model catalog cached in {folder}", file=sys.stderr)
|
||||
while True:
|
||||
try:
|
||||
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return human.needed(f"pick {name}'s model", "the input ended")
|
||||
if not answer:
|
||||
continue
|
||||
if not (offered and 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(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 []
|
||||
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def make_private(folder):
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
finally:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def replace_json(path, data, **dump):
|
||||
staged = f"{path}.{os.getpid()}"
|
||||
try:
|
||||
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
|
||||
with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:
|
||||
os.fchmod(handle.fileno(), mode)
|
||||
json.dump(data, handle, **dump)
|
||||
os.replace(staged, path)
|
||||
except OSError as failure:
|
||||
if os.path.exists(staged):
|
||||
os.remove(staged)
|
||||
return failure
|
||||
return None
|
||||
@@ -0,0 +1,29 @@
|
||||
import json
|
||||
import sys
|
||||
|
||||
from loop_claude.private_file import replace_json
|
||||
|
||||
|
||||
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 = data.setdefault("projects", {}) if isinstance(data, dict) else None
|
||||
if not isinstance(projects, dict):
|
||||
print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr)
|
||||
return
|
||||
if wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None):
|
||||
print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr)
|
||||
return
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
if not untrusted:
|
||||
return
|
||||
for path in untrusted:
|
||||
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
|
||||
if failure := replace_json(config, data, indent=2):
|
||||
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
@@ -20,10 +20,6 @@
|
||||
|
||||
2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path.
|
||||
|
||||
## loop-claude: a wrong-shape trust file gets one message, naming the shape
|
||||
|
||||
2026-09-26, larv-review, declining a product-owner nit. Serves goal 4. `trust` says `not an object whose "projects" maps paths to objects` for every wrong shape; naming the failing path would add a branch to `trust`, and the interrupt still lands in Claude Code's own dialog, which shows the path. The 2026-09-25 panel's `trust` as the unit least wanted to modify was the first reason; the 2026-09-26 panel named `typed`, so the entry rests on the dialog. Valid while the interrupt lands in that dialog.
|
||||
|
||||
## bin/: the Python floor is README's Install prerequisite
|
||||
|
||||
2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python.
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
|
||||
|
||||
- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive.
|
||||
- **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it.
|
||||
- **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds.
|
||||
- **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.**
|
||||
|
||||
Reference in New Issue
Block a user