Answer the architect's first round

This commit is contained in:
2026-10-01 23:19:10 +02:00
parent f385b563f0
commit 00446be689
12 changed files with 188 additions and 150 deletions
+2 -6
View File
@@ -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")
+1 -1
View File
@@ -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:
+23 -27
View File
@@ -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}")
+48 -31
View File
@@ -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))
+9 -12
View File
@@ -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:
+30 -4
View File
@@ -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,
)
+15 -15
View File
@@ -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 <task>")
return state
return loop_run
+5 -4
View File
@@ -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 <task>")
return None
+2 -2
View File
@@ -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: