From f385b563f0772f5c61d5f8ef2987a4e281a7c93d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:12:37 +0200 Subject: [PATCH 1/9] Name the loop's states with one transition function, and inject its side effects --- bin/loop-claude | 4 +- bin/loop_claude/cycle/interrupt.py | 18 ++- bin/loop_claude/cycle/judge.py | 41 ++--- bin/loop_claude/cycle/retry.py | 6 +- bin/loop_claude/cycle/states.py | 77 +++++++++ bin/loop_claude/cycle/steps.py | 70 +++++---- bin/loop_claude/cycle/verdicts.py | 20 +++ bin/loop_claude/cycle/worker.py | 5 +- bin/loop_claude/effects.py | 27 ++++ bin/loop_claude/human_needed.py | 6 +- bin/loop_claude/loop/main.py | 19 +-- bin/loop_claude/loop/reload.py | 9 +- bin/loop_claude/project/checkout.py | 11 +- bin/loop_claude/project/models.py | 41 +++-- bin/test_loop_claude.py | 234 +++++++++++++++++++++++++--- todo.md | 7 +- 16 files changed, 469 insertions(+), 126 deletions(-) create mode 100644 bin/loop_claude/cycle/states.py create mode 100644 bin/loop_claude/cycle/verdicts.py create mode 100644 bin/loop_claude/effects.py diff --git a/bin/loop-claude b/bin/loop-claude index 08b6b6ad..ba819173 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -6,7 +6,7 @@ import sys LAUNCHER = pathlib.Path(__file__).resolve() sys.path.insert(0, str(LAUNCHER.parent)) -from loop_claude import paths +from loop_claude import effects, paths from loop_claude.loop import main -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd())) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd(), effects.system_effects())) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 4a4164d3..b3816e48 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,31 +1,33 @@ -import subprocess import sys from loop_claude import human_needed from loop_claude.claude_code.transcript import human_turns, read from loop_claude.claude_code.trust import trust +from loop_claude.effects import Effects from loop_claude.outcome import Failure, Stop from loop_claude.project.checkout import checkouts TO = "answer the question above" -def interrupt(root, session_id, model, path, question, paths) -> Stop | None: +def interrupt(root, session_id, model, path, question, paths, effects: Effects) -> Stop | None: print(f"\n{question}", file=sys.stderr) - if stop := human_needed.off_terminal(TO): + if stop := human_needed.off_terminal(TO, effects.on_terminal()): return stop - trust(paths.claude_json, checkouts(root)) + trust(paths.claude_json, checkouts(root, effects)) entries = read(path) if isinstance(entries, Failure): return Stop(1, entries.reason) before = human_turns(entries) try: - subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + effects.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) except OSError as failure: return Stop(1, f"could not start claude for the interrupt: {failure.strerror}") entries = read(path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") - if human_turns(entries) <= before: - return human_needed.stop(TO, "the interrupt ended with nothing typed") - return None + return None if typed_since(before, entries) else human_needed.stop(TO, "the interrupt ended with nothing typed") + + +def typed_since(turns_before, entries) -> bool: + return human_turns(entries) > turns_before diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 92258226..da20d334 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -1,10 +1,11 @@ import dataclasses import json -import subprocess import typing from loop_claude.claude_code.formats 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 JUDGE_RULES = ( @@ -27,24 +28,25 @@ JUDGE_RULES = ( "not yet run, CI not yet reported." ) +# The reply's shape, which the schema below hands claude; verdict_from reads it into a Verdict. @dataclasses.dataclass(frozen=True) -class Verdict: +class Reply: evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."}) finished: bool interrupt: bool question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."}) -VERDICT_TYPES = typing.get_type_hints(Verdict) +REPLY_TYPES = typing.get_type_hints(Reply) JSON_TYPES = {bool: "boolean", str: "string"} JUDGE_SCHEMA = { - "properties": {field.name: {**field.metadata, "type": JSON_TYPES[VERDICT_TYPES[field.name]]} for field in dataclasses.fields(Verdict)}, - "required": list(VERDICT_TYPES), + "properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)}, + "required": list(REPLY_TYPES), "type": "object", } -def judge(root, task, premises, transcript, model) -> Verdict | Stop: +def judge(root, task, premises, transcript, model, 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,12 +58,12 @@ def judge(root, task, premises, transcript, model) -> Verdict | Stop: "--tools", "", ] prompt = judge_prompt(task, premises, transcript) - return retried("judge", lambda: run_judge(root, args, prompt, transcript)) + return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects) -def run_judge(root, args, prompt, transcript) -> Verdict | Failure: +def run_judge(root, args, prompt, transcript, effects: Effects) -> Verdict | Failure: try: - proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) + proc = effects.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: @@ -69,8 +71,8 @@ def run_judge(root, args, prompt, transcript) -> Verdict | Failure: 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, transcript): - return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")) + 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 "")) return verdict @@ -87,17 +89,20 @@ def judge_prompt(task, premises, transcript) -> str: def verdict_from(output) -> Verdict | Failure: if not isinstance(output, dict): return Failure("the judge returned no verdict") - for name, kind in VERDICT_TYPES.items(): + 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]}") - if output["interrupt"] and not output["question"].strip(): - return Failure("the judge interrupted without a question") - return Verdict(**{name: output[name] for name in VERDICT_TYPES}) + # An interrupt outranks finished: the human answers before the chunk can close. + if output["interrupt"]: + if not output["question"].strip(): + return Failure("the judge interrupted without a question") + return Interrupt(output["evidence"], output["question"]) + return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) -def grounded(verdict, transcript) -> bool: - evidence = plain(verdict.evidence) - return evidence != "" and evidence in plain(transcript) +def grounded(evidence, transcript) -> bool: + quoted = plain(evidence) + return quoted != "" and quoted in plain(transcript) def plain(text) -> str: diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 5395f439..4253177c 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -1,13 +1,13 @@ import sys -import time import typing +from loop_claude.effects import Effects from loop_claude.outcome import Failure, Stop T = typing.TypeVar("T") -def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop: +def retried(who, attempt: typing.Callable[[], T | Failure], effects: Effects) -> T | Stop: failures = 0 while True: failures += 1 @@ -17,4 +17,4 @@ def retried(who, attempt: typing.Callable[[], T | Failure]) -> T | Stop: if failures == 3: return Stop(1, f"the {who} failed three times running: {result.reason}") print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr) - time.sleep(60) + effects.sleep(60) diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py new file mode 100644 index 00000000..bde6e4ac --- /dev/null +++ b/bin/loop_claude/cycle/states.py @@ -0,0 +1,77 @@ +import dataclasses + +from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict + + +@dataclasses.dataclass(frozen=True) +class Fresh: + """No transcript: the worker opens the session.""" + + +@dataclasses.dataclass(frozen=True) +class Resuming: + """The session's transcript exists: the worker continues it.""" + + +@dataclasses.dataclass(frozen=True) +class Judging: + transcript: str + + +@dataclasses.dataclass(frozen=True) +class Interrupting: + transcript: str + question: str + + +@dataclasses.dataclass(frozen=True) +class Finishing: + transcript: str + + +State = Fresh | Resuming | Judging | Interrupting | Finishing + + +@dataclasses.dataclass(frozen=True) +class WorkerRan: + transcript: str + + +@dataclasses.dataclass(frozen=True) +class Ruled: + verdict: Verdict + + +@dataclasses.dataclass(frozen=True) +class Answered: + pass + + +@dataclasses.dataclass(frozen=True) +class Archived: + pass + + +Event = WorkerRan | Ruled | Answered | Archived + + +def opening(transcript: str) -> Fresh | Resuming: + return Resuming() if transcript else Fresh() + + +def transition(state: State, event: Event) -> State: + """The state after event; a cycle ends when it reaches Fresh or Resuming again.""" + match state, event: + case Fresh() | Resuming(), WorkerRan(transcript): + return Judging(transcript) + case Judging(transcript), Ruled(Interrupt(question=question)): + return Interrupting(transcript, question) + case Judging(transcript), Ruled(Finished()): + return Finishing(transcript) + case Judging(), Ruled(Unfinished()): + return Resuming() + case Interrupting(transcript), Answered(): + return Judging(transcript) + case Finishing(), Archived(): + return Fresh() + raise ValueError(f"no transition from {state} on {event}") diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/steps.py index 4ea60dfe..7ecb43cd 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/steps.py @@ -4,9 +4,11 @@ from loop_claude.claude_code.session import Session, delete_session, transcript_ from loop_claude.claude_code.transcript import read, render from loop_claude.cycle.archive import archive from loop_claude.cycle.interrupt import interrupt -from loop_claude.cycle.judge import Verdict, judge +from loop_claude.cycle.judge import judge from loop_claude.cycle.retry import retried +from loop_claude.cycle.states import Answered, Archived, Event, Finishing, Fresh, Interrupting, Judging, Resuming, Ruled, State, WorkerRan, opening, 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.paths import Paths from loop_claude.project.models import Models @@ -14,6 +16,7 @@ from loop_claude.project.models import Models @dataclasses.dataclass(frozen=True) class Cycle: + effects: Effects models: Models paths: Paths premises: str @@ -24,32 +27,43 @@ class Cycle: def run_cycle(cycle) -> Stop | None: - if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, bool(transcript_file(cycle.session))))): - return stop - path = transcript_file(cycle.session) - if not path: - return Stop(1, f"claude left no transcript for session {cycle.session.id}") - verdict = judge_through_interrupts(cycle, path) - if isinstance(verdict, Stop): - return verdict - if verdict.finished: - if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): - return Stop(1, failure.reason) - delete_session(cycle.session) - return None - - -def judge_through_interrupts(cycle, path) -> Verdict | Stop: - # The interrupt appends to this transcript, so each pass judges and archives it anew. + state: State = opening(transcript_file(cycle.session)) while True: - entries = read(path) - if isinstance(entries, Failure): - return Stop(1, entries.reason) - verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge) - if isinstance(verdict, Stop) or not verdict.interrupt: - return verdict - if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{verdict.question}", cycle.paths): - return Stop(1, failure.reason) - if stop := interrupt(cycle.root, cycle.session.id, cycle.models.worker, path, verdict.question, cycle.paths): - return stop + event = step(cycle, state) + if isinstance(event, Stop): + return event + state = transition(state, event) + if isinstance(state, Fresh | Resuming): + return None + +def step(cycle, state) -> Event | Stop: + """Carries out state's effects and reports what happened.""" + match state: + case Fresh() | Resuming(): + if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, resuming(cycle.session)), cycle.effects), cycle.effects): + return stop + path = transcript_file(cycle.session) + return WorkerRan(path) if path else Stop(1, f"claude left no transcript for session {cycle.session.id}") + case Judging(path): + entries = read(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) + return verdict if isinstance(verdict, Stop) else Ruled(verdict) + case Interrupting(path, question): + # The interrupt appends to this transcript, so it is archived at each question and judged anew after. + if failure := archive(cycle.project, 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, path, question, cycle.paths, cycle.effects) or Answered() + case Finishing(path): + if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): + return Stop(1, failure.reason) + delete_session(cycle.session) + return Archived() + raise ValueError(f"no step for {state}") + + +def resuming(session) -> bool: + # Asked at each attempt: a failed one may have opened the session. + return isinstance(opening(transcript_file(session)), Resuming) diff --git a/bin/loop_claude/cycle/verdicts.py b/bin/loop_claude/cycle/verdicts.py new file mode 100644 index 00000000..1fa48086 --- /dev/null +++ b/bin/loop_claude/cycle/verdicts.py @@ -0,0 +1,20 @@ +import dataclasses + + +@dataclasses.dataclass(frozen=True) +class Interrupt: + evidence: str + question: str + + +@dataclasses.dataclass(frozen=True) +class Finished: + evidence: str + + +@dataclasses.dataclass(frozen=True) +class Unfinished: + evidence: str + + +Verdict = Interrupt | Finished | Unfinished diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 664bd940..a63e9a1e 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -2,12 +2,13 @@ import subprocess from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse from loop_claude.claude_code.transcript import part_line +from loop_claude.effects import Effects from loop_claude.outcome import Failure -def run_worker(root, args) -> Failure | None: +def run_worker(root, args, effects: Effects) -> Failure | None: try: - proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) + proc = effects.popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") with proc: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py new file mode 100644 index 00000000..fd4cbbc0 --- /dev/null +++ b/bin/loop_claude/effects.py @@ -0,0 +1,27 @@ +import dataclasses +import os +import subprocess +import sys +import time +import typing + + +@dataclasses.dataclass(frozen=True) +class Effects: + execv: typing.Callable[[str, list[str]], None] + input: typing.Callable[[str], str] + on_terminal: typing.Callable[[], bool] + popen: typing.Callable[..., subprocess.Popen] + run: typing.Callable[..., subprocess.CompletedProcess] + sleep: typing.Callable[[float], None] + + +def system_effects() -> Effects: + return Effects( + execv=os.execv, + input=input, + on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), + popen=subprocess.Popen, + run=subprocess.run, + sleep=time.sleep, + ) diff --git a/bin/loop_claude/human_needed.py b/bin/loop_claude/human_needed.py index 6e3d372a..4ad9d301 100644 --- a/bin/loop_claude/human_needed.py +++ b/bin/loop_claude/human_needed.py @@ -1,5 +1,3 @@ -import sys - from loop_claude.outcome import Stop @@ -7,7 +5,7 @@ def stop(to, but) -> Stop: return Stop(2, f"the human is needed to {to}, but {but}") -def off_terminal(to) -> Stop | None: - if sys.stdin.isatty() and sys.stdout.isatty(): +def off_terminal(to, 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 858374cc..f6f25763 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -39,6 +39,7 @@ import sys from loop_claude.claude_code.session import session_for from loop_claude.cycle.steps import Cycle, run_cycle +from loop_claude.effects import Effects from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint from loop_claude.outcome import Stop from loop_claude.project.checkout import checkout_root, project_name @@ -46,9 +47,9 @@ from loop_claude.project.models import project_models from loop_claude.project.premises import read_premises -def main(argv, env, paths, launcher, cwd) -> int: +def main(argv, env, paths, launcher, cwd, effects: Effects) -> int: try: - stop = run_loop(argv, env, paths, launcher, cwd) + stop = run_loop(argv, env, paths, launcher, cwd, effects) except KeyboardInterrupt: stop = Stop(130, "") if stop.reason: @@ -56,34 +57,34 @@ def main(argv, env, paths, launcher, cwd) -> int: return stop.code -def run_loop(argv, env, paths, launcher, cwd) -> Stop: - state = loop_state(argv, cwd) +def run_loop(argv, env, paths, launcher, cwd, effects: Effects) -> Stop: + state = loop_state(argv, cwd, effects) if isinstance(state, Stop): return state baseline = fingerprint(launcher) project = project_name(state.root, paths.code) session = session_for(project, paths) while True: - if stop := exec_if_edited(launcher, baseline, state): + if stop := exec_if_edited(launcher, baseline, state, effects): return stop state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) premises = read_premises(state.root) if isinstance(premises, Stop): return premises - models = project_models(project, paths, env) + models = project_models(project, paths, env, effects) if isinstance(models, Stop): return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)): + if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)): return stop -def loop_state(argv, cwd) -> LoopState | Stop: +def loop_state(argv, cwd, effects: Effects) -> LoopState | Stop: if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) if task in ("", "-h", "--help"): return Stop(0 if task else 1, __doc__.strip()) - root = checkout_root(cwd) + root = checkout_root(cwd, effects) return root if isinstance(root, Stop) else LoopState(0, root, task) state = decode_state(argv[1], LoopState) if len(argv) == 2 else None if not (state and state.root and state.task): diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 7aa7c48a..b3dee4cf 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -1,11 +1,10 @@ import dataclasses import hashlib import json -import os -import subprocess import sys import typing +from loop_claude.effects import Effects from loop_claude.outcome import Stop RELOAD_FLAG = "--reloaded" @@ -44,15 +43,15 @@ def fingerprint(launcher) -> str: return digest.hexdigest() -def exec_if_edited(launcher, baseline, state) -> Stop | None: +def exec_if_edited(launcher, baseline, state, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None try: - trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) + trial = effects.run([sys.executable, launcher, "--help"], capture_output=True, text=True) if trial.returncode != 0: print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) return None - os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) + effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) except OSError as failure: return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude ") return None diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index 7c700b89..9e8f768c 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -1,11 +1,10 @@ -import subprocess - +from loop_claude.effects import Effects from loop_claude.outcome import Stop -def checkout_root(cwd) -> str | Stop: +def checkout_root(cwd, effects: Effects) -> str | Stop: try: - found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True) + found = effects.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True) except OSError as failure: return Stop(1, f"could not start git: {failure.strerror}") if found.returncode != 0: @@ -13,10 +12,10 @@ def checkout_root(cwd) -> str | Stop: return found.stdout.strip() -def checkouts(root) -> list[str]: +def checkouts(root, effects: Effects) -> list[str]: found = [root] try: - listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) + listing = effects.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) except OSError: return found if listing.returncode == 0: diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index e7c51360..c2f9f237 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -4,8 +4,9 @@ import sys from loop_claude import human_needed from loop_claude.claude_code.catalog import offered_models +from loop_claude.effects import Effects from loop_claude.file_writes import replace_json -from loop_claude.outcome import Stop +from loop_claude.outcome import Failure, Stop @dataclasses.dataclass(frozen=True) @@ -14,24 +15,24 @@ class Models: worker: str -def project_models(project, paths, env) -> Models | Stop: +def project_models(project, paths, env, 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) + chosen = project_model(project, paths, effects) if isinstance(chosen, Stop): return chosen return Models(judge or chosen, worker or chosen) -def project_model(name, paths) -> str | Stop: +def project_model(name, paths, effects: Effects) -> str | Stop: saved = paths.models_file models = read_models(saved) if isinstance(models, Stop): return models if saved_model := models.get(name): return saved_model - chosen = ask_model(name, saved, paths.model_catalog) + chosen = ask_model(name, 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. @@ -57,8 +58,8 @@ def read_models(saved) -> dict[str, str] | Stop: return models -def ask_model(name, saved, folder) -> str | Stop: - if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): +def ask_model(name, saved, folder, effects: Effects) -> str | Stop: + if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} 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) @@ -68,14 +69,24 @@ def ask_model(name, saved, folder) -> str | Stop: print(f" no model catalog cached in {folder}", file=sys.stderr) while True: try: - answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() + 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") - if not answer: - continue - if not (offered and answer.isdecimal()): - return answer - if 1 <= int(answer) <= len(offered): - return offered[int(answer) - 1][0] - print(f"pick 1 to {len(offered)}", file=sys.stderr) + picked = model_picked(answer, offered) + if isinstance(picked, Failure): + print(picked.reason, file=sys.stderr) + elif picked: + return picked + + +def model_picked(answer, offered) -> str | Failure | None: + """The model the answer picks, a Failure naming the numbers to pick from, or None to ask again.""" + answer = answer.strip() + if not answer: + return None + if not (offered and answer.isdecimal()): + return answer + if 1 <= int(answer) <= len(offered): + return offered[int(answer) - 1][0] + return Failure(f"pick 1 to {len(offered)}") diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 004a4ab1..93b1491a 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,20 +1,24 @@ import dataclasses +import io import json import os import pathlib +import subprocess import sys import tempfile import unittest -from unittest import mock +import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import file_writes -from loop_claude.claude_code import formats, transcript -from loop_claude.cycle import judge +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.cycle.verdicts import Finished, Interrupt, Unfinished +from loop_claude.effects import Effects from loop_claude.loop import main, reload from loop_claude.outcome import Failure, Stop -from loop_claude.project import checkout, premises +from loop_claude.project import checkout, models, premises CWD = pathlib.Path("/c") @@ -31,6 +35,195 @@ def queued(prompt, kind): return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}} +class FakeEffects: + """Effects that record each call and answer from a script, one answer per call.""" + + def __init__(self, runs=(), popens=(), inputs=(), on_terminal=True): + self.calls = [] + self.runs, self.popens, self.inputs = list(runs), list(popens), list(inputs) + self.terminal = on_terminal + + def effects(self): + return Effects(execv=self.execv, input=self.input, on_terminal=lambda: self.terminal, popen=self.popen, run=self.run, sleep=self.sleep) + + def answer(self, script, what): + answer = script.pop(0) + if isinstance(answer, BaseException): + raise answer + return answer(what) if callable(answer) else answer + + def execv(self, path, args): + self.calls.append(("execv", args)) + raise OSError(2, "No such file or directory") + + def input(self, prompt): + self.calls.append(("input", prompt)) + return self.answer(self.inputs, prompt) + + def popen(self, args, **options): + self.calls.append(("popen", args)) + return self.answer(self.popens, args) + + def run(self, args, **options): + self.calls.append(("run", args)) + return self.answer(self.runs, args) + + def sleep(self, seconds): + self.calls.append(("sleep", seconds)) + + +def ran(stdout="", code=0, stderr=""): + return subprocess.CompletedProcess([], code, stdout, stderr) + + +def judged(verdict, evidence="working"): + reply = {"evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict == "interrupt" else ""} + return ran(json.dumps({"structured_output": reply})) + + +class Worker: + """A worker claude: writes a line to the session's transcript, then streams a result.""" + + def __init__(self, home, code=0): + self.home, self.code = home, code + + def __call__(self, args): + flag = "--session-id" if "--session-id" in args else "--resume" + path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a") as handle: + handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n") + return Streamed(self.code) + + +class Streamed(io.StringIO): + def __init__(self, code): + super().__init__(json.dumps({"type": "result"}) + "\n") + self.stdout, self.code = self, code + + def wait(self): + return self.code + + +class Transitions(unittest.TestCase): + def test_a_run_resumes_only_while_its_transcript_exists(self): + self.assertEqual(states.opening(""), states.Fresh()) + self.assertEqual(states.opening("/t.jsonl"), states.Resuming()) + + def test_each_state_moves_on_its_events_and_only_on_them(self): + for state, event, after in ( + (states.Fresh(), states.WorkerRan("/t"), states.Judging("/t")), + (states.Resuming(), states.WorkerRan("/t"), states.Judging("/t")), + (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), + (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")), + (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Resuming()), + (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), + (states.Finishing("/t"), states.Archived(), states.Fresh()), + ): + with self.subTest(state=state, event=event): + self.assertEqual(states.transition(state, event), after) + with self.assertRaises(ValueError): + states.transition(states.Fresh(), states.Answered()) + + +class Cycles(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.home = pathlib.Path(temp.name) + self.paths = paths.paths_from(self.home, {}) + 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.") + + def archived_verdicts(self): + return sorted(path.read_text() for path in (self.paths.archive / "proj").glob("*.verdict.md")) + + def test_a_finished_chunk_is_archived_and_its_session_deleted(self): + fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)], runs=[judged("finished")]) + self.assertIsNone(steps.run_cycle(self.cycle(fake))) + self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) + self.assertEqual(session.transcript_file(self.session), "") + + def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self): + fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)] * 2, runs=[judged("unfinished")] * 2) + self.assertIsNone(steps.run_cycle(self.cycle(fake))) + self.assertTrue(session.transcript_file(self.session)) + self.assertIsNone(steps.run_cycle(self.cycle(fake))) + workers = [args for kind, args in fake.calls if kind == "popen"] + self.assertIn("--session-id", workers[0]) + self.assertIn("--resume", workers[1]) + self.assertFalse((self.paths.archive / "proj").exists()) + + def test_an_interrupt_is_archived_answered_and_judged_again(self): + def answer(args): + with open(session.transcript_file(self.session), "a") as handle: + handle.write(json.dumps(human("the second")) + "\n") + return ran() + fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)], runs=[judged("interrupt"), ran(), answer, judged("unfinished")]) + self.assertIsNone(steps.run_cycle(self.cycle(fake))) + self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"]) + self.assertEqual([args[0] for kind, args in fake.calls if kind == "run"], ["claude", "git", "claude", "claude"]) + + def test_stops_when_the_worker_leaves_no_transcript(self): + fake = FakeEffects(popens=[lambda args: Streamed(0)]) + self.assertEqual(steps.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}")) + + +class Retried(unittest.TestCase): + def test_retries_a_minute_apart_and_stops_on_the_third_failure(self): + fake = FakeEffects() + results = [Failure("one"), "done"] + self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done") + self.assertEqual(fake.calls, [("sleep", 60)]) + fake = FakeEffects() + self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no")) + self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)]) + + +class Interrupts(unittest.TestCase): + def test_stops_off_a_terminal_before_starting_claude(self): + fake = FakeEffects(on_terminal=False) + stop = interrupt.interrupt("/r", uuid.uuid4(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects()) + self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) + self.assertEqual(fake.calls, []) + + def test_counts_only_turns_typed_after_the_handover(self): + self.assertFalse(interrupt.typed_since(1, [human("a")])) + self.assertTrue(interrupt.typed_since(1, [human("a"), human("b")])) + + +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)) + + 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", "/m.json", pathlib.Path(empty), fake.effects()), "my-model") + self.assertEqual(len(fake.calls), 2) + fake = FakeEffects(inputs=[EOFError()]) + self.assertEqual(models.ask_model("proj", "/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): + def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): + opened = session.session_for("proj", paths.paths_from(pathlib.Path("/h"), {})) + fresh = worker.worker_args("Do it.", opened, "m", False) + self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) + self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") + resumed = worker.worker_args("Do it.", opened, "m", True) + self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id)) + self.assertNotIn("Do it.", " ".join(resumed)) + + class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" @@ -99,21 +292,21 @@ class MarkTrusted(unittest.TestCase): class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): - def verdict(evidence): - return judge.Verdict(evidence=evidence, finished=False, interrupt=False, question="") - self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n")) - self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) - self.assertFalse(judge.grounded(verdict(""), "the transcript")) - self.assertFalse(judge.grounded(verdict(" "), "the transcript")) + self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n")) + self.assertFalse(judge.grounded("invented", "the transcript")) + self.assertFalse(judge.grounded("", "the transcript")) + self.assertFalse(judge.grounded(" ", "the transcript")) transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it." - self.assertTrue(judge.grounded(verdict("Your step:\n```\n./run.sh\n```\nRun it."), transcript)) - self.assertTrue(judge.grounded(verdict("Your step: ``` ./run.sh ``` Run it."), transcript)) - self.assertFalse(judge.grounded(verdict("**"), transcript)) + self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript)) + self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript)) + self.assertFalse(judge.grounded("**", transcript)) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "", "finished": True, "question": ""}), judge.Verdict(evidence="", finished=True, interrupt=False, question="")) + 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": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) @@ -124,7 +317,7 @@ class LoopState(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_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_decodes_a_state_whose_annotations_are_strings(self): @dataclasses.dataclass(frozen=True) @@ -135,16 +328,17 @@ class LoopState(unittest.TestCase): self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly)) def test_stops_when_the_reload_cannot_start_python(self): - with tempfile.TemporaryDirectory() as root, mock.patch("os.execv", side_effect=OSError(2, "No such file or directory")): + with tempfile.TemporaryDirectory() as root: launcher = pathlib.Path(root, "loop-claude") launcher.write_text("") - self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopState(1, "/r", "do it")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude ")) + fake = FakeEffects(runs=[ran()]) + self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopState(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): def test_lists_the_root_alone_when_git_cannot_start(self): - with tempfile.TemporaryDirectory() as empty, mock.patch.dict(os.environ, {"PATH": empty}): - self.assertEqual(checkout.checkouts(empty), [empty]) + fake = FakeEffects(runs=[FileNotFoundError(2, "No such file or directory")]) + self.assertEqual(checkout.checkouts("/r", fake.effects()), ["/r"]) diff --git a/todo.md b/todo.md index 75aec0f9..cea6b120 100644 --- a/todo.md +++ b/todo.md @@ -4,18 +4,13 @@ The rebuild's design sketches, the blind judges' verdicts on them and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The first three items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). +The first two items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). -- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:47`). - **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, one seat learnt the cases only from `HumanTurns` in the tests, and another could not confirm them without `HumanTurns`. Three seats named it the unit they least wanted to modify, and the architect named it where the project rots first. - **Annotate the parameter types in `bin/loop_claude/`.** Whether `root` or `path` is a `str` or a `Path` is learnt by tracing callers back to `bin/loop-claude`. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:28` 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. -- **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1. - - Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects. - - Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set. - - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. - **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. - larv-review §3: name CLI flags and exit codes among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. -- 2.52.0 From 00446be6890d04b9cfa8f56884fe4495843ad25e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:19:10 +0200 Subject: [PATCH 2/9] Answer the architect's first round --- AGENTS.md | 1 + bin/loop_claude/cycle/interrupt.py | 8 +-- bin/loop_claude/cycle/judge.py | 2 +- bin/loop_claude/cycle/states.py | 50 +++++++-------- bin/loop_claude/cycle/steps.py | 79 ++++++++++++++---------- bin/loop_claude/cycle/worker.py | 21 +++---- bin/loop_claude/effects.py | 34 ++++++++-- bin/loop_claude/loop/main.py | 30 ++++----- bin/loop_claude/loop/reload.py | 9 +-- bin/loop_claude/project/checkout.py | 4 +- bin/test_loop_claude.py | 96 ++++++++++++++--------------- docs/decisions.md | 4 ++ 12 files changed, 188 insertions(+), 150 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8330c2e..9812f1f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,3 +28,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the planned stats line goes in the transcript archive - workflow changes: a change merges only once three planned benches rule it better - chunk: as large as one purpose allows +- loop-claude: a cycle's state machine holds the paths that move it on, and a `Stop` leaves it diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index b3816e48..2bbe6e26 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -20,14 +20,10 @@ def interrupt(root, session_id, model, path, question, paths, effects: Effects) return Stop(1, entries.reason) before = human_turns(entries) try: - effects.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + 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) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") - return None if typed_since(before, entries) else human_needed.stop(TO, "the interrupt ended with nothing typed") - - -def typed_since(turns_before, entries) -> bool: - return human_turns(entries) > turns_before + return None if human_turns(entries) > before else human_needed.stop(TO, "the interrupt ended with nothing typed") diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index da20d334..52a6130a 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -63,7 +63,7 @@ def judge(root, task, premises, transcript, model, effects: Effects) -> Verdict def run_judge(root, args, prompt, transcript, effects: Effects) -> Verdict | Failure: try: - proc = effects.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) + proc = effects.claude(args, root, prompt) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index bde6e4ac..8c316fcd 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -4,37 +4,38 @@ from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict @dataclasses.dataclass(frozen=True) -class Fresh: - """No transcript: the worker opens the session.""" - - -@dataclasses.dataclass(frozen=True) -class Resuming: - """The session's transcript exists: the worker continues it.""" +class Working: + """The worker runs: opening the session, or resuming it while its transcript exists.""" @dataclasses.dataclass(frozen=True) class Judging: - transcript: str + transcript_path: str @dataclasses.dataclass(frozen=True) class Interrupting: - transcript: str + transcript_path: str question: str @dataclasses.dataclass(frozen=True) class Finishing: - transcript: str + transcript_path: str -State = Fresh | Resuming | Judging | Interrupting | Finishing +@dataclasses.dataclass(frozen=True) +class Ended: + """The cycle is over; the next one starts Working.""" + + +Active = Working | Judging | Interrupting | Finishing +State = Active | Ended @dataclasses.dataclass(frozen=True) class WorkerRan: - transcript: str + transcript_path: str @dataclasses.dataclass(frozen=True) @@ -55,23 +56,18 @@ class Archived: Event = WorkerRan | Ruled | Answered | Archived -def opening(transcript: str) -> Fresh | Resuming: - return Resuming() if transcript else Fresh() - - def transition(state: State, event: Event) -> State: - """The state after event; a cycle ends when it reaches Fresh or Resuming again.""" match state, event: - case Fresh() | Resuming(), WorkerRan(transcript): - return Judging(transcript) - case Judging(transcript), Ruled(Interrupt(question=question)): - return Interrupting(transcript, question) - case Judging(transcript), Ruled(Finished()): - return Finishing(transcript) + case Working(), WorkerRan(transcript_path): + return Judging(transcript_path) + case Judging(transcript_path), Ruled(Interrupt(question=question)): + return Interrupting(transcript_path, question) + case Judging(transcript_path), Ruled(Finished()): + return Finishing(transcript_path) case Judging(), Ruled(Unfinished()): - return Resuming() - case Interrupting(transcript), Answered(): - return Judging(transcript) + return Ended() + case Interrupting(transcript_path), Answered(): + return Judging(transcript_path) case Finishing(), Archived(): - return Fresh() + return Ended() raise ValueError(f"no transition from {state} on {event}") diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/steps.py index 7ecb43cd..42d05ae8 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/steps.py @@ -1,4 +1,5 @@ import dataclasses +import typing from loop_claude.claude_code.session import Session, delete_session, transcript_file from loop_claude.claude_code.transcript import read, render @@ -6,7 +7,7 @@ from loop_claude.cycle.archive import archive from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.cycle.retry import retried -from loop_claude.cycle.states import Answered, Archived, Event, Finishing, Fresh, Interrupting, Judging, Resuming, Ruled, State, WorkerRan, opening, 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.effects import Effects from loop_claude.outcome import Failure, Stop @@ -27,43 +28,59 @@ class Cycle: def run_cycle(cycle) -> Stop | None: - state: State = opening(transcript_file(cycle.session)) - while True: + state: State = Working() + while not isinstance(state, Ended): event = step(cycle, state) if isinstance(event, Stop): return event state = transition(state, event) - if isinstance(state, Fresh | Resuming): - return None + return None -def step(cycle, state) -> Event | Stop: - """Carries out state's effects and reports what happened.""" +def step(cycle, state: Active) -> Event | Stop: match state: - case Fresh() | Resuming(): - if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, resuming(cycle.session)), cycle.effects), cycle.effects): - return stop - path = transcript_file(cycle.session) - return WorkerRan(path) if path else Stop(1, f"claude left no transcript for session {cycle.session.id}") - case Judging(path): - entries = read(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) - return verdict if isinstance(verdict, Stop) else Ruled(verdict) - case Interrupting(path, question): - # The interrupt appends to this transcript, so it is archived at each question and judged anew after. - if failure := archive(cycle.project, 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, path, question, cycle.paths, cycle.effects) or Answered() - case Finishing(path): - if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): - return Stop(1, failure.reason) - delete_session(cycle.session) - return Archived() - raise ValueError(f"no step for {state}") + case Working(): + return work(cycle) + case Judging(transcript_path): + return rule(cycle, transcript_path) + case Interrupting(transcript_path, question): + return ask(cycle, transcript_path, question) + case Finishing(transcript_path): + return close(cycle, transcript_path) + case _: + typing.assert_never(state) -def resuming(session) -> bool: +def work(cycle) -> WorkerRan | Stop: # Asked at each attempt: a failed one may have opened the session. - return isinstance(opening(transcript_file(session)), Resuming) + if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session)), cycle.effects), cycle.effects): + return stop + path = transcript_file(cycle.session) + return WorkerRan(path) if path else Stop(1, f"claude left no transcript for session {cycle.session.id}") + + +def rule(cycle, transcript_path) -> Ruled | Stop: + entries = read(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) + return verdict if isinstance(verdict, Stop) else Ruled(verdict) + + +def ask(cycle, transcript_path, question) -> Answered | Stop: + # The interrupt appends to this transcript, so it is archived at each question and judged anew after. + if failure := archive(cycle.project, 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, transcript_path) -> Archived | Stop: + if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): + return Stop(1, failure.reason) + delete_session(cycle.session) + return Archived() + + +def session_open(session) -> bool: + """A run resumes the session only while its transcript exists.""" + return bool(transcript_file(session)) diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index a63e9a1e..058090fd 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,5 +1,3 @@ -import subprocess - from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse from loop_claude.claude_code.transcript import part_line from loop_claude.effects import Effects @@ -8,18 +6,17 @@ from loop_claude.outcome import Failure def run_worker(root, args, effects: Effects) -> Failure | None: try: - proc = effects.popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) + proc = effects.stream_claude(args, root) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") - with proc: - done = False - for raw in proc.stdout or (): - event = parse(raw) or {} - done = done or ends_stream(event) - for part in assistant_parts(event): - if line := part_line(part, 160): - print(line, flush=True) - code = proc.wait() + done = False + for raw in proc.lines(): + event = parse(raw) or {} + done = done or ends_stream(event) + for part in assistant_parts(event): + if line := part_line(part, 160): + print(line, flush=True) + code = proc.wait() if code < 0: return Failure(f"claude killed by signal {-code}") if code: diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index fd4cbbc0..20f1b03b 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -6,22 +6,48 @@ import time import typing +class Streaming(typing.Protocol): + """A started claude whose stream-json lines arrive as it works.""" + + def lines(self) -> typing.Iterable[str]: ... + + def wait(self) -> int: ... + + @dataclasses.dataclass(frozen=True) class Effects: + claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]] + claude_on_terminal: typing.Callable[[list[str], str], int] execv: typing.Callable[[str, list[str]], None] + git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] input: typing.Callable[[str], str] on_terminal: typing.Callable[[], bool] - popen: typing.Callable[..., subprocess.Popen] - run: typing.Callable[..., subprocess.CompletedProcess] + python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]] sleep: typing.Callable[[float], None] + stream_claude: typing.Callable[[list[str], str], Streaming] + + +class Popened: + def __init__(self, args, cwd): + self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) + + def lines(self) -> typing.Iterable[str]: + with self.proc: + yield from self.proc.stdout or () + + def wait(self) -> int: + return self.proc.wait() def system_effects() -> Effects: return Effects( + claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), + claude_on_terminal=lambda args, cwd: subprocess.run(["claude", *args], cwd=cwd).returncode, execv=os.execv, + git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True), input=input, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), - popen=subprocess.Popen, - run=subprocess.run, + python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), sleep=time.sleep, + stream_claude=Popened, ) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index f6f25763..841805e1 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -40,7 +40,7 @@ import sys from loop_claude.claude_code.session import session_for from loop_claude.cycle.steps import Cycle, run_cycle from loop_claude.effects import Effects -from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint +from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_state, exec_if_edited, fingerprint from loop_claude.outcome import Stop from loop_claude.project.checkout import checkout_root, project_name from loop_claude.project.models import project_models @@ -58,35 +58,35 @@ def main(argv, env, paths, launcher, cwd, effects: Effects) -> int: def run_loop(argv, env, paths, launcher, cwd, effects: Effects) -> Stop: - state = loop_state(argv, cwd, effects) - if isinstance(state, Stop): - return state + loop_run = loop_run_from(argv, cwd, effects) + if isinstance(loop_run, Stop): + return loop_run baseline = fingerprint(launcher) - project = project_name(state.root, paths.code) + project = project_name(loop_run.root, paths.code) session = session_for(project, paths) while True: - if stop := exec_if_edited(launcher, baseline, state, effects): + if stop := exec_if_edited(launcher, baseline, loop_run, effects): return stop - state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) - premises = read_premises(state.root) + loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) + premises = read_premises(loop_run.root) if isinstance(premises, Stop): return premises models = project_models(project, paths, env, effects) if isinstance(models, Stop): return models - print(f"\n=== cycle {state.cycle_number} ===", flush=True) - if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)): + 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)): return stop -def loop_state(argv, cwd, effects: Effects) -> LoopState | Stop: +def loop_run_from(argv, cwd, effects: Effects) -> LoopRun | Stop: if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) if task in ("", "-h", "--help"): return Stop(0 if task else 1, __doc__.strip()) root = checkout_root(cwd, effects) - return root if isinstance(root, Stop) else LoopState(0, root, task) - state = decode_state(argv[1], LoopState) if len(argv) == 2 else None - if not (state and state.root and state.task): + return root if isinstance(root, Stop) else LoopRun(0, root, task) + loop_run = decode_state(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's state from {argv[1:]}; rerun loop-claude ") - return state + return loop_run diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index b3dee4cf..a0599203 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -13,7 +13,8 @@ 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 LoopState: +class LoopRun: + """One loop-claude run; a reload hands it to the new script as JSON on argv.""" cycle_number: int root: str task: str @@ -43,15 +44,15 @@ def fingerprint(launcher) -> str: return digest.hexdigest() -def exec_if_edited(launcher, baseline, state, effects: Effects) -> Stop | None: +def exec_if_edited(launcher, baseline, loop_run, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None try: - trial = effects.run([sys.executable, launcher, "--help"], capture_output=True, text=True) + trial = effects.python([str(launcher), "--help"]) if trial.returncode != 0: print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) return None - effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) + effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))]) except OSError as failure: return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude ") return None diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index 9e8f768c..a9b86d17 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -4,7 +4,7 @@ from loop_claude.outcome import Stop def checkout_root(cwd, effects: Effects) -> str | Stop: try: - found = effects.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True) + found = effects.git(["rev-parse", "--show-toplevel"], str(cwd)) except OSError as failure: return Stop(1, f"could not start git: {failure.strerror}") if found.returncode != 0: @@ -15,7 +15,7 @@ def checkout_root(cwd, effects: Effects) -> str | Stop: def checkouts(root, effects: Effects) -> list[str]: found = [root] try: - listing = effects.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) + listing = effects.git(["worktree", "list", "--porcelain"], root) except OSError: return found if listing.returncode == 0: diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 93b1491a..431c0799 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,5 +1,4 @@ import dataclasses -import io import json import os import pathlib @@ -38,16 +37,27 @@ def queued(prompt, kind): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, runs=(), popens=(), inputs=(), on_terminal=True): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True): self.calls = [] - self.runs, self.popens, self.inputs = list(runs), list(popens), list(inputs) + self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} self.terminal = on_terminal def effects(self): - return Effects(execv=self.execv, input=self.input, on_terminal=lambda: self.terminal, popen=self.popen, run=self.run, sleep=self.sleep) + return Effects( + claude=lambda args, cwd, stdin: self.answer("claude", args), + claude_on_terminal=lambda args, cwd: self.answer("claude_on_terminal", args), + execv=self.execv, + git=lambda args, cwd: self.answer("git", args), + input=lambda prompt: self.answer("input", prompt), + on_terminal=lambda: self.terminal, + python=lambda args: self.answer("python", args), + sleep=lambda seconds: self.calls.append(("sleep", seconds)), + stream_claude=lambda args, cwd: self.answer("stream_claude", args), + ) - def answer(self, script, what): - answer = script.pop(0) + def answer(self, seam, what): + self.calls.append((seam, what)) + answer = self.scripts[seam].pop(0) if isinstance(answer, BaseException): raise answer return answer(what) if callable(answer) else answer @@ -56,20 +66,8 @@ class FakeEffects: self.calls.append(("execv", args)) raise OSError(2, "No such file or directory") - def input(self, prompt): - self.calls.append(("input", prompt)) - return self.answer(self.inputs, prompt) - - def popen(self, args, **options): - self.calls.append(("popen", args)) - return self.answer(self.popens, args) - - def run(self, args, **options): - self.calls.append(("run", args)) - return self.answer(self.runs, args) - - def sleep(self, seconds): - self.calls.append(("sleep", seconds)) + def made(self, seam): + return [what for called, what in self.calls if called == seam] def ran(stdout="", code=0, stderr=""): @@ -96,34 +94,31 @@ class Worker: return Streamed(self.code) -class Streamed(io.StringIO): +class Streamed: def __init__(self, code): - super().__init__(json.dumps({"type": "result"}) + "\n") - self.stdout, self.code = self, code + self.code = code + + def lines(self): + return [json.dumps({"type": "result"}) + "\n"] def wait(self): return self.code class Transitions(unittest.TestCase): - def test_a_run_resumes_only_while_its_transcript_exists(self): - self.assertEqual(states.opening(""), states.Fresh()) - self.assertEqual(states.opening("/t.jsonl"), states.Resuming()) - def test_each_state_moves_on_its_events_and_only_on_them(self): for state, event, after in ( - (states.Fresh(), states.WorkerRan("/t"), states.Judging("/t")), - (states.Resuming(), states.WorkerRan("/t"), states.Judging("/t")), + (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")), - (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Resuming()), + (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Ended()), (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), - (states.Finishing("/t"), states.Archived(), states.Fresh()), + (states.Finishing("/t"), states.Archived(), states.Ended()), ): with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) with self.assertRaises(ValueError): - states.transition(states.Fresh(), states.Answered()) + states.transition(states.Working(), states.Answered()) class Cycles(unittest.TestCase): @@ -141,17 +136,17 @@ class Cycles(unittest.TestCase): return sorted(path.read_text() for path in (self.paths.archive / "proj").glob("*.verdict.md")) def test_a_finished_chunk_is_archived_and_its_session_deleted(self): - fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)], runs=[judged("finished")]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) self.assertIsNone(steps.run_cycle(self.cycle(fake))) self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertEqual(session.transcript_file(self.session), "") def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self): - fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)] * 2, runs=[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.assertTrue(session.transcript_file(self.session)) self.assertIsNone(steps.run_cycle(self.cycle(fake))) - workers = [args for kind, args in fake.calls if kind == "popen"] + workers = fake.made("stream_claude") self.assertIn("--session-id", workers[0]) self.assertIn("--resume", workers[1]) self.assertFalse((self.paths.archive / "proj").exists()) @@ -160,14 +155,15 @@ class Cycles(unittest.TestCase): def answer(args): with open(session.transcript_file(self.session), "a") as handle: handle.write(json.dumps(human("the second")) + "\n") - return ran() - fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)], runs=[judged("interrupt"), ran(), answer, judged("unfinished")]) + 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.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"]) - self.assertEqual([args[0] for kind, args in fake.calls if kind == "run"], ["claude", "git", "claude", "claude"]) + self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) + self.assertEqual(len(fake.made("claude")), 2) def test_stops_when_the_worker_leaves_no_transcript(self): - fake = FakeEffects(popens=[lambda args: 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}")) @@ -189,9 +185,13 @@ class Interrupts(unittest.TestCase): self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) self.assertEqual(fake.calls, []) - def test_counts_only_turns_typed_after_the_handover(self): - self.assertFalse(interrupt.typed_since(1, [human("a")])) - self.assertTrue(interrupt.typed_since(1, [human("a"), human("b")])) + def test_stops_when_nothing_was_typed_in_the_handover(self): + with tempfile.TemporaryDirectory() as home: + path = pathlib.Path(home, "t.jsonl") + path.write_text(json.dumps(human("a")) + "\n") + fake = FakeEffects(on_terminal_claude=[0], git=[ran()]) + stop = interrupt.interrupt(home, uuid.uuid4(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects()) + self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) class ModelPrompt(unittest.TestCase): @@ -208,7 +208,7 @@ class ModelPrompt(unittest.TestCase): with tempfile.TemporaryDirectory() as empty: fake = FakeEffects(inputs=["", "my-model"]) self.assertEqual(models.ask_model("proj", "/m.json", pathlib.Path(empty), fake.effects()), "my-model") - self.assertEqual(len(fake.calls), 2) + self.assertEqual(len(fake.made("input")), 2) fake = FakeEffects(inputs=[EOFError()]) self.assertEqual(models.ask_model("proj", "/m.json", pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended")) @@ -313,11 +313,11 @@ class Verdict(unittest.TestCase): self.assertEqual(judge.verdict_from(None), Failure("the judge returned no verdict")) -class LoopState(unittest.TestCase): +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_state([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_decodes_a_state_whose_annotations_are_strings(self): @dataclasses.dataclass(frozen=True) @@ -331,13 +331,13 @@ class LoopState(unittest.TestCase): with tempfile.TemporaryDirectory() as root: launcher = pathlib.Path(root, "loop-claude") launcher.write_text("") - fake = FakeEffects(runs=[ran()]) - self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopState(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude ")) + fake = FakeEffects(python=[ran()]) + 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): def test_lists_the_root_alone_when_git_cannot_start(self): - fake = FakeEffects(runs=[FileNotFoundError(2, "No such file or directory")]) + fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")]) self.assertEqual(checkout.checkouts("/r", fake.effects()), ["/r"]) diff --git a/docs/decisions.md b/docs/decisions.md index 75a94fb3..9680ad4d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -103,3 +103,7 @@ ## chunk: as large as one purpose allows 2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: up to ten, a few lines each, share one chunk whatever their purposes and passes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch. + +## loop-claude: a cycle's state machine holds the paths that move it on, and a `Stop` leaves it + +2026-10-02, larv-review. Applies "Always use explicit state machines". A `Stop` ends the process, so no later state could act on it; a `Stopped` state would add a case every step must pass through and nothing would read. Valid while every failure of a cycle ends the loop. -- 2.52.0 From 8e221712cb7b83877afadb6bdf93b15521040e8f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:20:57 +0200 Subject: [PATCH 3/9] Answer the architect's second round --- bin/loop_claude/loop/main.py | 6 +++--- bin/loop_claude/loop/reload.py | 2 +- bin/test_loop_claude.py | 6 +++--- docs/decisions.md | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 841805e1..6b3c8d81 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -40,7 +40,7 @@ import sys from loop_claude.claude_code.session import session_for from loop_claude.cycle.steps import Cycle, run_cycle from loop_claude.effects import Effects -from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_state, 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.project.checkout import checkout_root, project_name from loop_claude.project.models import project_models @@ -86,7 +86,7 @@ def loop_run_from(argv, cwd, effects: Effects) -> LoopRun | Stop: return Stop(0 if task else 1, __doc__.strip()) root = checkout_root(cwd, effects) return root if isinstance(root, Stop) else LoopRun(0, root, task) - loop_run = decode_state(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): - return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") + return Stop(1, f"the reload cannot read the loop run from {argv[1:]}; rerun loop-claude ") return loop_run diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index a0599203..33ca164f 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -20,7 +20,7 @@ class LoopRun: task: str -def decode_state(handed, kind: type[T]) -> T | None: +def decode_handed(handed, kind: type[T]) -> T | None: try: fields = json.loads(handed) except ValueError: diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 431c0799..e58d3940 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -317,15 +317,15 @@ 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's state from {handed}; rerun loop-claude ")) + 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 ")) def test_decodes_a_state_whose_annotations_are_strings(self): @dataclasses.dataclass(frozen=True) class Stringly: count: "int" name: "str" - self.assertEqual(reload.decode_state('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n")) - self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly)) + self.assertEqual(reload.decode_handed('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n")) + self.assertIsNone(reload.decode_handed('{"count": "1", "name": "n"}', Stringly)) def test_stops_when_the_reload_cannot_start_python(self): with tempfile.TemporaryDirectory() as root: diff --git a/docs/decisions.md b/docs/decisions.md index 9680ad4d..dc5b2926 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -106,4 +106,4 @@ ## loop-claude: a cycle's state machine holds the paths that move it on, and a `Stop` leaves it -2026-10-02, larv-review. Applies "Always use explicit state machines". A `Stop` ends the process, so no later state could act on it; a `Stopped` state would add a case every step must pass through and nothing would read. Valid while every failure of a cycle ends the loop. +2026-10-01, larv-review. Applies "Always use explicit state machines". A `Stop` ends the process, so no later state could act on it; a `Stopped` state would add a case every step must pass through and nothing would read. Valid while every failure of a cycle ends the loop. -- 2.52.0 From fa53ae61372b4b2a3d1e011e6bf074f72b545805 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:29:50 +0200 Subject: [PATCH 4/9] File what the architecture round found outside the chunk --- todo.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/todo.md b/todo.md index cea6b120..7f8875f2 100644 --- a/todo.md +++ b/todo.md @@ -8,6 +8,10 @@ The first two items are the places the panel on `rebuild` at 8585257 named under - **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, one seat learnt the cases only from `HumanTurns` in the tests, and another could not confirm them without `HumanTurns`. Three seats named it the unit they least wanted to modify, and the architect named it where the project rots first. - **Annotate the parameter types in `bin/loop_claude/`.** Whether `root` or `path` is a `str` or a `Path` is learnt by tracing callers back to `bin/loop-claude`. +- **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` (`session.py:32`) only prints a failed removal, so `close` reports `Archived` and the next chunk resumes the finished chunk's session without its own task prompt. Return a `Failure` and stop on it; move `session_open` into `session.py`; have `transcript_file` return `str | None`. Raised by the 2026-10-01 panel's inherited architect and the logging and technical-principles audits. Goal 4.1. +- **Give larv-review §3's rules one home per rule.** Every seat of the 2026-10-01 panel needed `SKILL.md`, `review-findings.md` and `CLAUDE.md` open to apply one rule of "Round cap" or "Re-entry". Goal 4.1. +- **Name `loop_claude`'s modules by what they hold.** 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`. Goal 4.1. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:28` 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. @@ -23,6 +27,27 @@ The first two items are the places the panel on `rebuild` at 8585257 named under - `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. - **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. 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. + - 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`. + - 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. +- **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. +- **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. +- **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. +- **Move what the plan and the decision log point at under `~/code/claude-handoffs/` into the repo.** The design sketches, the judges' verdicts and the bench scripts are unreachable from another machine's checkout. 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.py:82` 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. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. -- 2.52.0 From 9f80bfb9defdad175c859b09ac997343535c51da Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:30:41 +0200 Subject: [PATCH 5/9] Use UUID v7s in the unit tests --- bin/test_loop_claude.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index e58d3940..b8971c8c 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -5,6 +5,7 @@ import pathlib import subprocess import sys import tempfile +import time import unittest import uuid @@ -70,6 +71,12 @@ class FakeEffects: return [what for called, what in self.calls if called == seam] +def uuid7(): + # Python 3.11, the floor, has no uuid.uuid7. + random = int.from_bytes(os.urandom(10)) + return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1) + + def ran(stdout="", code=0, stderr=""): return subprocess.CompletedProcess([], code, stdout, stderr) @@ -181,7 +188,7 @@ class Retried(unittest.TestCase): class Interrupts(unittest.TestCase): def test_stops_off_a_terminal_before_starting_claude(self): fake = FakeEffects(on_terminal=False) - stop = interrupt.interrupt("/r", uuid.uuid4(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects()) + stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects()) self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) self.assertEqual(fake.calls, []) @@ -190,7 +197,7 @@ class Interrupts(unittest.TestCase): path = pathlib.Path(home, "t.jsonl") path.write_text(json.dumps(human("a")) + "\n") fake = FakeEffects(on_terminal_claude=[0], git=[ran()]) - stop = interrupt.interrupt(home, uuid.uuid4(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects()) + stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects()) self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) -- 2.52.0 From dbf3c6e27ae469f842e43b24929cd342d87570a6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:34:41 +0200 Subject: [PATCH 6/9] Answer the stability review's first round --- bin/test_loop_claude.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index b8971c8c..4e7e2478 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -45,7 +45,7 @@ class FakeEffects: def effects(self): return Effects( - claude=lambda args, cwd, stdin: self.answer("claude", args), + claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=lambda args, cwd: self.answer("claude_on_terminal", args), execv=self.execv, git=lambda args, cwd: self.answer("git", args), @@ -89,8 +89,8 @@ def judged(verdict, evidence="working"): class Worker: """A worker claude: writes a line to the session's transcript, then streams a result.""" - def __init__(self, home, code=0): - self.home, self.code = home, code + def __init__(self, home): + self.home = home def __call__(self, args): flag = "--session-id" if "--session-id" in args else "--resume" @@ -98,7 +98,7 @@ class Worker: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a") as handle: handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n") - return Streamed(self.code) + return Streamed(0) class Streamed: @@ -114,18 +114,24 @@ class Streamed: class Transitions(unittest.TestCase): def test_each_state_moves_on_its_events_and_only_on_them(self): - for state, event, after in ( + legal = ( (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), (states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")), (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Ended()), (states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")), (states.Finishing("/t"), states.Archived(), states.Ended()), - ): + ) + for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - with self.assertRaises(ValueError): - states.transition(states.Working(), states.Answered()) + every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Finishing("/t"), states.Ended()) + every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived()) + for state in every_state: + for event in every_event: + if (state, event) not in [(state, event) for state, event, _ in legal]: + with self.subTest(state=state, event=event), self.assertRaises(ValueError): + states.transition(state, event) class Cycles(unittest.TestCase): @@ -167,7 +173,10 @@ class Cycles(unittest.TestCase): self.assertIsNone(steps.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]) - self.assertEqual(len(fake.made("claude")), 2) + prompts = [stdin for args, stdin in fake.made("claude")] + self.assertEqual(len(prompts), 2) + self.assertNotIn("the second", prompts[0]) + self.assertIn("[human] the second", prompts[1]) def test_stops_when_the_worker_leaves_no_transcript(self): fake = FakeEffects(streams=[Streamed(0)]) -- 2.52.0 From 1514327d34f42eec125b98693d9bbe28272843d6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:38:06 +0200 Subject: [PATCH 7/9] Answer the prose review's first round, ship under the floor, and plan giving the judge the decisions --- AGENTS.md | 2 +- bin/loop_claude/cycle/judge.py | 1 - bin/loop_claude/cycle/states.py | 4 ++-- bin/loop_claude/cycle/steps.py | 5 ++--- bin/loop_claude/loop/main.py | 2 +- docs/decisions.md | 8 ++++---- todo.md | 13 +++++++------ 7 files changed, 17 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9812f1f5..07ebf5e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,4 +28,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the planned stats line goes in the transcript archive - workflow changes: a change merges only once three planned benches rule it better - chunk: as large as one purpose allows -- loop-claude: a cycle's state machine holds the paths that move it on, and a `Stop` leaves it +- loop-claude: a cycle's states cover only its progress, and a returned `Stop` ends the cycle diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 52a6130a..acf07502 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -28,7 +28,6 @@ JUDGE_RULES = ( "not yet run, CI not yet reported." ) -# The reply's shape, which the schema below hands claude; verdict_from reads it into a Verdict. @dataclasses.dataclass(frozen=True) class Reply: evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."}) diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 8c316fcd..fe3443d0 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -5,7 +5,7 @@ from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict @dataclasses.dataclass(frozen=True) class Working: - """The worker runs: opening the session, or resuming it while its transcript exists.""" + """The worker runs.""" @dataclasses.dataclass(frozen=True) @@ -26,7 +26,7 @@ class Finishing: @dataclasses.dataclass(frozen=True) class Ended: - """The cycle is over; the next one starts Working.""" + """The cycle is over.""" Active = Working | Judging | Interrupting | Finishing diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/steps.py index 42d05ae8..c386395a 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/steps.py @@ -52,7 +52,7 @@ def step(cycle, state: Active) -> Event | Stop: def work(cycle) -> WorkerRan | Stop: - # Asked at each attempt: a failed one may have opened the session. + # session_open runs inside the lambda: a failed attempt may have opened the session. if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session)), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) @@ -68,7 +68,7 @@ def rule(cycle, transcript_path) -> Ruled | Stop: def ask(cycle, transcript_path, question) -> Answered | Stop: - # The interrupt appends to this transcript, so it is archived at each question and judged anew after. + # 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): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or Answered() @@ -82,5 +82,4 @@ def close(cycle, transcript_path) -> Archived | Stop: def session_open(session) -> bool: - """A run resumes the session only while its transcript exists.""" return bool(transcript_file(session)) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 6b3c8d81..52f932af 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -12,7 +12,7 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V 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, claude cannot start for an -interrupt, python cannot start for a reload, a reload with unreadable state, or the worker or the +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, diff --git a/docs/decisions.md b/docs/decisions.md index dc5b2926..34fcefc8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -6,7 +6,7 @@ ## loop-claude: a judge decides interrupts, not the worker's self-report -2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. +2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge also reads `docs/decisions.md` and `AGENTS.md`, so an answer recorded there is never asked again (goal 4.2); `todo.md`'s "Give the judge the project's recorded decisions" ends the README-only bar. Valid while the worker's self-report stays unreliable. ## loop-claude: one session per project, at a fixed id from its checkout's path @@ -30,7 +30,7 @@ ## 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. 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 main at the loop state machine's PR scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor 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. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -104,6 +104,6 @@ 2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: up to ten, a few lines each, share one chunk whatever their purposes and passes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch. -## loop-claude: a cycle's state machine holds the paths that move it on, and a `Stop` leaves it +## loop-claude: a cycle's states cover only its progress, and a returned `Stop` ends the cycle -2026-10-01, larv-review. Applies "Always use explicit state machines". A `Stop` ends the process, so no later state could act on it; a `Stopped` state would add a case every step must pass through and nothing would read. Valid while every failure of a cycle ends the loop. +2026-10-01, larv-review. Applies "Always use explicit state machines". A `Stop` ends the process, so no later state could act on it. A `Stopped` state would add an event and a transition that nothing reads. Valid until a cycle must act after a `Stop`, as `todo.md`'s "Archive the transcript as each cycle ends" would. diff --git a/todo.md b/todo.md index 7f8875f2..4f663bf0 100644 --- a/todo.md +++ b/todo.md @@ -4,16 +4,17 @@ The rebuild's design sketches, the blind judges' verdicts on them and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The first two items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). +The first six items are the places the panels on `rebuild` at 8585257 and on main on 2026-10-01 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). - **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, one seat learnt the cases only from `HumanTurns` in the tests, and another could not confirm them without `HumanTurns`. Three seats named it the unit they least wanted to modify, and the architect named it where the project rots first. - **Annotate the parameter types in `bin/loop_claude/`.** Whether `root` or `path` is a `str` or a `Path` is learnt by tracing callers back to `bin/loop-claude`. -- **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` (`session.py:32`) only prints a failed removal, so `close` reports `Archived` and the next chunk resumes the finished chunk's session without its own task prompt. Return a `Failure` and stop on it; move `session_open` into `session.py`; have `transcript_file` return `str | None`. Raised by the 2026-10-01 panel's inherited architect and the logging and technical-principles audits. Goal 4.1. +- **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` (`session.py:32`) only prints a failed removal, so `close` reports `Archived` and the next chunk resumes the finished chunk's session without its own task prompt. Return a `Failure` and stop on it; move `session_open` into `session.py`; have `transcript_file` return `str | None`. Goal 4.1. - **Give larv-review §3's rules one home per rule.** Every seat of the 2026-10-01 panel needed `SKILL.md`, `review-findings.md` and `CLAUDE.md` open to apply one rule of "Round cap" or "Re-entry". Goal 4.1. -- **Name `loop_claude`'s modules by what they hold.** 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. +- **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`. Goal 4.1. -- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:28` 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 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. +- **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. - **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. @@ -48,7 +49,7 @@ The first two items are the places the panel on `rebuild` at 8585257 named under - **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. - **Move what the plan and the decision log point at under `~/code/claude-handoffs/` into the repo.** The design sketches, the judges' verdicts and the bench scripts are unreachable from another machine's checkout. 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.py:82` 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. +- **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. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - 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. -- 2.52.0 From a6a5f99bfec3568387a7c337b7d2480bfdc81ae0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:40:49 +0200 Subject: [PATCH 8/9] Answer the prose review's second round --- docs/decisions.md | 4 ++-- todo.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 34fcefc8..1e8e5be0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -6,7 +6,7 @@ ## loop-claude: a judge decides interrupts, not the worker's self-report -2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge also reads `docs/decisions.md` and `AGENTS.md`, so an answer recorded there is never asked again (goal 4.2); `todo.md`'s "Give the judge the project's recorded decisions" ends the README-only bar. Valid while the worker's self-report stays unreliable. +2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. On 2026-10-01 lilleman decided the judge is to read `docs/decisions.md` and `AGENTS.md` too, so an answer recorded there is not asked again (goal 4.2); `todo.md`'s "Give the judge the project's recorded decisions" ends the README-only bar. Valid while the worker's self-report stays unreliable. ## loop-claude: one session per project, at a fixed id from its checkout's path @@ -30,7 +30,7 @@ ## 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 main at the loop state machine's PR scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor 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. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 4f663bf0..9bfb2737 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,7 @@ The rebuild's design sketches, the blind judges' verdicts on them and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The first six items are the places the panels on `rebuild` at 8585257 and on main on 2026-10-01 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). +The first six items are the places the panels on `rebuild` at 8585257 and on PR #182 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). - **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, one seat learnt the cases only from `HumanTurns` in the tests, and another could not confirm them without `HumanTurns`. Three seats named it the unit they least wanted to modify, and the architect named it where the project rots first. - **Annotate the parameter types in `bin/loop_claude/`.** Whether `root` or `path` is a `str` or a `Path` is learnt by tracing callers back to `bin/loop-claude`. -- 2.52.0 From f8131946ae0df67c2acaad01d29fa4fdabc4cb05 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:42:12 +0200 Subject: [PATCH 9/9] File the product-owner nits under the exit-contract item --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 9bfb2737..6bb3b2b3 100644 --- a/todo.md +++ b/todo.md @@ -11,7 +11,7 @@ The first six items are the places the panels on `rebuild` at 8585257 and on PR - **Make a failed session delete stop the loop, and give the session one owner.** `delete_session` (`session.py:32`) only prints a failed removal, so `close` reports `Archived` and the next chunk resumes the finished chunk's session without its own task prompt. Return a `Failure` and stop on it; move `session_open` into `session.py`; have `transcript_file` return `str | None`. Goal 4.1. - **Give larv-review §3's rules one home per rule.** Every seat of the 2026-10-01 panel needed `SKILL.md`, `review-findings.md` and `CLAUDE.md` open to apply one rule of "Round cap" or "Re-entry". Goal 4.1. - **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`. 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. - **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. - **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. -- 2.52.0