Name the loop's states with one transition function, and inject its side effects

This commit is contained in:
2026-10-01 23:12:37 +02:00
parent d0ce3b2690
commit f385b563f0
16 changed files with 469 additions and 126 deletions
+10 -8
View File
@@ -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
+23 -18
View File
@@ -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:
+3 -3
View File
@@ -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)
+77
View File
@@ -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}")
+42 -28
View File
@@ -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)
+20
View File
@@ -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
+3 -2
View File
@@ -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:
+27
View File
@@ -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,
)
+2 -4
View File
@@ -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")
+10 -9
View File
@@ -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):
+4 -5
View File
@@ -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 <task>")
return None
+5 -6
View File
@@ -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:
+26 -15
View File
@@ -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}\": \"<model>\"}} 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}\": \"<model>\"}} 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)}")