Answer the architect's first round
This commit is contained in:
@@ -28,3 +28,4 @@ Decisions live in `docs/decisions.md`:
|
|||||||
- loop-claude: the planned stats line goes in the transcript archive
|
- loop-claude: the planned stats line goes in the transcript archive
|
||||||
- workflow changes: a change merges only once three planned benches rule it better
|
- workflow changes: a change merges only once three planned benches rule it better
|
||||||
- chunk: as large as one purpose allows
|
- 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
|
||||||
|
|||||||
@@ -20,14 +20,10 @@ def interrupt(root, session_id, model, path, question, paths, effects: Effects)
|
|||||||
return Stop(1, entries.reason)
|
return Stop(1, entries.reason)
|
||||||
before = human_turns(entries)
|
before = human_turns(entries)
|
||||||
try:
|
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:
|
except OSError as failure:
|
||||||
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
|
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
|
||||||
entries = read(path)
|
entries = read(path)
|
||||||
if isinstance(entries, Failure):
|
if isinstance(entries, Failure):
|
||||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
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")
|
return None if human_turns(entries) > before else human_needed.stop(TO, "the interrupt ended with nothing typed")
|
||||||
|
|
||||||
|
|
||||||
def typed_since(turns_before, entries) -> bool:
|
|
||||||
return human_turns(entries) > turns_before
|
|
||||||
|
|||||||
@@ -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:
|
def run_judge(root, args, prompt, transcript, effects: Effects) -> Verdict | Failure:
|
||||||
try:
|
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:
|
except OSError as failure:
|
||||||
return Failure(f"could not start claude: {failure.strerror}")
|
return Failure(f"could not start claude: {failure.strerror}")
|
||||||
if proc.returncode != 0:
|
if proc.returncode != 0:
|
||||||
|
|||||||
@@ -4,37 +4,38 @@ from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
|
|||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Fresh:
|
class Working:
|
||||||
"""No transcript: the worker opens the session."""
|
"""The worker runs: opening the session, or resuming it while its transcript exists."""
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
|
||||||
class Resuming:
|
|
||||||
"""The session's transcript exists: the worker continues it."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Judging:
|
class Judging:
|
||||||
transcript: str
|
transcript_path: str
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Interrupting:
|
class Interrupting:
|
||||||
transcript: str
|
transcript_path: str
|
||||||
question: str
|
question: str
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Finishing:
|
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)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class WorkerRan:
|
class WorkerRan:
|
||||||
transcript: str
|
transcript_path: str
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
@@ -55,23 +56,18 @@ class Archived:
|
|||||||
Event = WorkerRan | Ruled | Answered | 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:
|
def transition(state: State, event: Event) -> State:
|
||||||
"""The state after event; a cycle ends when it reaches Fresh or Resuming again."""
|
|
||||||
match state, event:
|
match state, event:
|
||||||
case Fresh() | Resuming(), WorkerRan(transcript):
|
case Working(), WorkerRan(transcript_path):
|
||||||
return Judging(transcript)
|
return Judging(transcript_path)
|
||||||
case Judging(transcript), Ruled(Interrupt(question=question)):
|
case Judging(transcript_path), Ruled(Interrupt(question=question)):
|
||||||
return Interrupting(transcript, question)
|
return Interrupting(transcript_path, question)
|
||||||
case Judging(transcript), Ruled(Finished()):
|
case Judging(transcript_path), Ruled(Finished()):
|
||||||
return Finishing(transcript)
|
return Finishing(transcript_path)
|
||||||
case Judging(), Ruled(Unfinished()):
|
case Judging(), Ruled(Unfinished()):
|
||||||
return Resuming()
|
return Ended()
|
||||||
case Interrupting(transcript), Answered():
|
case Interrupting(transcript_path), Answered():
|
||||||
return Judging(transcript)
|
return Judging(transcript_path)
|
||||||
case Finishing(), Archived():
|
case Finishing(), Archived():
|
||||||
return Fresh()
|
return Ended()
|
||||||
raise ValueError(f"no transition from {state} on {event}")
|
raise ValueError(f"no transition from {state} on {event}")
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import dataclasses
|
import dataclasses
|
||||||
|
import typing
|
||||||
|
|
||||||
from loop_claude.claude_code.session import Session, delete_session, transcript_file
|
from loop_claude.claude_code.session import Session, delete_session, transcript_file
|
||||||
from loop_claude.claude_code.transcript import read, render
|
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.interrupt import interrupt
|
||||||
from loop_claude.cycle.judge import judge
|
from loop_claude.cycle.judge import judge
|
||||||
from loop_claude.cycle.retry import retried
|
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.cycle.worker import run_worker, worker_args
|
||||||
from loop_claude.effects import Effects
|
from loop_claude.effects import Effects
|
||||||
from loop_claude.outcome import Failure, Stop
|
from loop_claude.outcome import Failure, Stop
|
||||||
@@ -27,43 +28,59 @@ class Cycle:
|
|||||||
|
|
||||||
|
|
||||||
def run_cycle(cycle) -> Stop | None:
|
def run_cycle(cycle) -> Stop | None:
|
||||||
state: State = opening(transcript_file(cycle.session))
|
state: State = Working()
|
||||||
while True:
|
while not isinstance(state, Ended):
|
||||||
event = step(cycle, state)
|
event = step(cycle, state)
|
||||||
if isinstance(event, Stop):
|
if isinstance(event, Stop):
|
||||||
return event
|
return event
|
||||||
state = transition(state, event)
|
state = transition(state, event)
|
||||||
if isinstance(state, Fresh | Resuming):
|
return None
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def step(cycle, state) -> Event | Stop:
|
def step(cycle, state: Active) -> Event | Stop:
|
||||||
"""Carries out state's effects and reports what happened."""
|
|
||||||
match state:
|
match state:
|
||||||
case Fresh() | Resuming():
|
case Working():
|
||||||
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 work(cycle)
|
||||||
return stop
|
case Judging(transcript_path):
|
||||||
path = transcript_file(cycle.session)
|
return rule(cycle, transcript_path)
|
||||||
return WorkerRan(path) if path else Stop(1, f"claude left no transcript for session {cycle.session.id}")
|
case Interrupting(transcript_path, question):
|
||||||
case Judging(path):
|
return ask(cycle, transcript_path, question)
|
||||||
entries = read(path)
|
case Finishing(transcript_path):
|
||||||
if isinstance(entries, Failure):
|
return close(cycle, transcript_path)
|
||||||
return Stop(1, entries.reason)
|
case _:
|
||||||
verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge, cycle.effects)
|
typing.assert_never(state)
|
||||||
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:
|
def work(cycle) -> WorkerRan | Stop:
|
||||||
# Asked at each attempt: a failed one may have opened the session.
|
# 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))
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import subprocess
|
|
||||||
|
|
||||||
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
|
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
|
||||||
from loop_claude.claude_code.transcript import part_line
|
from loop_claude.claude_code.transcript import part_line
|
||||||
from loop_claude.effects import Effects
|
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:
|
def run_worker(root, args, effects: Effects) -> Failure | None:
|
||||||
try:
|
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:
|
except OSError as failure:
|
||||||
return Failure(f"could not start claude: {failure.strerror}")
|
return Failure(f"could not start claude: {failure.strerror}")
|
||||||
with proc:
|
done = False
|
||||||
done = False
|
for raw in proc.lines():
|
||||||
for raw in proc.stdout or ():
|
event = parse(raw) or {}
|
||||||
event = parse(raw) or {}
|
done = done or ends_stream(event)
|
||||||
done = done or ends_stream(event)
|
for part in assistant_parts(event):
|
||||||
for part in assistant_parts(event):
|
if line := part_line(part, 160):
|
||||||
if line := part_line(part, 160):
|
print(line, flush=True)
|
||||||
print(line, flush=True)
|
code = proc.wait()
|
||||||
code = proc.wait()
|
|
||||||
if code < 0:
|
if code < 0:
|
||||||
return Failure(f"claude killed by signal {-code}")
|
return Failure(f"claude killed by signal {-code}")
|
||||||
if code:
|
if code:
|
||||||
|
|||||||
@@ -6,22 +6,48 @@ import time
|
|||||||
import typing
|
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)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Effects:
|
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]
|
execv: typing.Callable[[str, list[str]], None]
|
||||||
|
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||||
input: typing.Callable[[str], str]
|
input: typing.Callable[[str], str]
|
||||||
on_terminal: typing.Callable[[], bool]
|
on_terminal: typing.Callable[[], bool]
|
||||||
popen: typing.Callable[..., subprocess.Popen]
|
python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||||
run: typing.Callable[..., subprocess.CompletedProcess]
|
|
||||||
sleep: typing.Callable[[float], None]
|
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:
|
def system_effects() -> Effects:
|
||||||
return 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,
|
execv=os.execv,
|
||||||
|
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
|
||||||
input=input,
|
input=input,
|
||||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||||
popen=subprocess.Popen,
|
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
|
||||||
run=subprocess.run,
|
|
||||||
sleep=time.sleep,
|
sleep=time.sleep,
|
||||||
|
stream_claude=Popened,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ import sys
|
|||||||
from loop_claude.claude_code.session import session_for
|
from loop_claude.claude_code.session import session_for
|
||||||
from loop_claude.cycle.steps import Cycle, run_cycle
|
from loop_claude.cycle.steps import Cycle, run_cycle
|
||||||
from loop_claude.effects import Effects
|
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.outcome import Stop
|
||||||
from loop_claude.project.checkout import checkout_root, project_name
|
from loop_claude.project.checkout import checkout_root, project_name
|
||||||
from loop_claude.project.models import project_models
|
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:
|
def run_loop(argv, env, paths, launcher, cwd, effects: Effects) -> Stop:
|
||||||
state = loop_state(argv, cwd, effects)
|
loop_run = loop_run_from(argv, cwd, effects)
|
||||||
if isinstance(state, Stop):
|
if isinstance(loop_run, Stop):
|
||||||
return state
|
return loop_run
|
||||||
baseline = fingerprint(launcher)
|
baseline = fingerprint(launcher)
|
||||||
project = project_name(state.root, paths.code)
|
project = project_name(loop_run.root, paths.code)
|
||||||
session = session_for(project, paths)
|
session = session_for(project, paths)
|
||||||
while True:
|
while True:
|
||||||
if stop := exec_if_edited(launcher, baseline, state, effects):
|
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||||
return stop
|
return stop
|
||||||
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
|
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||||
premises = read_premises(state.root)
|
premises = read_premises(loop_run.root)
|
||||||
if isinstance(premises, Stop):
|
if isinstance(premises, Stop):
|
||||||
return premises
|
return premises
|
||||||
models = project_models(project, paths, env, effects)
|
models = project_models(project, paths, env, effects)
|
||||||
if isinstance(models, Stop):
|
if isinstance(models, Stop):
|
||||||
return models
|
return models
|
||||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
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=state.root, session=session, task=state.task)):
|
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
|
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]:
|
if argv[:1] != [RELOAD_FLAG]:
|
||||||
task = " ".join(argv)
|
task = " ".join(argv)
|
||||||
if task in ("", "-h", "--help"):
|
if task in ("", "-h", "--help"):
|
||||||
return Stop(0 if task else 1, __doc__.strip())
|
return Stop(0 if task else 1, __doc__.strip())
|
||||||
root = checkout_root(cwd, effects)
|
root = checkout_root(cwd, effects)
|
||||||
return root if isinstance(root, Stop) else LoopState(0, root, task)
|
return root if isinstance(root, Stop) else LoopRun(0, root, task)
|
||||||
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
|
loop_run = decode_state(argv[1], LoopRun) if len(argv) == 2 else None
|
||||||
if not (state and state.root and state.task):
|
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 Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||||
return state
|
return loop_run
|
||||||
|
|||||||
@@ -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.
|
# A field change stops a running loop at its next reload: the new script rejects the old fields.
|
||||||
@dataclasses.dataclass(frozen=True)
|
@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
|
cycle_number: int
|
||||||
root: str
|
root: str
|
||||||
task: str
|
task: str
|
||||||
@@ -43,15 +44,15 @@ def fingerprint(launcher) -> str:
|
|||||||
return digest.hexdigest()
|
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:
|
if fingerprint(launcher) == baseline:
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
trial = effects.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
|
trial = effects.python([str(launcher), "--help"])
|
||||||
if trial.returncode != 0:
|
if trial.returncode != 0:
|
||||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||||
return None
|
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:
|
except OSError as failure:
|
||||||
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
|
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from loop_claude.outcome import Stop
|
|||||||
|
|
||||||
def checkout_root(cwd, effects: Effects) -> str | Stop:
|
def checkout_root(cwd, effects: Effects) -> str | Stop:
|
||||||
try:
|
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:
|
except OSError as failure:
|
||||||
return Stop(1, f"could not start git: {failure.strerror}")
|
return Stop(1, f"could not start git: {failure.strerror}")
|
||||||
if found.returncode != 0:
|
if found.returncode != 0:
|
||||||
@@ -15,7 +15,7 @@ def checkout_root(cwd, effects: Effects) -> str | Stop:
|
|||||||
def checkouts(root, effects: Effects) -> list[str]:
|
def checkouts(root, effects: Effects) -> list[str]:
|
||||||
found = [root]
|
found = [root]
|
||||||
try:
|
try:
|
||||||
listing = effects.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
|
listing = effects.git(["worktree", "list", "--porcelain"], root)
|
||||||
except OSError:
|
except OSError:
|
||||||
return found
|
return found
|
||||||
if listing.returncode == 0:
|
if listing.returncode == 0:
|
||||||
|
|||||||
+48
-48
@@ -1,5 +1,4 @@
|
|||||||
import dataclasses
|
import dataclasses
|
||||||
import io
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import pathlib
|
import pathlib
|
||||||
@@ -38,16 +37,27 @@ def queued(prompt, kind):
|
|||||||
class FakeEffects:
|
class FakeEffects:
|
||||||
"""Effects that record each call and answer from a script, one answer per call."""
|
"""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.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
|
self.terminal = on_terminal
|
||||||
|
|
||||||
def effects(self):
|
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):
|
def answer(self, seam, what):
|
||||||
answer = script.pop(0)
|
self.calls.append((seam, what))
|
||||||
|
answer = self.scripts[seam].pop(0)
|
||||||
if isinstance(answer, BaseException):
|
if isinstance(answer, BaseException):
|
||||||
raise answer
|
raise answer
|
||||||
return answer(what) if callable(answer) else answer
|
return answer(what) if callable(answer) else answer
|
||||||
@@ -56,20 +66,8 @@ class FakeEffects:
|
|||||||
self.calls.append(("execv", args))
|
self.calls.append(("execv", args))
|
||||||
raise OSError(2, "No such file or directory")
|
raise OSError(2, "No such file or directory")
|
||||||
|
|
||||||
def input(self, prompt):
|
def made(self, seam):
|
||||||
self.calls.append(("input", prompt))
|
return [what for called, what in self.calls if called == seam]
|
||||||
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=""):
|
def ran(stdout="", code=0, stderr=""):
|
||||||
@@ -96,34 +94,31 @@ class Worker:
|
|||||||
return Streamed(self.code)
|
return Streamed(self.code)
|
||||||
|
|
||||||
|
|
||||||
class Streamed(io.StringIO):
|
class Streamed:
|
||||||
def __init__(self, code):
|
def __init__(self, code):
|
||||||
super().__init__(json.dumps({"type": "result"}) + "\n")
|
self.code = code
|
||||||
self.stdout, self.code = self, code
|
|
||||||
|
def lines(self):
|
||||||
|
return [json.dumps({"type": "result"}) + "\n"]
|
||||||
|
|
||||||
def wait(self):
|
def wait(self):
|
||||||
return self.code
|
return self.code
|
||||||
|
|
||||||
|
|
||||||
class Transitions(unittest.TestCase):
|
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):
|
def test_each_state_moves_on_its_events_and_only_on_them(self):
|
||||||
for state, event, after in (
|
for state, event, after in (
|
||||||
(states.Fresh(), states.WorkerRan("/t"), states.Judging("/t")),
|
(states.Working(), 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(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")),
|
||||||
(states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")),
|
(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.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):
|
with self.subTest(state=state, event=event):
|
||||||
self.assertEqual(states.transition(state, event), after)
|
self.assertEqual(states.transition(state, event), after)
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
states.transition(states.Fresh(), states.Answered())
|
states.transition(states.Working(), states.Answered())
|
||||||
|
|
||||||
|
|
||||||
class Cycles(unittest.TestCase):
|
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"))
|
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):
|
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.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
||||||
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
|
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
|
||||||
self.assertEqual(session.transcript_file(self.session), "")
|
self.assertEqual(session.transcript_file(self.session), "")
|
||||||
|
|
||||||
def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self):
|
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.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
||||||
self.assertTrue(session.transcript_file(self.session))
|
self.assertTrue(session.transcript_file(self.session))
|
||||||
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
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("--session-id", workers[0])
|
||||||
self.assertIn("--resume", workers[1])
|
self.assertIn("--resume", workers[1])
|
||||||
self.assertFalse((self.paths.archive / "proj").exists())
|
self.assertFalse((self.paths.archive / "proj").exists())
|
||||||
@@ -160,14 +155,15 @@ class Cycles(unittest.TestCase):
|
|||||||
def answer(args):
|
def answer(args):
|
||||||
with open(session.transcript_file(self.session), "a") as handle:
|
with open(session.transcript_file(self.session), "a") as handle:
|
||||||
handle.write(json.dumps(human("the second")) + "\n")
|
handle.write(json.dumps(human("the second")) + "\n")
|
||||||
return ran()
|
return 0
|
||||||
fake = FakeEffects(popens=[Worker(self.paths.claude_code_transcripts.parent)], runs=[judged("interrupt"), ran(), answer, judged("unfinished")])
|
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.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
||||||
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"])
|
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):
|
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}"))
|
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(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, [])
|
self.assertEqual(fake.calls, [])
|
||||||
|
|
||||||
def test_counts_only_turns_typed_after_the_handover(self):
|
def test_stops_when_nothing_was_typed_in_the_handover(self):
|
||||||
self.assertFalse(interrupt.typed_since(1, [human("a")]))
|
with tempfile.TemporaryDirectory() as home:
|
||||||
self.assertTrue(interrupt.typed_since(1, [human("a"), human("b")]))
|
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):
|
class ModelPrompt(unittest.TestCase):
|
||||||
@@ -208,7 +208,7 @@ class ModelPrompt(unittest.TestCase):
|
|||||||
with tempfile.TemporaryDirectory() as empty:
|
with tempfile.TemporaryDirectory() as empty:
|
||||||
fake = FakeEffects(inputs=["", "my-model"])
|
fake = FakeEffects(inputs=["", "my-model"])
|
||||||
self.assertEqual(models.ask_model("proj", "/m.json", pathlib.Path(empty), fake.effects()), "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()])
|
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"))
|
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"))
|
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):
|
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"})]):
|
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):
|
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 <task>"))
|
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 <task>"))
|
||||||
|
|
||||||
def test_decodes_a_state_whose_annotations_are_strings(self):
|
def test_decodes_a_state_whose_annotations_are_strings(self):
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
@@ -331,13 +331,13 @@ class LoopState(unittest.TestCase):
|
|||||||
with tempfile.TemporaryDirectory() as root:
|
with tempfile.TemporaryDirectory() as root:
|
||||||
launcher = pathlib.Path(root, "loop-claude")
|
launcher = pathlib.Path(root, "loop-claude")
|
||||||
launcher.write_text("")
|
launcher.write_text("")
|
||||||
fake = FakeEffects(runs=[ran()])
|
fake = FakeEffects(python=[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 <task>"))
|
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 <task>"))
|
||||||
|
|
||||||
|
|
||||||
class Checkouts(unittest.TestCase):
|
class Checkouts(unittest.TestCase):
|
||||||
def test_lists_the_root_alone_when_git_cannot_start(self):
|
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"])
|
self.assertEqual(checkout.checkouts("/r", fake.effects()), ["/r"])
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -103,3 +103,7 @@
|
|||||||
## chunk: as large as one purpose allows
|
## 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.
|
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.
|
||||||
|
|||||||
Reference in New Issue
Block a user