From f385b563f0772f5c61d5f8ef2987a4e281a7c93d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:12:37 +0200 Subject: [PATCH] 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.