Move the judge, the interrupt, trust and model resolution into their own modules #99

Merged
lilleman merged 8 commits from rebuild-judge-modules into rebuild 2026-09-28 16:50:49 +02:00
14 changed files with 409 additions and 325 deletions
-2
View File
@@ -9,11 +9,9 @@ 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
- loop-claude: the section headers stay
- vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
- larv-review: a re-entered loop takes a fresh round cap
- loop-claude: a reload into an older file is unsupported
+3 -1
View File
@@ -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 interrupting without a question, 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
View File
@@ -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.file_writes import make_private
from loop_claude.interrupt import interrupt
from loop_claude.judge import judge
from loop_claude.outcome import Continue, Failure, Retry, Stop
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)
+25
View File
@@ -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
+13
View File
@@ -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; rerun loop-claude on a terminal")
+31
View File
@@ -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 for the interrupt: {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 with nothing typed")
return None
+101
View File
@@ -0,0 +1,101 @@
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 reason := incomplete(verdict):
failure = reason
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 incomplete(verdict):
if not isinstance(verdict, dict):
return "the judge returned no verdict"
for name in JUDGE_SCHEMA["required"]:
kind = JUDGE_SCHEMA["properties"][name]["type"]
if not isinstance(verdict.get(name), bool if kind == "boolean" else str):
return f"the judge's verdict has no {name} of type {kind}"
if verdict["interrupt"] and not verdict["question"].strip():
return "the judge interrupted without a question"
return None
def grounded(verdict, transcript):
evidence = verdict["evidence"]
return evidence.strip() != "" and evidence in transcript
+13 -10
View File
@@ -11,12 +11,14 @@ 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 or mistypes a field, interrupts without a question,
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 with nothing typed. 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 +50,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 +87,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):
+97
View File
@@ -0,0 +1,97 @@
import dataclasses
import json
import sys
from loop_claude import human
from loop_claude.checkout import project_name
from loop_claude.file_writes import replace_json
from loop_claude.outcome import Stop
@dataclasses.dataclass(frozen=True)
class Models:
judge: str
worker: str
def project_models(root, paths, env):
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 []
+29
View File
@@ -0,0 +1,29 @@
import json
import sys
from loop_claude.file_writes 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)) is not 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)
+46 -46
View File
@@ -15,7 +15,7 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import checkout, cycle, main, premises, reload, session, transcript, worker
from loop_claude import checkout, cycle, interrupt, judge, main, models, premises, reload, session, transcript, trust, worker
from loop_claude.outcome import Continue, Failure, Retry, Stop
from loop_claude.paths import paths_from
@@ -24,6 +24,7 @@ LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude")
PATHS = paths_from(pathlib.Path("/h"), {})
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects)
OPUS = models.Models("claude-opus-5-5", "claude-opus-5-5")
def assistant(*parts):
@@ -146,10 +147,6 @@ class WorkerArgs(unittest.TestCase):
self.assertNotIn("--name", args)
self.assertNotIn("paint the fence", args[1])
def test_the_project_model_runs_unless_the_environment_names_one(self):
self.assertEqual(cycle.model_for({}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-opus-5-5")
self.assertEqual(cycle.model_for({"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-fable-5-1")
class ProjectModel(unittest.TestCase):
def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self):
@@ -161,19 +158,19 @@ class ProjectModel(unittest.TestCase):
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):
stop = cycle.project_model("/srv/a", paths, {})
stop = models.project_models("/srv/a", paths, {})
self.assertEqual(stop.code, 2)
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', stop.reason)
self.assertFalse(saved.exists())
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "")
self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2)
self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("j", "w"))
self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2)
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(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5")
self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "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())
@@ -185,33 +182,34 @@ class ProjectModel(unittest.TestCase):
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(cycle.project_model("/srv/b", paths, {}), "opus[1m]")
self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5")
self.assertEqual(models.project_models("/srv/b", paths, {}), models.Models("opus[1m]", "opus[1m]"))
self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5"))
self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("claude-sonnet-5", "w"))
self.assertEqual(typed.call_count, 4)
typed.side_effect = EOFError
self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked"))
self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(2, "the human is needed to pick srv/c's model, but the input ended"))
typed.side_effect = ["sonnet"]
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied"))
self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(1, 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(stat.S_IMODE(saved.stat().st_mode), 0o640)
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"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(cycle.catalog(catalog), [])
self.assertEqual(models.catalog(catalog), [])
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=["1"]) as typed,
):
self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1")
self.assertEqual(models.project_models("/srv/e", paths, {}), models.Models("1", "1"))
self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ")
self.assertIn("no model catalog cached", sys.stderr.getvalue())
for broken in ("{", "[]", '{"srv/a": 1}'):
saved.write_text(broken)
with self.subTest(broken=broken):
stop = cycle.project_model("/srv/a", paths, {})
stop = models.project_models("/srv/a", paths, {})
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
self.assertEqual(saved.read_text(), broken)
@@ -219,10 +217,10 @@ class ProjectModel(unittest.TestCase):
class JudgePrompt(unittest.TestCase):
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
prompt = judge.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
self.assertIn("LATE", prompt)
self.assertLess(prompt.count("early"), 20000)
self.assertTrue(prompt.endswith(cycle.JUDGE_RULES))
self.assertTrue(prompt.endswith(judge.JUDGE_RULES))
class Archive(unittest.TestCase):
@@ -273,14 +271,14 @@ class Interrupt(unittest.TestCase):
transcript = os.path.join(root, "session.jsonl")
pathlib.Path(transcript).write_text("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "stdin or stdout is not a terminal"))
self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on 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(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "the interrupt ended without the human typing anything"))
self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
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")
@@ -289,7 +287,7 @@ class Interrupt(unittest.TestCase):
handle.write(json.dumps(human("typed")) + "\n")
run.side_effect = type_a_turn
self.assertIsNone(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}))
self.assertIsNone(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})))
class Trust(unittest.TestCase):
@@ -297,27 +295,27 @@ class Trust(unittest.TestCase):
with tempfile.TemporaryDirectory() as home, umask(0o022):
config = pathlib.Path(home, ".claude.json")
with contextlib.redirect_stderr(io.StringIO()) as err:
cycle.trust(config, ["/a"])
trust.trust(config, ["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n")
config.write_text("{")
with contextlib.redirect_stderr(io.StringIO()) as err:
cycle.trust(config, ["/a"])
trust.trust(config, ["/a"])
self.assertIn(f"could not read {config}: ", err.getvalue())
for shape in ([], {"projects": []}, {"projects": {"/a": 1}}):
for shape, said in (([], 'not an object whose "projects" is an object'), ({"projects": []}, 'not an object whose "projects" is an object'), ({"projects": {"/a": 1}}, 'projects["/a"] is not an object')):
config.write_text(json.dumps(shape))
with contextlib.redirect_stderr(io.StringIO()) as err:
cycle.trust(config, ["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n")
trust.trust(config, ["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: {said}\n")
self.assertEqual(json.loads(config.read_text()), shape)
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
config.write_text(json.dumps(data))
config.chmod(0o600)
with contextlib.redirect_stderr(io.StringIO()) as err:
cycle.trust(config, ["/a"])
trust.trust(config, ["/a"])
self.assertEqual(err.getvalue(), "")
self.assertEqual(json.loads(config.read_text()), data)
with contextlib.redirect_stderr(io.StringIO()) as err:
cycle.trust(config, ["/a", "/b"])
trust.trust(config, ["/a", "/b"])
self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n")
data["projects"]["/b"] = {"hasTrustDialogAccepted": True}
self.assertEqual(json.loads(config.read_text()), data)
@@ -325,7 +323,7 @@ class Trust(unittest.TestCase):
contextlib.redirect_stderr(io.StringIO()) as err,
unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")),
):
cycle.trust(config, ["/c"])
trust.trust(config, ["/c"])
self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n")
self.assertEqual(json.loads(config.read_text()), data)
self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
@@ -340,19 +338,21 @@ class Parse(unittest.TestCase):
class Grounded(unittest.TestCase):
def test_an_interrupt_must_quote_the_transcript(self):
self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything"))
self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript"))
def test_every_verdict_must_quote_the_transcript(self):
for interrupting in (False, True):
self.assertTrue(judge.grounded({"interrupt": interrupting, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": "invented"}, "the transcript"))
self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": ""}, "the transcript"))
self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": " "}, "the transcript"))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(cycle.complete({"interrupt": False}))
self.assertFalse(cycle.complete(None))
self.assertIsNone(judge.incomplete({"interrupt": False, "evidence": "", "finished": True, "question": ""}))
self.assertEqual(judge.incomplete({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), "the judge's verdict has no interrupt of type boolean")
self.assertEqual(judge.incomplete({"interrupt": False, "evidence": None, "finished": True, "question": ""}), "the judge's verdict has no evidence of type string")
self.assertEqual(judge.incomplete({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), "the judge interrupted without a question")
self.assertEqual(judge.incomplete(None), "the judge returned no verdict")
STUB_CLAUDE = """#!/usr/bin/env python3
@@ -366,7 +366,7 @@ if "--json-schema" in args:
if plan[0] == "fail":
sys.exit(1)
interrupt = plan[0] in ("interrupt", "unquoted")
print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}}))
print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], "worked"), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}}))
else:
flag = "--session-id" if "--session-id" in args else "--resume"
folder = os.path.expanduser("~/.claude/projects/p")
@@ -407,19 +407,19 @@ 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(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue())
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue())
pathlib.Path(verdicts).write_text("interrupt")
with unittest.mock.patch("sys.stderr") as stderr:
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal"))
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
pathlib.Path(verdicts).write_text("interrupt fail fail fail")
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None):
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1)
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths).code, 1)
with unittest.mock.patch.object(cycle, "transcript_file", return_value=""):
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}"))
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(1, f"claude left no transcript for session {session_id}"))
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
pathlib.Path(verdicts).write_text(plan)
stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {})
stop = cycle.run_cycle(home, "task", "premises", OPUS, paths)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the judge "))
if plan.startswith("unquoted"):
@@ -468,7 +468,7 @@ class RunLoop(unittest.TestCase):
self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, 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(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_models")]
stopped = Stop(1, "stopped")
with contextlib.ExitStack() as stack:
mocks = [stack.enter_context(patch) for patch in patches]
+42 -18
View File
@@ -81,6 +81,8 @@ elif "type" in step:
append({{"type": "user", "message": {{"content": step["type"]}}}})
if step.get("unreadable"):
transcript().chmod(0)
if step.get("vanish"):
os.remove(__file__)
sys.exit(step.get("exit", 0))
"""
@@ -103,7 +105,7 @@ def worker(**step):
return {"role": "worker", **step}
def judge(interrupt=False, finished=False, evidence="", question="", **step):
def judge(interrupt=False, finished=False, evidence="working", question="", **step):
verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
return {"role": "judge", "verdict": verdict, **step}
@@ -147,6 +149,7 @@ class Checkout:
fake.mkdir()
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
(fake / "claude").chmod(0o755)
(fake / "git").symlink_to(shutil.which("git"))
site = self.temp / "site"
site.mkdir()
(site / "sitecustomize.py").write_text(SITECUSTOMIZE)
@@ -159,7 +162,7 @@ class Checkout:
"LOOP_CLAUDE_JUDGE_MODEL": "judge-model",
"LOOP_CLAUDE_WORKER_MODEL": "worker-model",
"LOOP_TEST_LOG": str(self.temp / "starts.jsonl"),
"PATH": f"{fake}{os.pathsep}{os.environ['PATH']}",
"PATH": str(fake),
"PYTHONPATH": str(site),
})
self.git("init", "--quiet")
@@ -271,8 +274,8 @@ class Cycles(unittest.TestCase):
def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self):
checkout = Checkout(self)
run = checkout.run([
worker(say="started"), judge(),
worker(say="landed-it"), judge(finished=True),
worker(say="started"), judge(evidence="started"),
worker(say="landed-it"), judge(finished=True, evidence="landed-it"),
worker(say="next chunk"),
])
self.assertEqual(run.code, 130)
@@ -312,19 +315,35 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
self.assertEqual(run.sleeps, [60, 60])
self.assertIn("retrying the judge in a minute: judge down", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict")
self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr)
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string")
def test_retries_the_judge_alone_when_its_interrupt_quotes_nothing_in_the_transcript(self):
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
checkout = Checkout(self)
run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="never said", question="A or B?"), judge()])
run = checkout.run([
worker(say="Shall I use A or B?"),
judge(interrupt=True, evidence="never said", question="A or B?"),
judge(finished=True, evidence=""),
judge(evidence="A or B"),
worker(),
])
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"])
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge", "worker", "judge"])
self.assertEqual(run.sleeps, [60, 60])
self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr)
self.assertIn("retrying the judge in a minute: the judge quoted '', nothing in the transcript\n", run.stderr)
def test_retries_a_judge_claude_cannot_start(self):
checkout = Checkout(self)
run = checkout.run([worker(vanish=True)])
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
self.assertEqual(run.sleeps, [60, 60])
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory")
def test_skips_a_malformed_transcript_or_stream_line(self):
checkout = Checkout(self)
raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n"
run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge()])
run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge(evidence="past the noise")])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"]))
self.assertIn("past the noise", run.stdout)
self.assertIn("past the noise", run.calls[1]["stdin"])
@@ -338,10 +357,7 @@ class Cycles(unittest.TestCase):
def test_retries_a_worker_claude_cannot_start(self):
checkout = Checkout(self)
only_git = checkout.temp / "only-git"
only_git.mkdir()
(only_git / "git").symlink_to(shutil.which("git"))
checkout.env["PATH"] = str(only_git)
(checkout.temp / "fake-bin" / "claude").unlink()
run = checkout.run([])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.sleeps, [60, 60])
@@ -360,13 +376,13 @@ class Interrupt(unittest.TestCase):
steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
run = checkout.run(steps)
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "stdin or stdout is not a terminal"])
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
self.assertTrue(checkout.archived())
session = argument(run.calls[0], "--session-id")
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
self.assertEqual(argument(run.calls[0], "--resume"), session)
self.assertEqual(run.stderr.strip().splitlines()[-1], "stdin or stdout is not a terminal")
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
checkout = Checkout(self)
@@ -375,7 +391,7 @@ class Interrupt(unittest.TestCase):
checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}}))
checkout.claude_json().chmod(0o644)
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
run = checkout.run([*asked, interrupt(type="B"), judge(), worker()], terminal_input="")
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], terminal_input="")
self.assertEqual(run.code, 130)
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
handed = run.calls[2]["argv"]
@@ -393,7 +409,11 @@ class Interrupt(unittest.TestCase):
transcript.unlink()
run = checkout.run([*asked, interrupt()], terminal_input="")
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything")
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed")
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="")
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory")
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
@@ -416,7 +436,11 @@ class Models(unittest.TestCase):
self.catalog(checkout)
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (2, []))
self.assertIn(f"proj has no model in {checkout.models_file()}", run.stderr)
self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": "<model>"}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun loop-claude on a terminal')
run = checkout.run([worker()], terminal_input="\x04")
self.assertEqual((run.code, run.calls), (2, []))
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended")
run = checkout.run([worker(), judge()], terminal_input="9\n2\n")
self.assertEqual(run.code, 130)
-8
View File
@@ -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.
@@ -36,10 +32,6 @@
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats.
## loop-claude: the section headers stay
2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in what is now `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`.
## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run.
-1
View File
@@ -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.**