diff --git a/AGENTS.md b/AGENTS.md index 9db3d697..dcddecb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ Decisions live in `docs/decisions.md`: - review: an ask no user answers leaves the PR unmerged - loop-claude: every claude it starts bypasses permissions inside its sandbox - loop-claude: the planned stats line goes in the transcript archive, off the remote -- workflow changes: a change merges only once three planned benches rule it better +- workflow changes: once the bench runs, a change merges only after three benches rule it better - review: `/security-review` is the security pass of record - review: the premises chunk's whole review is the human's approval +- workflow-bench/: the remote may show the bench cases' names and commit SHAs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3250c6c0..cf75fbdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 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 --help` lists each exit cause on its own line, and when an edit to `loop-claude` breaks its reload, the exit-1 message names what the edited script could not read. - `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` counts an interrupt reply starting with `<` as typed. diff --git a/bin/loop_claude/claude_code/__init__.py b/bin/loop_claude/claude_code/__init__.py index e69de29b..be0bea62 100644 --- a/bin/loop_claude/claude_code/__init__.py +++ b/bin/loop_claude/claude_code/__init__.py @@ -0,0 +1 @@ +"""Claude Code's files and JSON shapes, each beside a sample, as Claude Code 2.1.284 writes them.""" diff --git a/bin/loop_claude/claude_code/catalog.py b/bin/loop_claude/claude_code/catalog.py deleted file mode 100644 index 909a396b..00000000 --- a/bin/loop_claude/claude_code/catalog.py +++ /dev/null @@ -1,15 +0,0 @@ -import json -import pathlib - -from loop_claude.claude_code.formats import models_in - - -def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]: - files = [] - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - files.append(json.load(handle)) - except (OSError, ValueError): - continue - return models_in(files) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/entries.py similarity index 68% rename from bin/loop_claude/claude_code/formats.py rename to bin/loop_claude/claude_code/entries.py index dc4dd33e..5c5045b7 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/entries.py @@ -1,10 +1,8 @@ -"""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 -from loop_claude.outcome import Failure - -def parse(raw: str | bytes) -> dict | None: +def parse_entry(raw: str | bytes) -> dict | None: try: entry = json.loads(raw) except ValueError: @@ -93,28 +91,4 @@ def ends_stream(event: dict) -> bool: # {"type": "result", "structured_output": {"evidence": "...", ...}, ...} def structured_output(stdout: str) -> object: - 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 [] + return (parse_entry(stdout) or {}).get("structured_output") diff --git a/bin/loop_claude/claude_code/model_catalog.py b/bin/loop_claude/claude_code/model_catalog.py new file mode 100644 index 00000000..5444126f --- /dev/null +++ b/bin/loop_claude/claude_code/model_catalog.py @@ -0,0 +1,26 @@ +import json +import pathlib + + +def catalog_models(folder: pathlib.Path) -> list[tuple[str, object]]: + files = [] + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + files.append(json.load(handle)) + except (OSError, ValueError): + continue + 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 [] diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index 09da7e25..d881fa1e 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -5,7 +5,7 @@ import pathlib import shutil import uuid -from loop_claude.outcome import Failure +from loop_claude.failure import Failure from loop_claude.paths import Paths NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -19,9 +19,9 @@ class Session: 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. - 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) diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index b110bc1d..93a3d173 100644 --- a/bin/loop_claude/claude_code/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -1,13 +1,15 @@ import json -from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call -from loop_claude.outcome import Failure +from loop_claude.claude_code.entries import assistant_parts, human_text, parse_entry, part_text, tool_call +from loop_claude.failure import Failure + +JUDGED_TOOL_INPUT = 400 -def read(path: str) -> list[dict] | Failure: +def read_transcript(path: str) -> list[dict] | Failure: try: with open(path, "rb") as handle: - return [entry for raw in handle if (entry := parse(raw))] + return [entry for raw in handle if (entry := parse_entry(raw))] except OSError as failure: return Failure(f"could not read the transcript {path}: {failure.strerror}") @@ -19,16 +21,16 @@ def human_turns(entries: list[dict]) -> int: def render(entries: list[dict]) -> str: lines = [] 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: lines.append("[human] " + text) 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(): return text if call := tool_call(part): name, arguments = call - return f"[tool {name}] {json.dumps(arguments)[:limit]}" + return f"[tool {name}] {json.dumps(arguments)[:tool_input_chars]}" return "" diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index ed1ba6ba..d6cb662e 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -2,9 +2,8 @@ import json import pathlib 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.outcome import Failure # 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) return 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 diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index b862d050..b7702eda 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -1,13 +1,13 @@ import hashlib import sys +from loop_claude.failure import Failure from loop_claude.file_writes import make_private, replace_file -from loop_claude.outcome import Failure from loop_claude.paths import Paths -def archive(project: str, path: str, note: str, paths: Paths) -> Failure | None: - folder = paths.archive / project +def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | None: + folder = paths.transcript_archive / project_key try: with open(path, "rb") as handle: raw = handle.read() diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 53514085..12279394 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,23 +1,23 @@ import sys 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_transcript from loop_claude.claude_code.trust import trust 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.project.checkout import checkouts +from loop_claude.project.checkout import worktrees +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: 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 - trust(paths.claude_json, checkouts(root, effects)) - entries = read(path) + trust(paths.claude_json, worktrees(root, effects)) + entries = read_transcript(path) if isinstance(entries, Failure): return Stop(1, entries.reason) before = human_turns(entries) @@ -25,7 +25,7 @@ def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: effects.claude_on_terminal(["--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], root) except OSError as failure: return Stop(1, f"could not start claude for the interrupt: {failure.strerror}") - entries = read(path) + entries = read_transcript(path) if isinstance(entries, Failure): 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") diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index f40f834c..76e2f1bb 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -2,11 +2,14 @@ import dataclasses import json 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.verdicts import Finished, Interrupt, Unfinished, Verdict 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 + +JUDGED_TRANSCRIPT_TAIL = 40000 JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" @@ -45,7 +48,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. args = [ "-p", @@ -56,11 +59,11 @@ def judge(root: str, task: str, premises: str, transcript: str, model: str, effe "--permission-mode", "bypassPermissions", "--tools", "", ] - prompt = judge_prompt(task, premises, transcript) - return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects) + prompt = judge_prompt(task, premises, rendered_transcript) + 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: proc = effects.claude(args, root, prompt) except OSError as failure: @@ -70,27 +73,27 @@ def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects: verdict = verdict_from(structured_output(proc.stdout)) if isinstance(verdict, Failure): return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}") - if not grounded(verdict.evidence, 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 "")) + if not grounded(verdict.evidence, rendered_transcript): + return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else "")) return verdict -def judge_prompt(task: str, premises: str, transcript: str) -> str: +def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str: 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"What the agent did and said, and what the human typed on [human] lines, latest last:\n{rendered_transcript[-JUDGED_TRANSCRIPT_TAIL:]}\n\n" f"{JUDGE_RULES}" ) def verdict_from(output: object) -> Verdict | Failure: 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(): 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. if output["interrupt"]: if not output["question"].strip(): @@ -99,9 +102,9 @@ def verdict_from(output: object) -> Verdict | Failure: 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) - return quoted != "" and quoted in plain(transcript) + return quoted != "" and quoted in plain(rendered_transcript) def plain(text: str) -> str: diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 12606c56..9a4d73b2 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -2,7 +2,8 @@ import sys import typing 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") diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/run.py similarity index 84% rename from bin/loop_claude/cycle/steps.py rename to bin/loop_claude/cycle/run.py index c91c0e2b..8b1b4206 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/run.py @@ -2,7 +2,7 @@ import dataclasses import typing from loop_claude.claude_code.session import Session, delete_session, session_open, transcript_file -from loop_claude.claude_code.transcript import read, render +from loop_claude.claude_code.transcript import read_transcript, render from loop_claude.cycle.archive import archive from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge @@ -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.worker import run_worker, worker_args 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.project.models import Models +from loop_claude.project.model_choice import Models +from loop_claude.stop import Stop @dataclasses.dataclass(frozen=True) @@ -21,7 +22,7 @@ class Cycle: models: Models paths: Paths premises: str - project: str + project_key: str root: str session: Session task: str @@ -60,7 +61,7 @@ def work(cycle: Cycle) -> WorkerRan | Stop: def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: - entries = read(transcript_path) + entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge, cycle.effects) @@ -69,13 +70,13 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | 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. - 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 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: - 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) if failure := delete_session(cycle.session): return Stop(1, failure.reason) diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index fe3443d0..14d8a36a 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -66,6 +66,7 @@ def transition(state: State, event: Event) -> State: return Finishing(transcript_path) case Judging(), Ruled(Unfinished()): return Ended() + # The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves. case Interrupting(transcript_path), Answered(): return Judging(transcript_path) case Finishing(), Archived(): diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 97a6a033..c23a33cb 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -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_entry from loop_claude.claude_code.session import Session from loop_claude.claude_code.transcript import part_line 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: @@ -12,10 +14,10 @@ def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None: return Failure(f"could not start claude: {failure.strerror}") done = False for raw in proc.lines(): - event = parse(raw) or {} + event = parse_entry(raw) or {} done = done or ends_stream(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) code = proc.wait() if code < 0: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 79384e47..8a52d3c5 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -27,7 +27,7 @@ class Effects: stream_claude: typing.Callable[[list[str], str], Streaming] -class Popened: +class StreamingClaude: 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) @@ -49,5 +49,5 @@ def system_effects() -> Effects: on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), sleep=time.sleep, - stream_claude=Popened, + stream_claude=StreamingClaude, ) diff --git a/bin/loop_claude/failure.py b/bin/loop_claude/failure.py new file mode 100644 index 00000000..9b46b0b1 --- /dev/null +++ b/bin/loop_claude/failure.py @@ -0,0 +1,7 @@ +import dataclasses + + +@dataclasses.dataclass(frozen=True) +class Failure: + """A step failed, and reason says why; its caller decides what follows.""" + reason: str diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 33b89103..cca4bdaa 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -3,7 +3,7 @@ import os import pathlib import typing -from loop_claude.outcome import Failure +from loop_claude.failure import Failure def make_private(folder: pathlib.Path) -> None: diff --git a/bin/loop_claude/human_needed.py b/bin/loop_claude/human_needed.py deleted file mode 100644 index 2fd7e2c7..00000000 --- a/bin/loop_claude/human_needed.py +++ /dev/null @@ -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") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 8100bce6..6cdd1cff 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,35 +4,49 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, the work of one PR, is finished. +the transcript against the premises and rules whether the chunk, the work of one PR, is finished. A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes 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". -Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or -write, claude leaves no transcript or one it cannot read or archive, a finished chunk's session it -cannot delete, claude cannot start for an interrupt, python cannot start for a reload, a reload whose -loop run it cannot read, or 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 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, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any -open session. +Each project has one session, named "A loop-claude", where is the checkout's path +relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every +interrupt, and when the chunk finishes, the session's transcript is copied to +$LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default ~/.claude/loop-claude-transcripts), the +verdict beside it in .verdict.md. -Each project has one session, "A loop-claude", being the checkout relative to ~/code, -or to / outside it, deleted when the chunk finishes. At every interrupt and when the chunk finishes -its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default -~/.claude/loop-claude-transcripts), the verdict beside it in .verdict.md. - -Every claude it starts runs the project's model, saved per in ~/.claude/loop-claude-models.json -and read each cycle; a project without an entry, as on its first run, is asked for one. -LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the -interrupt; with both set, nothing is asked. +Every claude loop-claude starts runs the project's model, saved per in +~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first +run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL +for the worker and the interrupt; with both set, nothing is asked. A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once -loop-claude --help succeeds. +loop-claude --help succeeds: the loop reloads into the edited script. + +Exit 1, saying why, when: +- no task is given +- git cannot start or finds no checkout +- README.md holds no premises +- the models file cannot be read or written +- claude leaves no 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 running script handed it, + likely because the edit changed that handover +- 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 a line the transcript does not hold. + +Exit 2, when the human is needed and cannot answer: +- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered +- the input ends while a model is picked +- an interrupt ends with nothing typed +Rerunning resumes any open session. + """ import dataclasses import pathlib @@ -40,14 +54,14 @@ import sys import typing 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.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.project.checkout import checkout_root, project_name -from loop_claude.project.models import project_models +from loop_claude.project.checkout import checkout_root, project_key +from loop_claude.project.model_choice import get_or_ask_models 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: @@ -65,8 +79,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(loop_run, Stop): return loop_run baseline = fingerprint(launcher) - project = project_name(loop_run.root, paths.code) - session = session_for(project, paths) + key = project_key(loop_run.root, paths.code) + session = session_for(key, paths) while True: if stop := exec_if_edited(launcher, baseline, loop_run, effects): return stop @@ -74,11 +88,11 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc premises = read_premises(loop_run.root) if isinstance(premises, Stop): return premises - models = project_models(project, paths, env, effects) + models = get_or_ask_models(key, paths, env, effects) if isinstance(models, Stop): return models 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 @@ -91,5 +105,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) 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): - return Stop(1, f"the reload cannot read the loop run from {argv[1:]}; rerun loop-claude ") + return Stop(1, f"the edited loop-claude cannot read the cycle number, checkout root and task the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: {' '.join(argv[1:])}") return loop_run diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 2813f1ee..e7fc5bc0 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -6,7 +6,7 @@ import sys import typing from loop_claude.effects import Effects -from loop_claude.outcome import Stop +from loop_claude.stop import Stop RELOAD_FLAG = "--reloaded" T = typing.TypeVar("T") @@ -15,7 +15,7 @@ T = typing.TypeVar("T") # A field change stops a running loop at its next reload: the new script rejects the old fields. @dataclasses.dataclass(frozen=True) 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.""" cycle_number: int root: str task: str @@ -45,6 +45,7 @@ def fingerprint(launcher: pathlib.Path) -> str: return digest.hexdigest() +# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to loop-claude to use without the human rerunning it. def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py deleted file mode 100644 index 95fa3451..00000000 --- a/bin/loop_claude/outcome.py +++ /dev/null @@ -1,14 +0,0 @@ -import dataclasses - - -@dataclasses.dataclass(frozen=True) -class Failure: - """A step failed, for reason; its caller decides what follows.""" - reason: str - - -@dataclasses.dataclass(frozen=True) -class Stop: - """loop-claude exits with code, printing reason.""" - code: int - reason: str diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index dfd3d10e..35ecdbc5 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -5,21 +5,21 @@ import typing @dataclasses.dataclass(frozen=True) class Paths: - archive: pathlib.Path claude_code_transcripts: pathlib.Path claude_json: pathlib.Path code: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path + transcript_archive: pathlib.Path def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths: claude = home / ".claude" 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_json=home / ".claude.json", code=home / "code", model_catalog=claude / "cache" / "model-catalog", 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", ) diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index f63df11c..4fc70c25 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -1,7 +1,7 @@ import pathlib 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: @@ -14,7 +14,7 @@ def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop: return found.stdout.strip() -def checkouts(root: str, effects: Effects) -> list[str]: +def worktrees(root: str, effects: Effects) -> list[str]: found = [root] try: listing = effects.git(["worktree", "list", "--porcelain"], root) @@ -25,5 +25,5 @@ def checkouts(root: str, effects: Effects) -> list[str]: 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("/") diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/model_choice.py similarity index 63% rename from bin/loop_claude/project/models.py rename to bin/loop_claude/project/model_choice.py index 4897c134..c7b36882 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/model_choice.py @@ -4,12 +4,12 @@ import pathlib import sys import typing -from loop_claude import human_needed -from loop_claude.claude_code.catalog import offered_models +from loop_claude.claude_code.model_catalog import catalog_models from loop_claude.effects import Effects +from loop_claude.failure import Failure from loop_claude.file_writes import replace_json -from loop_claude.outcome import Failure, Stop from loop_claude.paths import Paths +from loop_claude.stop import Stop, needs_human, needs_terminal @dataclasses.dataclass(frozen=True) @@ -18,37 +18,37 @@ class Models: worker: str -def project_models(project: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop: +def get_or_ask_models(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") if judge and worker: return Models(judge, worker) - chosen = project_model(project, paths, effects) + chosen = get_or_ask_model(project_key, paths, effects) if isinstance(chosen, Stop): return chosen return Models(judge or chosen, worker or chosen) -def project_model(name: str, paths: Paths, effects: Effects) -> str | Stop: +def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str | Stop: saved = paths.models_file - models = read_models(saved) + models = read_models_file(saved) if isinstance(models, Stop): return models - if saved_model := models.get(name): - return saved_model - chosen = ask_model(name, saved, paths.model_catalog, effects) + if kept := models.get(project_key): + return kept + chosen = ask_for_model(project_key, saved, paths.model_catalog, effects) 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) + models = read_models_file(saved) if isinstance(models, Stop): 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}") - print(f"{name} runs on {chosen}", file=sys.stderr) + print(f"{project_key} runs on {chosen}", file=sys.stderr) return chosen -def read_models(saved: pathlib.Path) -> dict[str, str] | Stop: +def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop: try: with open(saved, encoding="utf-8") as handle: models = json.load(handle) @@ -61,11 +61,11 @@ def read_models(saved: pathlib.Path) -> dict[str, str] | Stop: return models -def ask_model(name: 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}\": \"\"}} into {saved}", effects.on_terminal()): +def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop: + if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"\"}} into {saved}", effects.on_terminal()): return stop - offered = offered_models(folder) - print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) + offered = catalog_models(folder) + print(f"\nThe model to run {project_key} 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: @@ -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: ") except EOFError: 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) if isinstance(picked, Failure): print(picked.reason, file=sys.stderr) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 27e7a55a..e6289e5c 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,6 +1,6 @@ import pathlib -from loop_claude.outcome import Stop +from loop_claude.stop import Stop def read_premises(root: str) -> str | Stop: diff --git a/bin/loop_claude/stop.py b/bin/loop_claude/stop.py new file mode 100644 index 00000000..44be1929 --- /dev/null +++ b/bin/loop_claude/stop.py @@ -0,0 +1,19 @@ +import dataclasses +import typing + + +@dataclasses.dataclass(frozen=True) +class Stop: + """loop-claude exits with code, printing reason.""" + code: typing.Literal[0, 1, 2, 130] + 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") diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index d8ef6e6c..78effad3 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,3 +1,4 @@ +import ast import dataclasses import json import os @@ -12,13 +13,14 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude import file_writes, paths -from loop_claude.claude_code import formats, session, transcript -from loop_claude.cycle import interrupt, judge, retry, states, steps, worker +from loop_claude.claude_code import entries, session, transcript, trust +from loop_claude.cycle import interrupt, judge, retry, run, states, worker from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished from loop_claude.effects import Effects +from loop_claude.failure import Failure 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, model_choice, premises +from loop_claude.stop import Stop CWD = pathlib.Path("/c") @@ -143,26 +145,26 @@ class Cycles(unittest.TestCase): self.session = session.session_for("proj", self.paths) 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=model_choice.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): - 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): 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.assertIsNone(session.transcript_file(self.session)) 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) - self.assertIsNone(steps.run_cycle(self.cycle(fake))) + self.assertIsNone(run.run_cycle(self.cycle(fake))) 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") self.assertIn("--session-id", workers[0]) 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 answer(args): @@ -170,7 +172,7 @@ class Cycles(unittest.TestCase): handle.write(json.dumps(human("the second")) + "\n") return 0 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.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) prompts = [stdin for args, stdin in fake.made("claude")] @@ -185,14 +187,14 @@ class Cycles(unittest.TestCase): folder.chmod(0o500) self.addCleanup(folder.chmod, 0o700) 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.assertTrue(session.session_open(self.session)) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) def test_stops_when_the_worker_leaves_no_transcript(self): 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): @@ -226,19 +228,19 @@ class ModelPrompt(unittest.TestCase): OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self): - self.assertEqual(models.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5") - self.assertEqual(models.model_picked("opus", self.OFFERED), "opus") - self.assertEqual(models.model_picked("3", []), "3") - self.assertEqual(models.model_picked("3", self.OFFERED), Failure("pick 1 to 2")) - self.assertIsNone(models.model_picked(" ", self.OFFERED)) + self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5") + self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus") + self.assertEqual(model_choice.model_picked("3", []), "3") + self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2")) + self.assertIsNone(model_choice.model_picked(" ", self.OFFERED)) def test_asks_again_until_an_answer_picks_a_model(self): with tempfile.TemporaryDirectory() as empty: fake = FakeEffects(inputs=["", "my-model"]) - self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model") + self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model") self.assertEqual(len(fake.made("input")), 2) 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(model_choice.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): @@ -297,26 +299,26 @@ class HumanTurns(unittest.TestCase): class PartLine(unittest.TestCase): 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": " \n"}), "") + self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}, 20), "hi") + 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("not a part"), "") + self.assertEqual(transcript.part_line("not a part", 20), "") class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(formats.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(formats.parse("not json")) - self.assertIsNone(formats.parse("[1, 2]")) + self.assertEqual(entries.parse_entry('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(entries.parse_entry("not json")) + self.assertIsNone(entries.parse_entry("[1, 2]")) class MarkTrusted(unittest.TestCase): def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self): config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}} 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(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) + self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) 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": 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": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's verdict 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": "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 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(None), Failure("the judge returned no verdict")) + self.assertEqual(judge.verdict_from(None), Failure("the judge returned no reply")) class LoopRuns(unittest.TestCase): 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"})]): 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 ")) + self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the cycle number, checkout root and task the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: {' '.join(handed)}")) def test_decodes_a_state_whose_annotations_are_strings(self): @dataclasses.dataclass(frozen=True) @@ -364,11 +366,53 @@ 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 ")) -class Checkouts(unittest.TestCase): +class ExitContract(unittest.TestCase): + def test_every_exit_1_stop_has_its_clause_in_help(self): + read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "README.md holds no premises" + models_ = "the models file cannot be read or written" + # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. + clauses = [ + ("cycle/interrupt.py", "interrupt", "1", "entries.reason", read), + ("cycle/interrupt.py", "interrupt", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), + ("cycle/interrupt.py", "interrupt", "1", "f'could not tell whether you typed anything:", read), + ("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), + ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), + ("cycle/run.py", "rule", "1", "entries.reason", read), + ("cycle/run.py", "ask", "1", "failure.reason", read), + ("cycle/run.py", "close", "1", "failure.reason", read), + ("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), + ("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"), + ("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the cycle number,', "a reload cannot read the cycle number, checkout root and task"), + ("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), + ("project/checkout.py", "checkout_root", "1", "f'could not start git:", git), + ("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git), + ("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_), + ("project/model_choice.py", "read_models_file", "1", 'f"could not read {saved}: {getattr(', models_), + ("project/model_choice.py", "read_models_file", "1", "f'could not read {saved}: not an object", models_), + ("project/premises.py", "read_premises", "1", "f'README.md in {root}:", premises_), + ("project/premises.py", "read_premises", "1", "f'README.md is not UTF-8", premises_), + ("project/premises.py", "read_premises", "1", "f'README.md has no ##", premises_), + ("project/premises.py", "read_premises", "1", "f'README.md has ## {name} more than once", premises_), + ("project/premises.py", "read_premises", "1", "f'README.md has nothing under", premises_), + ] + root = pathlib.Path(main.__file__).parents[1] + found = [] + for path in sorted(root.rglob("*.py")): + functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)] + stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions 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))] + found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)] + self.assertEqual(len(found), len(clauses), found) + for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses): + self.assertEqual((path, function, code), (want_path, want_function, want_code)) + self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}") + help_exit_1 = main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")] + self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], []) + + +class Worktrees(unittest.TestCase): def test_lists_the_root_alone_when_git_cannot_start(self): fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")]) - self.assertEqual(checkout.checkouts("/r", fake.effects()), ["/r"]) - + self.assertEqual(checkout.worktrees("/r", fake.effects()), ["/r"]) class ReplaceFile(unittest.TestCase): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 17b438f6..fda16a3a 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -382,8 +382,8 @@ 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.assertIn("retrying the judge in a minute: the judge returned no verdict; 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.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 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): checkout = Checkout(self) @@ -397,8 +397,8 @@ class Cycles(unittest.TestCase): self.assertEqual(run.code, 130) 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) + self.assertIn("the judge quoted 'never said', which is not in the transcript, for the question: A or B?", run.stderr) + self.assertIn("retrying the judge in a minute: the judge quoted '', which is not in the transcript\n", run.stderr) def test_retries_a_judge_claude_cannot_start(self): checkout = Checkout(self) diff --git a/docs/decisions.md b/docs/decisions.md index 6c942c04..8633ee30 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,11 +30,11 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -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 same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. Valid until the next scoring run, which uses the same four seats. +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 same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review §3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes -2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. Valid while Claude Code keeps rewriting the settings' model from inside a session. +2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 1 shares the setup across machines, and a project's model is not part of it, so each new machine asks once per project. Valid while Claude Code keeps rewriting the settings' model from inside a session. ## review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human @@ -68,9 +68,9 @@ 2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. -## workflow changes: a change merges only once three planned benches rule it better +## workflow changes: once the bench runs, a change merges only after three benches rule it better -2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. +2026-10-01, lilleman. 2026-10-02, lilleman: binding once `todo.md`'s "Bench about one chunk in ten against an open PR that changes the workflow" lands. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. ## review: `/security-review` is the security pass of record @@ -79,3 +79,7 @@ ## review: the premises chunk's whole review is the human's approval 2026-09-20, lilleman. Serves goal 4.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle. + +## workflow-bench/: the remote may show the bench cases' names and commit SHAs + +2026-10-02, lilleman. Serves goal 3, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results. diff --git a/todo.md b/todo.md index 483e1393..ebfd6d94 100644 --- a/todo.md +++ b/todo.md @@ -2,23 +2,15 @@ ## 0.1.0 -### Under the comprehension floor - -The panels on `rebuild` at 8585257 and on PR #182 named these under Self-sufficiency and Locality, the two dimensions under the floor. Scores: `docs/decisions.md` → "comprehension floor". - -- **Name `loop_claude`'s modules and words by what each holds.** The 2026-10-01 panel misread `formats.py` (it holds every Claude Code shape, `mark_trusted` and `models_in` included), `steps.py`, `outcome.py` and `human_needed.py`. "Project", "transcripts", "verdict" and "model" each name two or three things. Goal 4.1. -- **State in `reload.py` why a loop reloads its own script, and tie each exit-1 clause of `--help` to the `Stop` that produces it.** Two seats found the reload's purpose nowhere in the code, and one could keep the exit contract true only by grepping every `Stop(1`. Name what a reload could not read, and its likely cause, in both `--help` and the reload's error: "loop run" is defined nowhere a reader looks. Goal 4.1. - -### The rest - -- **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 "loop-claude: a judge decides each interrupt from the transcript and the README's premises; the worker's own account of which goal settles a choice decides nothing" 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. -- **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. - **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 contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. + - `docs/decisions.md`: order the entries and the `AGENTS.md` index by one key. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. @@ -26,21 +18,29 @@ 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. - 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. - - Check the catalog `name` in `models_in` 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`. + - Check the catalog `name` in `newest_catalog_models` as well as `id`. + - Sort `worker_args`' flags and the globs in `model_catalog.py` and `session.py`. - Write `"bypassPermissions"` once for every claude `loop-claude` starts. - 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, and have `test_citations.py` use that `ROOT`. +- **Make the small fixes filed by the 2026-10-02 principles audit against `bin/`.** Goal 4.1. + - Have `Session` carry the project key, so `Cycle` cannot hold a key and a session for different projects. + - Inject the black-box tests' sleep through `Effects.sleep`; today `SITECUSTOMIZE` swaps `time.sleep` in the child process. + - Return a `Failure` from `replace_file` when removing the staged file fails too. + - Say so when a catalog file cannot be read; today the prompt says no catalog is cached. + - Sort `transcript_file`'s glob, and delete a session's files under every project folder that holds its id. + - Type `decode_handed` for `LoopRun`, its one caller's type, and drop the type variable `T`. +- **Give each cycle phase one name across its state, step and event.** Today `Judging` runs `rule` and yields `Ruled`, and `Finishing` runs `close`, which also deletes the session, and yields `Archived`. Goal 4.1. +- **Copy the transcript archive off the machine, or say in README how it is backed up.** It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Goal 2. - **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.** `read_transcript` 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. - **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. - **Archive a finished chunk's subagent transcripts before `delete_session` removes them.** Today only `.jsonl` is copied, so every reviewer's full run in an unattended chunk is lost. Goal 2. - **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** No machine has it enabled, so every chunk that fires the pass skips it. Goal 4.1. - **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads. Goal 4.4. -- **Give `settings.json`'s model one writer.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3. +- **Give `settings.json`'s model one writer, and sort its keys.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3. - **Rewrite `statusline.sh` in Python, and test it.** It needs `jq` and GNU `date` on every machine, `eval`s jq output, has three near-identical usage blocks and no test. Goal 1. - **Say in `systems-architect.md` that a REST API's `/v1/` prefix is not versioning machinery to defer.** Its "defer the versioning story" can be read against `principles/rest-apis.md`, which requires the prefix from the start. Goal 4.3. - **Judge a cycle on more than the transcript's last 40,000 characters.** `judge_prompt` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. @@ -49,5 +49,6 @@ The panels on `rebuild` at 8585257 and on PR #182 named these under Self-suffici - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. - **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. Goal 4.4. - **Bench about one chunk in ten against an open PR that changes the workflow, and have a blind claude rule which run better serves this repo's goal 4.** Redo the chunk under the PR, from the commit it started from. The ruling claude is not told which run is which. `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. The same outcome with less code and prose, in the chunk or in the workflow, also counts as better. The PR merges only once three benches rule it better. A bench that rules it worse closes the PR and records, in `docs/workflow-learnings.md`, what the PR changed and why it lost. The ruling and both runs' numbers go on the chunk's stats line. Start from `workflow-bench/`, written for the 2026-09-30 bench's four fixed cases. Needs the stats line. Goals 4.1 and 4.4. -- **Bring the project to the comprehension floor on the four-seat panel.** Every dimension and the overall must reach 7.0, and none may fall below its best run on `rebuild`. A dimension under the floor gets its places filed under "Under the comprehension floor". +- **Put the scoring run's four seat prompts in `skills/comprehension-panel/`.** Each run copies them from the last run's handoff folder outside the repo, so another machine cannot rerun a comparable panel. Goal 1. +- **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. Goal 4.1. - **Wait out a usage limit and retry however long it lasts, without counting it as a failed run.** Today a worker or judge that hits a usage limit fails three times a minute apart, and the loop exits 1, so an unattended loop dies at every limit. The transcript line Claude Code writes for it, marked `"error":"rate_limit"`, holds the reset time: `You've hit your session limit · resets 7:40pm (Europe/Stockholm)`. Sleep until 2 minutes past it. The judge runs without a transcript, so find what its JSON reply carries on a limit. Where no reset time can be read, retry every 10 minutes: a retry before the reset fails (https://platform.claude.com/docs/en/api/rate-limits), so polling sooner only spends requests. Print when the next try is due, and update `--help`'s exit 1. Goal 4.