Name loop_claude's modules and words by what each holds, explain the reload, and tie each exit-1 clause of --help to its Stop

This commit is contained in:
2026-10-02 08:42:29 +02:00
parent dc844030fa
commit 211524196b
27 changed files with 212 additions and 165 deletions
+1
View File
@@ -11,6 +11,7 @@
- `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 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`'s exit-2 message says what the human is needed for.
- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start. - `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start.
- `loop-claude --help` lists each exit-1 cause on its own line, and a reload's exit 1 names what it could not read and the likely cause: the edit changed what one script hands the next.
- `loop-claude` shows the judge's reply when it rejects the judge's verdict. - `loop-claude` shows the judge's reply when it rejects the judge's verdict.
- `loop-claude` retries a failed worker within its cycle. - `loop-claude` retries a failed worker within its cycle.
- `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude` counts an interrupt reply starting with `<` as typed.
+1
View File
@@ -0,0 +1 @@
"""Claude Code's files and JSON shapes, each beside a sample, as Claude Code 2.1.284 writes them."""
+15 -4
View File
@@ -1,10 +1,8 @@
import json import json
import pathlib import pathlib
from loop_claude.claude_code.formats import models_in
def catalog_models(folder: pathlib.Path) -> list[tuple[str, object]]:
def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
files = [] files = []
for path in folder.glob("*.json"): for path in folder.glob("*.json"):
try: try:
@@ -12,4 +10,17 @@ def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
files.append(json.load(handle)) files.append(json.load(handle))
except (OSError, ValueError): except (OSError, ValueError):
continue continue
return models_in(files) return newest_catalog_models(files)
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def newest_catalog_models(files: list[object]) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest: dict = {}
for data in files:
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models: object = 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 []
@@ -1,8 +1,6 @@
"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it.""" """Entries of Claude Code's transcripts and of its stream-json and json output."""
import json import json
from loop_claude.outcome import Failure
def parse(raw: str | bytes) -> dict | None: def parse(raw: str | bytes) -> dict | None:
try: try:
@@ -94,27 +92,3 @@ def ends_stream(event: dict) -> bool:
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...} # {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout: str) -> object: def structured_output(stdout: str) -> object:
return (parse(stdout) or {}).get("structured_output") return (parse(stdout) or {}).get("structured_output")
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
return {**config, "projects": {**projects, **marked}}, untrusted
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files: list[object]) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest: dict = {}
for data in files:
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models: object = 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 []
+3 -3
View File
@@ -5,7 +5,7 @@ import pathlib
import shutil import shutil
import uuid import uuid
from loop_claude.outcome import Failure from loop_claude.failure import Failure
from loop_claude.paths import Paths from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@@ -19,9 +19,9 @@ class Session:
name: str name: str
def session_for(project: str, paths: Paths) -> Session: def session_for(project_key: str, paths: Paths) -> Session:
# "A " is the human's cue in the session picker that the session is the loop's. # "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project} loop-claude" name = f"A {project_key} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name) return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
+7 -5
View File
@@ -1,7 +1,9 @@
import json import json
from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call from loop_claude.claude_code.entries import assistant_parts, human_text, parse, part_text, tool_call
from loop_claude.outcome import Failure from loop_claude.failure import Failure
JUDGED_TOOL_INPUT = 400
def read(path: str) -> list[dict] | Failure: def read(path: str) -> list[dict] | Failure:
@@ -19,16 +21,16 @@ def human_turns(entries: list[dict]) -> int:
def render(entries: list[dict]) -> str: def render(entries: list[dict]) -> str:
lines = [] lines = []
for entry in entries: for entry in entries:
lines += [line for part in assistant_parts(entry) if (line := part_line(part))] lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
if (text := human_text(entry)) is not None: if (text := human_text(entry)) is not None:
lines.append("[human] " + text) lines.append("[human] " + text)
return "\n\n".join(lines) return "\n\n".join(lines)
def part_line(part: object, limit: int = 400) -> str: def part_line(part: object, tool_input_chars: int) -> str:
if (text := part_text(part)) and text.strip(): if (text := part_text(part)) and text.strip():
return text return text
if call := tool_call(part): if call := tool_call(part):
name, arguments = call name, arguments = call
return f"[tool {name}] {json.dumps(arguments)[:limit]}" return f"[tool {name}] {json.dumps(arguments)[:tool_input_chars]}"
return "" return ""
+12 -2
View File
@@ -2,9 +2,8 @@ import json
import pathlib import pathlib
import sys import sys
from loop_claude.claude_code.formats import mark_trusted from loop_claude.failure import Failure
from loop_claude.file_writes import replace_json from loop_claude.file_writes import replace_json
from loop_claude.outcome import Failure
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog. # A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
@@ -26,3 +25,14 @@ def trust(config: pathlib.Path, roots: list[str]) -> None:
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr) print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
return return
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
return {**config, "projects": {**projects, **marked}}, untrusted
+3 -3
View File
@@ -1,13 +1,13 @@
import hashlib import hashlib
import sys import sys
from loop_claude.failure import Failure
from loop_claude.file_writes import make_private, replace_file from loop_claude.file_writes import make_private, replace_file
from loop_claude.outcome import Failure
from loop_claude.paths import Paths from loop_claude.paths import Paths
def archive(project: str, path: str, note: str, paths: Paths) -> Failure | None: def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | None:
folder = paths.archive / project folder = paths.transcript_archive / project_key
try: try:
with open(path, "rb") as handle: with open(path, "rb") as handle:
raw = handle.read() raw = handle.read()
+5 -5
View File
@@ -1,20 +1,20 @@
import sys import sys
import uuid import uuid
from loop_claude import human_needed
from loop_claude.claude_code.transcript import human_turns, read from loop_claude.claude_code.transcript import human_turns, read
from loop_claude.claude_code.trust import trust from loop_claude.claude_code.trust import trust
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop from loop_claude.failure import Failure
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.project.checkout import checkouts from loop_claude.project.checkout import checkouts
from loop_claude.stop import Stop, needs_human, needs_terminal
TO = "answer the question above" ANSWER_QUESTION = "answer the question above"
def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None: def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None:
print(f"\n{question}", file=sys.stderr) print(f"\n{question}", file=sys.stderr)
if stop := human_needed.off_terminal(TO, effects.on_terminal()): if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
return stop return stop
trust(paths.claude_json, checkouts(root, effects)) trust(paths.claude_json, checkouts(root, effects))
entries = read(path) entries = read(path)
@@ -28,4 +28,4 @@ def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question:
entries = read(path) entries = read(path)
if isinstance(entries, Failure): if isinstance(entries, Failure):
return Stop(1, f"could not tell whether you typed anything: {entries.reason}") return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
return None if human_turns(entries) > before else human_needed.stop(TO, "the interrupt ended with nothing typed") return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
+14 -13
View File
@@ -2,11 +2,12 @@ import dataclasses
import json import json
import typing import typing
from loop_claude.claude_code.formats import structured_output from loop_claude.claude_code.entries import structured_output
from loop_claude.cycle.retry import retried from loop_claude.cycle.retry import retried
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop from loop_claude.failure import Failure
from loop_claude.stop import Stop
JUDGE_RULES = ( JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -45,7 +46,7 @@ JUDGE_SCHEMA = {
} }
def judge(root: str, task: str, premises: str, transcript: str, model: str, effects: Effects) -> Verdict | Stop: def judge(root: str, task: str, premises: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. # 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 = [ args = [
"-p", "-p",
@@ -56,11 +57,11 @@ def judge(root: str, task: str, premises: str, transcript: str, model: str, effe
"--permission-mode", "bypassPermissions", "--permission-mode", "bypassPermissions",
"--tools", "", "--tools", "",
] ]
prompt = judge_prompt(task, premises, transcript) prompt = judge_prompt(task, premises, rendered_transcript)
return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects) return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects)
def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects: Effects) -> Verdict | Failure: def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure:
try: try:
proc = effects.claude(args, root, prompt) proc = effects.claude(args, root, prompt)
except OSError as failure: except OSError as failure:
@@ -70,27 +71,27 @@ def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects:
verdict = verdict_from(structured_output(proc.stdout)) verdict = verdict_from(structured_output(proc.stdout))
if isinstance(verdict, Failure): if isinstance(verdict, Failure):
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}") return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
if not grounded(verdict.evidence, transcript): if not grounded(verdict.evidence, rendered_transcript):
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else "")) return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else ""))
return verdict return verdict
def judge_prompt(task: str, premises: str, transcript: str) -> str: def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str:
return ( return (
f"From README.md:\n{premises}\n\n" f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\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. # 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"What the agent did and said, and what the human typed on [human] lines, latest last:\n{rendered_transcript[-40000:]}\n\n"
f"{JUDGE_RULES}" f"{JUDGE_RULES}"
) )
def verdict_from(output: object) -> Verdict | Failure: def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict): if not isinstance(output, dict):
return Failure("the judge returned no verdict") return Failure("the judge returned no reply")
for name, kind in REPLY_TYPES.items(): for name, kind in REPLY_TYPES.items():
if not isinstance(output.get(name), kind): if not isinstance(output.get(name), kind):
return Failure(f"the judge's verdict has no {name} of type {JSON_TYPES[kind]}") return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
# An interrupt outranks finished: the human answers before the chunk can close. # An interrupt outranks finished: the human answers before the chunk can close.
if output["interrupt"]: if output["interrupt"]:
if not output["question"].strip(): if not output["question"].strip():
@@ -99,9 +100,9 @@ def verdict_from(output: object) -> Verdict | Failure:
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
def grounded(evidence: str, transcript: str) -> bool: def grounded(evidence: str, rendered_transcript: str) -> bool:
quoted = plain(evidence) quoted = plain(evidence)
return quoted != "" and quoted in plain(transcript) return quoted != "" and quoted in plain(rendered_transcript)
def plain(text: str) -> str: def plain(text: str) -> str:
+2 -1
View File
@@ -2,7 +2,8 @@ import sys
import typing import typing
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop from loop_claude.failure import Failure
from loop_claude.stop import Stop
T = typing.TypeVar("T") T = typing.TypeVar("T")
@@ -10,9 +10,10 @@ from loop_claude.cycle.retry import retried
from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition
from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Failure, Stop from loop_claude.failure import Failure
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.project.models import Models from loop_claude.project.models import Models
from loop_claude.stop import Stop
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -21,7 +22,7 @@ class Cycle:
models: Models models: Models
paths: Paths paths: Paths
premises: str premises: str
project: str project_key: str
root: str root: str
session: Session session: Session
task: str task: str
@@ -69,13 +70,13 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop: def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop:
# The interrupt appends to this transcript, so it is archived at each question. # The interrupt appends to this transcript, so it is archived at each question.
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", cycle.paths): if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", cycle.paths):
return Stop(1, failure.reason) return Stop(1, failure.reason)
return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered()
def close(cycle: Cycle, transcript_path: str) -> Archived | Stop: def close(cycle: Cycle, transcript_path: str) -> Archived | Stop:
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
return Stop(1, failure.reason) return Stop(1, failure.reason)
if failure := delete_session(cycle.session): if failure := delete_session(cycle.session):
return Stop(1, failure.reason) return Stop(1, failure.reason)
+5 -3
View File
@@ -1,8 +1,10 @@
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse from loop_claude.claude_code.entries import assistant_parts, ends_stream, parse
from loop_claude.claude_code.session import Session from loop_claude.claude_code.session import Session
from loop_claude.claude_code.transcript import part_line from loop_claude.claude_code.transcript import part_line
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Failure from loop_claude.failure import Failure
PRINTED_TOOL_INPUT = 160
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None: def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
@@ -15,7 +17,7 @@ def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
event = parse(raw) or {} event = parse(raw) or {}
done = done or ends_stream(event) done = done or ends_stream(event)
for part in assistant_parts(event): for part in assistant_parts(event):
if line := part_line(part, 160): if line := part_line(part, PRINTED_TOOL_INPUT):
print(line, flush=True) print(line, flush=True)
code = proc.wait() code = proc.wait()
if code < 0: if code < 0:
+2 -2
View File
@@ -27,7 +27,7 @@ class Effects:
stream_claude: typing.Callable[[list[str], str], Streaming] stream_claude: typing.Callable[[list[str], str], Streaming]
class Popened: class StreamingClaude:
def __init__(self, args: list[str], cwd: str) -> None: def __init__(self, args: list[str], cwd: str) -> None:
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
@@ -49,5 +49,5 @@ def system_effects() -> Effects:
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
sleep=time.sleep, sleep=time.sleep,
stream_claude=Popened, stream_claude=StreamingClaude,
) )
@@ -5,10 +5,3 @@ import dataclasses
class Failure: class Failure:
"""A step failed, for reason; its caller decides what follows.""" """A step failed, for reason; its caller decides what follows."""
reason: str reason: str
@dataclasses.dataclass(frozen=True)
class Stop:
"""loop-claude exits with code, printing reason."""
code: int
reason: str
+1 -1
View File
@@ -3,7 +3,7 @@ import os
import pathlib import pathlib
import typing import typing
from loop_claude.outcome import Failure from loop_claude.failure import Failure
def make_private(folder: pathlib.Path) -> None: def make_private(folder: pathlib.Path) -> None:
-11
View File
@@ -1,11 +0,0 @@
from loop_claude.outcome import Stop
def stop(to: str, but: str) -> Stop:
return Stop(2, f"the human is needed to {to}, but {but}")
def off_terminal(to: str, on_terminal: bool) -> Stop | None:
if on_terminal:
return None
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
+25 -16
View File
@@ -10,13 +10,22 @@ on the terminal, every worktree first marked trusted in ~/.claude.json. An unfin
its session next cycle; the next chunk starts a fresh session. its session next cycle; the next chunk starts a fresh session.
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or Exit 1, saying why, when:
write, claude leaves no transcript or one it cannot read or archive, a finished chunk's session it - no task is given
cannot delete, claude cannot start for an interrupt, python cannot start for a reload, a reload whose - git cannot start or finds no checkout
loop run it cannot read, or the worker or the judge fails three times running, retried a minute apart - README.md holds no premises
within the cycle. A worker fails when claude cannot start, exits non-zero, is killed, or ends without - the models file cannot be read or written
a result event; a judge when claude cannot start or exits non-zero, or its verdict misses or mistypes - claude leaves no transcript
a field, interrupts without a question, or quotes nothing in the transcript. - a transcript cannot be read or archived
- a finished chunk's session cannot be deleted
- claude cannot start for an interrupt
- python cannot start for a reload
- a reload cannot read the cycle number, checkout root and task the edited script was handed, as
when the edit changed what one script hands the next
- the worker or the judge fails three times running, retried a minute apart within the cycle. 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 reply 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 Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
open session. open session.
@@ -40,14 +49,14 @@ import sys
import typing import typing
from loop_claude.claude_code.session import session_for from loop_claude.claude_code.session import session_for
from loop_claude.cycle.steps import Cycle, run_cycle from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint
from loop_claude.outcome import Stop
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.project.checkout import checkout_root, project_name from loop_claude.project.checkout import checkout_root, project_key
from loop_claude.project.models import project_models from loop_claude.project.models import models_for
from loop_claude.project.premises import read_premises from loop_claude.project.premises import read_premises
from loop_claude.stop import Stop
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
@@ -65,8 +74,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
if isinstance(loop_run, Stop): if isinstance(loop_run, Stop):
return loop_run return loop_run
baseline = fingerprint(launcher) baseline = fingerprint(launcher)
project = project_name(loop_run.root, paths.code) key = project_key(loop_run.root, paths.code)
session = session_for(project, paths) session = session_for(key, paths)
while True: while True:
if stop := exec_if_edited(launcher, baseline, loop_run, effects): if stop := exec_if_edited(launcher, baseline, loop_run, effects):
return stop return stop
@@ -74,11 +83,11 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
premises = read_premises(loop_run.root) premises = read_premises(loop_run.root)
if isinstance(premises, Stop): if isinstance(premises, Stop):
return premises return premises
models = project_models(project, paths, env, effects) models = models_for(key, paths, env, effects)
if isinstance(models, Stop): if isinstance(models, Stop):
return models return models
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True) print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project=project, root=loop_run.root, session=session, task=loop_run.task)): if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, root=loop_run.root, session=session, task=loop_run.task)):
return stop return stop
@@ -91,5 +100,5 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
return root if isinstance(root, Stop) else LoopRun(0, root, task) return root if isinstance(root, Stop) else LoopRun(0, root, task)
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
if not (loop_run and loop_run.root and loop_run.task): if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the reload cannot read the loop run from {argv[1:]}; rerun loop-claude <task>") return Stop(1, f"the reload cannot read the cycle number, checkout root and task the edited script was handed in {argv[1:]}, as when the edit changed what one script hands the next; rerun loop-claude <task>")
return loop_run return loop_run
+3 -2
View File
@@ -1,3 +1,4 @@
"""A loop runs unattended for hours, often on its own checkout: a reload puts an edit to loop-claude to work at the next cycle without the human rerunning it."""
import dataclasses import dataclasses
import hashlib import hashlib
import json import json
@@ -6,7 +7,7 @@ import sys
import typing import typing
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Stop from loop_claude.stop import Stop
RELOAD_FLAG = "--reloaded" RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T") T = typing.TypeVar("T")
@@ -15,7 +16,7 @@ T = typing.TypeVar("T")
# A field change stops a running loop at its next reload: the new script rejects the old fields. # A field change stops a running loop at its next reload: the new script rejects the old fields.
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class LoopRun: class LoopRun:
"""One loop-claude run; a reload hands it to the new script as JSON on argv.""" """What a reload hands the edited script, as JSON on argv: the cycle number, checkout root and task."""
cycle_number: int cycle_number: int
root: str root: str
task: str task: str
+2 -2
View File
@@ -5,21 +5,21 @@ import typing
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Paths: class Paths:
archive: pathlib.Path
claude_code_transcripts: pathlib.Path claude_code_transcripts: pathlib.Path
claude_json: pathlib.Path claude_json: pathlib.Path
code: pathlib.Path code: pathlib.Path
model_catalog: pathlib.Path model_catalog: pathlib.Path
models_file: pathlib.Path models_file: pathlib.Path
transcript_archive: pathlib.Path
def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths: def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths:
claude = home / ".claude" claude = home / ".claude"
return Paths( return Paths(
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
claude_code_transcripts=claude / "projects", claude_code_transcripts=claude / "projects",
claude_json=home / ".claude.json", claude_json=home / ".claude.json",
code=home / "code", code=home / "code",
model_catalog=claude / "cache" / "model-catalog", model_catalog=claude / "cache" / "model-catalog",
models_file=claude / "loop-claude-models.json", models_file=claude / "loop-claude-models.json",
transcript_archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
) )
+2 -2
View File
@@ -1,7 +1,7 @@
import pathlib import pathlib
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.outcome import Stop from loop_claude.stop import Stop
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop: def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
@@ -25,5 +25,5 @@ def checkouts(root: str, effects: Effects) -> list[str]:
return sorted(set(found)) return sorted(set(found))
def project_name(root: str, code: pathlib.Path) -> str: def project_key(root: str, code: pathlib.Path) -> str:
return root.removeprefix(f"{code}/").lstrip("/") return root.removeprefix(f"{code}/").lstrip("/")
+19 -19
View File
@@ -4,12 +4,12 @@ import pathlib
import sys import sys
import typing import typing
from loop_claude import human_needed from loop_claude.claude_code.catalog import catalog_models
from loop_claude.claude_code.catalog import offered_models
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.file_writes import replace_json from loop_claude.file_writes import replace_json
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.stop import Stop, needs_human, needs_terminal
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -18,37 +18,37 @@ class Models:
worker: str worker: str
def project_models(project: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop: def models_for(project_key: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop:
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
if judge and worker: if judge and worker:
return Models(judge, worker) return Models(judge, worker)
chosen = project_model(project, paths, effects) chosen = saved_model(project_key, paths, effects)
if isinstance(chosen, Stop): if isinstance(chosen, Stop):
return chosen return chosen
return Models(judge or chosen, worker or chosen) return Models(judge or chosen, worker or chosen)
def project_model(name: str, paths: Paths, effects: Effects) -> str | Stop: def saved_model(project_key: str, paths: Paths, effects: Effects) -> str | Stop:
saved = paths.models_file saved = paths.models_file
models = read_models(saved) models = read_models_file(saved)
if isinstance(models, Stop): if isinstance(models, Stop):
return models return models
if saved_model := models.get(name): if kept := models.get(project_key):
return saved_model return kept
chosen = ask_model(name, saved, paths.model_catalog, effects) chosen = ask_for_model(project_key, saved, paths.model_catalog, effects)
if isinstance(chosen, Stop): if isinstance(chosen, Stop):
return chosen return chosen
# Reread: another loop may have saved its project while this one waited on the human. # Reread: another loop may have saved its project while this one waited on the human.
models = read_models(saved) models = read_models_file(saved)
if isinstance(models, Stop): if isinstance(models, Stop):
return models return models
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True):
return Stop(1, f"could not save the model in {saved}: {failure.reason}") return Stop(1, f"could not save the model in {saved}: {failure.reason}")
print(f"{name} runs on {chosen}", file=sys.stderr) print(f"{project_key} runs on {chosen}", file=sys.stderr)
return chosen return chosen
def read_models(saved: pathlib.Path) -> dict[str, str] | Stop: def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop:
try: try:
with open(saved, encoding="utf-8") as handle: with open(saved, encoding="utf-8") as handle:
models = json.load(handle) models = json.load(handle)
@@ -61,11 +61,11 @@ def read_models(saved: pathlib.Path) -> dict[str, str] | Stop:
return models return models
def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop: def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop:
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}", effects.on_terminal()): if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"<model>\"}} into {saved}", effects.on_terminal()):
return stop return stop
offered = offered_models(folder) offered = catalog_models(folder)
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) print(f"\nThe model to run {project_key} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1): for number, (model_id, label) in enumerate(offered, 1):
print(f" {number}. {label} ({model_id})", file=sys.stderr) print(f" {number}. {label} ({model_id})", file=sys.stderr)
if not offered: if not offered:
@@ -75,7 +75,7 @@ def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Eff
answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ") answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ")
except EOFError: except EOFError:
print(file=sys.stderr) print(file=sys.stderr)
return human_needed.stop(f"pick {name}'s model", "the input ended") return needs_human(f"pick {project_key}'s model", "the input ended")
picked = model_picked(answer, offered) picked = model_picked(answer, offered)
if isinstance(picked, Failure): if isinstance(picked, Failure):
print(picked.reason, file=sys.stderr) print(picked.reason, file=sys.stderr)
+1 -1
View File
@@ -1,6 +1,6 @@
import pathlib import pathlib
from loop_claude.outcome import Stop from loop_claude.stop import Stop
def read_premises(root: str) -> str | Stop: def read_premises(root: str) -> str | Stop:
+18
View File
@@ -0,0 +1,18 @@
import dataclasses
@dataclasses.dataclass(frozen=True)
class Stop:
"""loop-claude exits with code, printing reason."""
code: int
reason: str
def needs_human(need: str, blocker: str) -> Stop:
return Stop(2, f"the human is needed to {need}, but {blocker}")
def needs_terminal(need: str, on_terminal: bool) -> Stop | None:
if on_terminal:
return None
return needs_human(need, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
+60 -26
View File
@@ -1,3 +1,4 @@
import ast
import dataclasses import dataclasses
import json import json
import os import os
@@ -12,13 +13,14 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import file_writes, paths from loop_claude import file_writes, paths
from loop_claude.claude_code import formats, session, transcript from loop_claude.claude_code import entries, session, transcript, trust
from loop_claude.cycle import interrupt, judge, retry, states, steps, worker from loop_claude.cycle import interrupt, judge, retry, run, states, worker
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.failure import Failure
from loop_claude.loop import main, reload from loop_claude.loop import main, reload
from loop_claude.outcome import Failure, Stop
from loop_claude.project import checkout, models, premises from loop_claude.project import checkout, models, premises
from loop_claude.stop import Stop
CWD = pathlib.Path("/c") CWD = pathlib.Path("/c")
@@ -143,26 +145,26 @@ class Cycles(unittest.TestCase):
self.session = session.session_for("proj", self.paths) self.session = session.session_for("proj", self.paths)
def cycle(self, fake): def cycle(self, fake):
return steps.Cycle(effects=fake.effects(), models=models.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project="proj", root=str(self.home), session=self.session, task="Do it.") return run.Cycle(effects=fake.effects(), models=models.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", root=str(self.home), session=self.session, task="Do it.")
def archived_verdicts(self): def archived_verdicts(self):
return sorted(path.read_text() for path in (self.paths.archive / "proj").glob("*.verdict.md")) return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*.verdict.md"))
def test_a_finished_chunk_is_archived_and_its_session_deleted(self): def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertIsNone(steps.run_cycle(self.cycle(fake))) self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
self.assertIsNone(session.transcript_file(self.session)) self.assertIsNone(session.transcript_file(self.session))
def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self): def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
self.assertIsNone(steps.run_cycle(self.cycle(fake))) self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertTrue(session.transcript_file(self.session)) self.assertTrue(session.transcript_file(self.session))
self.assertIsNone(steps.run_cycle(self.cycle(fake))) self.assertIsNone(run.run_cycle(self.cycle(fake)))
workers = fake.made("stream_claude") workers = fake.made("stream_claude")
self.assertIn("--session-id", workers[0]) self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1]) self.assertIn("--resume", workers[1])
self.assertFalse((self.paths.archive / "proj").exists()) self.assertFalse((self.paths.transcript_archive / "proj").exists())
def test_an_interrupt_is_archived_answered_and_judged_again(self): def test_an_interrupt_is_archived_answered_and_judged_again(self):
def answer(args): def answer(args):
@@ -170,7 +172,7 @@ class Cycles(unittest.TestCase):
handle.write(json.dumps(human("the second")) + "\n") handle.write(json.dumps(human("the second")) + "\n")
return 0 return 0
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()])
self.assertIsNone(steps.run_cycle(self.cycle(fake))) self.assertIsNone(run.run_cycle(self.cycle(fake)))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"]) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
prompts = [stdin for args, stdin in fake.made("claude")] prompts = [stdin for args, stdin in fake.made("claude")]
@@ -185,14 +187,14 @@ class Cycles(unittest.TestCase):
folder.chmod(0o500) folder.chmod(0o500)
self.addCleanup(folder.chmod, 0o700) self.addCleanup(folder.chmod, 0o700)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
stop = steps.run_cycle(self.cycle(fake)) stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")) self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
self.assertTrue(session.session_open(self.session)) self.assertTrue(session.session_open(self.session))
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
def test_stops_when_the_worker_leaves_no_transcript(self): def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)]) fake = FakeEffects(streams=[Streamed(0)])
self.assertEqual(steps.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}")) self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}"))
class Retried(unittest.TestCase): class Retried(unittest.TestCase):
@@ -235,10 +237,10 @@ class ModelPrompt(unittest.TestCase):
def test_asks_again_until_an_answer_picks_a_model(self): def test_asks_again_until_an_answer_picks_a_model(self):
with tempfile.TemporaryDirectory() as empty: with tempfile.TemporaryDirectory() as empty:
fake = FakeEffects(inputs=["", "my-model"]) fake = FakeEffects(inputs=["", "my-model"])
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model") self.assertEqual(models.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model")
self.assertEqual(len(fake.made("input")), 2) self.assertEqual(len(fake.made("input")), 2)
fake = FakeEffects(inputs=[EOFError()]) fake = FakeEffects(inputs=[EOFError()])
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended")) self.assertEqual(models.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
class WorkerArgs(unittest.TestCase): class WorkerArgs(unittest.TestCase):
@@ -297,26 +299,26 @@ class HumanTurns(unittest.TestCase):
class PartLine(unittest.TestCase): class PartLine(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self): def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}), "hi") self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi")
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}), "") self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.part_line("not a part"), "") self.assertEqual(transcript.part_line("not a part", 20), "")
class Parse(unittest.TestCase): class Parse(unittest.TestCase):
def test_yields_only_json_objects(self): def test_yields_only_json_objects(self):
self.assertEqual(formats.parse('{"type": "user"}'), {"type": "user"}) self.assertEqual(entries.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(formats.parse("not json")) self.assertIsNone(entries.parse("not json"))
self.assertIsNone(formats.parse("[1, 2]")) self.assertIsNone(entries.parse("[1, 2]"))
class MarkTrusted(unittest.TestCase): class MarkTrusted(unittest.TestCase):
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self): def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}} config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
handed = json.dumps(config) handed = json.dumps(config)
self.assertEqual(formats.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"])) self.assertEqual(trust.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
self.assertEqual(json.dumps(config), handed) self.assertEqual(json.dumps(config), handed)
self.assertEqual(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
class Grounded(unittest.TestCase): class Grounded(unittest.TestCase):
@@ -336,17 +338,17 @@ class Verdict(unittest.TestCase):
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's verdict has no interrupt of type boolean")) self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's verdict has no evidence of type string")) self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string"))
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
self.assertEqual(judge.verdict_from(None), Failure("the judge returned no verdict")) self.assertEqual(judge.verdict_from(None), Failure("the judge returned no reply"))
class LoopRuns(unittest.TestCase): class LoopRuns(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]):
with self.subTest(handed=handed): with self.subTest(handed=handed):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop run from {handed}; rerun loop-claude <task>")) self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the cycle number, checkout root and task the edited script was handed in {handed}, as when the edit changed what one script hands the next; rerun loop-claude <task>"))
def test_decodes_a_state_whose_annotations_are_strings(self): def test_decodes_a_state_whose_annotations_are_strings(self):
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -364,6 +366,38 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>")) self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, task, git, premises_ = "a transcript cannot be read or archived", "no task is given", "git cannot start or finds no checkout", "README.md holds no premises"
models_, retries = "the models file cannot be read or written", "the worker or the judge fails three times running"
# Per function, the --help clause of each Stop it returns with an exit code other than 0, 2 or 130, in source order.
clauses = {
("cycle/interrupt.py", "interrupt"): (read, read, "claude cannot start for an interrupt"),
("cycle/retry.py", "retried"): (retries,),
("cycle/run.py", "ask"): (read,),
("cycle/run.py", "close"): (read, "a finished chunk's session cannot be deleted"),
("cycle/run.py", "rule"): (read,),
("cycle/run.py", "work"): ("claude leaves no transcript",),
("loop/main.py", "loop_run_from"): (task, "a reload cannot read the cycle number, checkout root and task"),
("loop/reload.py", "exec_if_edited"): ("python cannot start for a reload",),
("project/checkout.py", "checkout_root"): (git, git),
("project/models.py", "read_models_file"): (models_, models_),
("project/models.py", "saved_model"): (models_,),
("project/premises.py", "read_premises"): (premises_,) * 5,
}
root = pathlib.Path(main.__file__).parents[1]
found = {}
for path in sorted(root.rglob("*.py")):
for function in ast.walk(ast.parse(path.read_text())):
if isinstance(function, ast.FunctionDef):
stops = [call for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
if stops:
found[(str(path.relative_to(root)), function.name)] = len(stops)
self.assertEqual(found, {site: len(said) for site, said in clauses.items()})
help_exit_1 = main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")]
self.assertEqual([clause for said in clauses.values() for clause in said if f"- {clause}" not in help_exit_1], [])
class Checkouts(unittest.TestCase): class Checkouts(unittest.TestCase):
def test_lists_the_root_alone_when_git_cannot_start(self): def test_lists_the_root_alone_when_git_cannot_start(self):
fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")]) fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")])
+2 -2
View File
@@ -382,8 +382,8 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
self.assertEqual(run.sleeps, [60, 60]) self.assertEqual(run.sleeps, [60, 60])
self.assertIn("retrying the judge in a minute: judge down", run.stderr) self.assertIn("retrying the judge in a minute: judge down", run.stderr)
self.assertIn("retrying the judge in a minute: the judge returned no verdict; it replied: nothing\n", run.stderr) self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", 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; it replied: {"structured_output": {"interrupt": false}}') self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}')
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
checkout = Checkout(self) checkout = Checkout(self)
+3 -4
View File
@@ -13,7 +13,7 @@ The panels on `rebuild` at 8585257 and on PR #182 named these under Self-suffici
- **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "a judge decides interrupts, not the worker's self-report" to match. Goal 4.2. - **Give the judge the project's recorded decisions, and ask it whether anything the project records settles a choice.** Today it reads only the README's Goals and Audience (`premises.py`) and cannot see an answer recorded in `docs/decisions.md` or `AGENTS.md`, so it can interrupt the human again for a question already answered. Revise the decision "a judge decides interrupts, not the worker's self-report" to match. Goal 4.2.
- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. Goal 2. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. Goal 2.
- **Key a project on its checkout's full path, and refuse to start while another session uses that key.** The key names the project's session, archive folder and models entry. `project_name` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1. - **Key a project on its checkout's full path, and refuse to start while another session uses that key.** The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 4.1.
- **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1.
- **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1.
- **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4. - **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4.
@@ -26,14 +26,13 @@ The panels on `rebuild` at 8585257 and on PR #182 named these under Self-suffici
- **Make the small fixes filed by the 2026-10-01 principles audit against `bin/`.** Goal 4.1. - **Make the small fixes filed by the 2026-10-01 principles audit against `bin/`.** Goal 4.1.
- Prefix each diagnostic `loop-claude` prints with its level, `warning:` at the least, so a run's output can be grepped for what needs fixing. - Prefix each diagnostic `loop-claude` prints with its level, `warning:` at the least, so a run's output can be grepped for what needs fixing.
- Have `make_private` return a `Failure` like `replace_file` beside it. - Have `make_private` return a `Failure` like `replace_file` beside it.
- Check the catalog `name` in `models_in` as well as `id`. - Check the catalog `name` in `newest_catalog_models` as well as `id`.
- Name `part_line`'s limits 160 and 400, rename `Popened`, and give `human_needed.stop(to, but)` and `TO` names that read without the caller.
- Sort `worker_args`' flags and the globs in `catalog.py` and `session.py`. - Sort `worker_args`' flags and the globs in `catalog.py` and `session.py`.
- Write `"bypassPermissions"` once for every claude `loop-claude` starts. - Write `"bypassPermissions"` once for every claude `loop-claude` starts.
- Keep the judge's evidence and model in each archived `.verdict.md`. - Keep the judge's evidence and model in each archived `.verdict.md`.
- Move the test helpers `ROOT` and `readme_floor` out of `test_python_floor.py`, which two other tests import them from. - Move the test helpers `ROOT` and `readme_floor` out of `test_python_floor.py`, which two other tests import them from.
- **Inject output and storage into `Effects`, and test what each step prints.** `print` and `open` are called directly across `bin/loop_claude/`, so the stderr lines of the CLI contract can be checked only through the black-box tests. Goal 4.1. - **Inject output and storage into `Effects`, and test what each step prints.** `print` and `open` are called directly across `bin/loop_claude/`, so the stderr lines of the CLI contract can be checked only through the black-box tests. Goal 4.1.
- **Read transcript and stream entries into typed values where they are read.** `transcript.read` and `run_worker` pass raw `dict`s, so about ten accessors in `formats.py` re-check shapes deep inside and mypy cannot check `render`, `human_turns` or `run_worker`. Goal 4.1. - **Read transcript and stream entries into typed values where they are read.** `transcript.read` and `run_worker` pass raw `dict`s, so about ten accessors in `entries.py` re-check shapes deep inside and mypy cannot check `render`, `human_turns` or `run_worker`. Goal 4.1.
- **Measure test coverage in the suite, and fail on a drop.** Nothing measures it, so "Test coverage should not decline" cannot be held. Goal 4.1. - **Measure test coverage in the suite, and fail on a drop.** Nothing measures it, so "Test coverage should not decline" cannot be held. Goal 4.1.
- **Give the reviewer agents only the tools they need.** `systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. Goal 4.1. - **Give the reviewer agents only the tools they need.** `systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. Goal 4.1.
- **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3. - **Add a test that `.gitignore` keeps credentials, transcripts and memory files out.** `test_gitignore.py` checks only that every tracked file is allowlisted; a widened negation such as `!*.json` would un-ignore `.credentials.json`. Goal 3.