Group a cycle's modules under cycle/, apart from claude_code/

This commit is contained in:
2026-09-29 11:55:53 +02:00
parent aba2a98d7e
commit 830ba331ca
10 changed files with 8 additions and 9 deletions
View File
+23
View File
@@ -0,0 +1,23 @@
import hashlib
import sys
from loop_claude.file_writes import make_private, replace_file
from loop_claude.outcome import Failure
def archive(project, path, note, paths):
folder = paths.archive / project
try:
with open(path, "rb") as handle:
raw = handle.read()
make_private(folder)
except OSError as failure:
return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}")
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
# The copy lands last, so a copy on disk always has its verdict beside it.
if not copy.exists():
for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)):
if failure := replace_file(dest, data):
return Failure(f"could not archive the transcript: {dest}: {failure.reason}")
print(f"transcript: {copy}", file=sys.stderr)
return None
+31
View File
@@ -0,0 +1,31 @@
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.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):
print(f"\n{question}", file=sys.stderr)
if stop := human_needed.off_terminal(TO):
return stop
trust(paths.claude_json, checkouts(root))
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)
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
+97
View File
@@ -0,0 +1,97 @@
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.outcome import Failure
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
"- it carried on under an assumption that decides the deliverable and that the human could "
"reasonably reject; a caveat about transient state it then handled is not one\n"
"- it is blocked on something only the human can supply: a credential, a version bump, a release "
"ready to cut, a choice outside the repo\n"
"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
"- it chose between alternatives the README text does not discriminate between - it does not "
"rule the rejected one out - and the choice materially changes the deliverable\n"
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
"is still open, never a question they already answered there.\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n"
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
"its own. finished=false when work remains that a further run can continue: an open PR, a review "
"not yet run, CI not yet reported."
)
@dataclasses.dataclass(frozen=True)
class Verdict:
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)
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),
"type": "object",
}
def judge(root, task, premises, transcript, model):
# 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",
"--json-schema", json.dumps(JUDGE_SCHEMA),
"--model", model,
"--no-session-persistence",
"--output-format", "json",
"--permission-mode", "bypassPermissions",
"--tools", "",
]
prompt = judge_prompt(task, premises, transcript)
return retried("judge", lambda: run_judge(root, args, prompt, transcript))
def run_judge(root, args, prompt, transcript):
try:
proc = subprocess.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:
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
verdict = verdict_from(structured_output(proc.stdout))
if isinstance(verdict, Verdict) and 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 ""))
return verdict
def judge_prompt(task, premises, transcript):
return (
f"From README.md:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
f"{JUDGE_RULES}"
)
def verdict_from(output):
if not isinstance(output, dict):
return Failure("the judge returned no verdict")
for name, kind in VERDICT_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})
def grounded(verdict, transcript):
return verdict.evidence.strip() != "" and verdict.evidence in transcript
+16
View File
@@ -0,0 +1,16 @@
import itertools
import sys
import time
from loop_claude.outcome import Failure, Stop
def retried(who, attempt):
for failures in itertools.count(1):
result = attempt()
if not isinstance(result, Failure):
return result
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)
+54
View File
@@ -0,0 +1,54 @@
import dataclasses
from loop_claude.claude_code.session import Session, delete_session, transcript_file
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 judge
from loop_claude.cycle.retry import retried
from loop_claude.cycle.worker import run_worker, worker_args
from loop_claude.outcome import Failure, Stop
from loop_claude.paths import Paths
from loop_claude.project.models import Models
@dataclasses.dataclass(frozen=True)
class Cycle:
models: Models
paths: Paths
premises: str
project: str
root: str
session: Session
task: str
def run_cycle(cycle):
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)
def judge_through_interrupts(cycle, path):
# The interrupt appends to this transcript, so each pass judges and archives it anew.
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
+40
View File
@@ -0,0 +1,40 @@
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.outcome import Failure
def run_worker(root, args):
try:
proc = subprocess.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:
done = False
for raw in proc.stdout:
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:
return Failure(f"claude exited {code}")
return None if done else Failure("claude exited 0 without a result event")
def worker_args(task, session, model, resuming):
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)]
else:
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", session.name, "--session-id", str(session.id)]
return [
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
"--model", model,
]