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: