219 lines
14 KiB
Python
219 lines
14 KiB
Python
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
|
|
|
usage: loop-claude <task>
|
|
|
|
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
|
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
|
worker prompt also quotes the premises. They, with code health
|
|
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
|
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
|
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
|
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
|
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
|
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
|
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
|
|
writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the
|
|
worker made that the premises or the records settle is not asked about. When the worker asks a
|
|
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
|
|
with it. A quote they do not hold word for word is dropped, and the question goes to the human. So
|
|
does a question asked again after its answer. The fourth question they answer in one cycle goes to
|
|
the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker
|
|
is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session.
|
|
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
|
|
|
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
|
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
|
|
interrupts of every loop on the machine. The first answer counts, from either place:
|
|
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
|
chunk stays unfinished until the answer is recorded.
|
|
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
|
|
discuss first. Once that claude exits, the judge rules on what was typed there.
|
|
- Enter alone, on loop-claude's terminal: stops the loop.
|
|
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
|
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
|
|
|
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
|
as bin/loop_claude/running_loops.py describes.
|
|
|
|
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
|
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
|
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
|
after 600 s and is stopped, leaves the worker to find the facts itself.
|
|
|
|
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
|
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
|
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
|
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
|
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
|
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
|
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
|
|
|
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
|
|
(bin/machine_load/memory.py).
|
|
|
|
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
|
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
|
|
compacts its context at about 170k tokens.
|
|
|
|
Every claude loop-claude starts runs the project's model, saved per <key> in
|
|
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
|
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
|
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
|
|
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
|
|
the worker and the session /talk opens; with both set, nothing is asked.
|
|
|
|
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
|
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
|
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
|
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
|
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
|
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
|
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
|
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
|
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
|
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
|
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
|
without it.
|
|
|
|
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
|
loop to close one measures every finished chunk there, with no model run, and writes
|
|
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
|
|
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
|
|
on the terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to
|
|
the human; loop-inbox lists it too. Once that claude ends, the calls are listed in
|
|
routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised
|
|
again at the next measurement.
|
|
|
|
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
|
loop-claude --help succeeds: the loop reloads into the edited script.
|
|
|
|
Exit 1, saying why, when:
|
|
- no task is given
|
|
- git cannot start or finds no checkout
|
|
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
|
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
|
- README.md holds no premises
|
|
- the models file cannot be read or written
|
|
- claude leaves no transcript
|
|
- a transcript cannot be read or archived
|
|
- a finished chunk's session cannot be deleted
|
|
- claude cannot start for an interrupt
|
|
- python cannot start for a reload
|
|
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
|
handover
|
|
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
|
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
|
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
|
mistypes a field, interrupts or quotes an answer without a question, or quotes a passage the
|
|
transcript does not hold; it holds an elided passage when each fragment appears in order.
|
|
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
|
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
|
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
|
always retried every 10 minutes. stderr says when the next try is due.
|
|
|
|
Exit 2, when the human is needed to go on:
|
|
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
|
- the input ends while a model is picked
|
|
- an interrupt's answer is empty, or the input ends before one is typed
|
|
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
|
nothing typed
|
|
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
|
Rerunning resumes any open session.
|
|
|
|
"""
|
|
import dataclasses
|
|
import pathlib
|
|
import typing
|
|
|
|
from transcript_archive.location import archive_root, project_archive
|
|
from loop_claude.loop.chunk_start import archived_route, chunk_start, routed, shown_items
|
|
from loop_claude.loop.routing_check import check_routing
|
|
from loop_claude.project.checkout import checkout_root
|
|
from loop_claude.loop.close import closed_cycle
|
|
from loop_claude.cycle.run import Cycle, run_cycle
|
|
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
|
from loop_claude.effects import Effects, say
|
|
from failure import Failure
|
|
from loop_claude.project.model_choice import get_or_ask_models
|
|
from loop_claude.running_loops import Listed, shown_running
|
|
from loop_claude.paths import Paths
|
|
from project_key import project_key
|
|
from model_routing.ladder import project_rung
|
|
from loop_claude.project.premises import read_premises
|
|
from loop_claude.project.records import read_records
|
|
from claude_code.session import Session, session_named
|
|
from loop_claude.stop import Stop
|
|
|
|
|
|
|
|
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
|
try:
|
|
stop = run_loop(argv, env, paths, launcher, cwd, effects)
|
|
except KeyboardInterrupt:
|
|
stop = Stop(130, "")
|
|
if stop.reason:
|
|
say(stop.reason, effects, stdout=not stop.code)
|
|
return stop.code
|
|
|
|
|
|
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> Stop:
|
|
loop_run = loop_run_from(argv, cwd, effects)
|
|
if isinstance(loop_run, Stop):
|
|
return loop_run
|
|
baseline = fingerprint(launcher)
|
|
# "A " is the human's cue in the session picker that the session is the loop's.
|
|
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
|
|
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed:
|
|
while True:
|
|
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
|
return stop
|
|
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
|
cycle = next_cycle(loop_run, session, listed, paths, env, launcher, effects)
|
|
if isinstance(cycle, Stop):
|
|
return cycle
|
|
concluded = run_cycle(cycle)
|
|
if isinstance(concluded, Stop):
|
|
return concluded
|
|
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, session, effects)
|
|
if isinstance(closed, Stop):
|
|
return closed
|
|
loop_run = closed
|
|
# Off the ladder the worker runs on the project's model itself, which its route names.
|
|
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), cycle.project or cycle.route.rung, paths, listed.folder, effects):
|
|
return stop
|
|
|
|
|
|
def next_cycle(loop_run: LoopRun, session: Session, listed: Listed, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> Cycle | Stop:
|
|
"""The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
|
|
premises = read_premises(loop_run.root)
|
|
if isinstance(premises, Failure):
|
|
return Stop(1, premises.reason)
|
|
records = read_records(loop_run.root, paths.claude_dir)
|
|
if isinstance(records, Failure):
|
|
return Stop(1, records.reason)
|
|
models = get_or_ask_models(project_key(loop_run.root, paths.home), paths, env, effects)
|
|
if isinstance(models, Stop):
|
|
return models
|
|
archive_folder = project_archive(loop_run.root, paths.home, env)
|
|
# After the reads above, so a loop that stops on one makes no worktree.
|
|
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
|
project = project_rung(models.worker)
|
|
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
|
|
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
|
|
show_taken_in = shown_items(listed.show, loop_run.root, route.item)
|
|
show_taken_in(loop_run.items_taken_in)
|
|
return Cycle(effects=effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=listed.folder, records=records, root=loop_run.root, route=route, session=session, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)
|
|
|
|
|
|
def loop_run_from(argv: list[str], cwd: pathlib.Path, 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 LoopRun(0, root, task, "")
|
|
loop_run = decode_handed(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 edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
|
|
return loop_run
|