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.