Rename loop-claude to build-release, with no alias

This commit is contained in:
2026-12-03 15:22:11 +01:00
parent 38102d5aa5
commit 969190064e
139 changed files with 717 additions and 671 deletions
View File
+13
View File
@@ -0,0 +1,13 @@
import pathlib
from failure import Failure
from loop_effects.effects import Effects
from agent_cycle.stop import Stop
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
found = effects.git("rev-parse", "--show-toplevel", cwd=str(cwd))
return Stop(1, found.reason) if isinstance(found, Failure) else found.strip()
+65
View File
@@ -0,0 +1,65 @@
"""How build-release's cycle starts: the plan it fetches, the item it takes, and the facts chunk-preflight finds for a fresh chunk. The route is `chunk_driver.cycle_start`'s."""
from git_cli.git_repo import default_ref
from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELEASES
from loop_effects.effects import Effects, say
from failure import Failure
from build_release.chunk import fresh_prompt
from build_release.loop.chunk_windows import held_beside, item_of
from chunk_preflight.main import ITEM
from plan.todo_table import Item
from project_config.main import located
from chunk_driver.this_loop import Loop
from plan_store.plans import Plan
from build_release.routed_item import routed_item
from claude_code.session import session_open
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
ORIGIN_TIMEOUT = 60
def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Failure:
"""The plan, which scores the items a chunk takes, from what the default branch holds; where it can't be read or scored, it says why."""
plan = default.plan if isinstance(default, DefaultPlan) else default
if isinstance(plan, Failure):
say(f"the items the worker names lift no rung: {plan.reason}", effects)
return plan
def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]:
"""The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
fresh = not session_open(loop.session)
return chunk_facts(loop) if fresh else "", fetched_plan(loop, fresh)
def chunk_facts(loop: Loop) -> str:
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold."""
item = item_of(loop.window.name)
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root)
facts = fresh_prompt.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else fresh_prompt.preflight_facts(done.stdout.strip())
held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects)
return facts + (fresh_prompt.held_by_others(held) if held else "")
def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle."""
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
return config
if announce and config.tracked("plan") is None:
say(UNSEEN_RELEASES, loop.effects)
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git, loop.effects.forge(loop.root))
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
# It prints the reason itself, through effects, like the other build-release functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
if isinstance(plan, Failure):
item: Item | Failure | None = plan
else:
item = routed_item(plan.plan, plan.cut, window_item)
if isinstance(item, Failure):
say(f"routing on the project's rung: {item.reason}", effects)
return None
return item
+177
View File
@@ -0,0 +1,177 @@
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `build-release: each chunk runs in its own tmux window`)."""
import dataclasses
import pathlib
import re
import typing
from touch_predictions.beside import Beside, chunks_beside
from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_session, project_lock, starting
from build_release.chunk import chunk_items
from git_cli.git_repo import default_ref
from loop_effects.effects import Effects, say
from failure import Failure
from project_config.main import located
from build_release.loop.reload import LoopRun
from release_plan.next_chunk import NextChunk, NoItem, planned
from plan.touches import overlaps, predicted, Touches
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from release_plan.release_standing import project_plan
from claude_code.transcript import read_transcript
from claude_code.session import Session, session_named, transcript_file
from agent_cycle import tmux
# The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan.
NO_ITEM = "no-item"
# Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched.
FETCH_TIMEOUT = 60
def window_name(item_id: int) -> str:
return f"item-{item_id}"
def item_of(chunk: str) -> int | None:
"""The ID of the plan item a chunk starts from; None for NO_ITEM."""
named = re.fullmatch(r"item-([0-9]+)", chunk)
return int(named[1]) if named else None
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
return session_named(f"A {key} build-release {chunk}", claude_code_transcripts)
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
"""The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from."""
held: set[int] = set()
for chunk in chunks:
held.update(filter(None, [item_of(chunk)]))
transcript = transcript_file(chunk_session(key, chunk, claude_code_transcripts))
entries = read_transcript(transcript) if transcript else []
held.update([] if isinstance(entries, Failure) else chunk_items.named(entries))
return held
@dataclasses.dataclass(frozen=True)
class Room:
"""What a project's windows leave room for, under its limit of chunks at once."""
# The chunks whose windows run.
running: list[str]
# The chunks whose windows are dead: their loop stopped or failed, and the window keeps its last lines and its items.
stopped: list[str]
# The stopped chunks to start again, before any chunk from the plan.
restart: list[str]
# How many chunks from the plan may start beside them.
left: int
def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room:
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's build-release <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's build-release <task>, restarts one."""
running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)]
# Below 0 where the config lowered parallel-chunks while more chunks ran.
room = max(limit - len(running), 0)
stopped = [window.name for window in windows if window.dead]
restart = [] if leaving else stopped[:room]
return Room(running, stopped, restart, room - len(restart))
@dataclasses.dataclass(frozen=True)
class AwaitedMerges:
"""Why no chunk starts and none runs: every item left awaits a person's merge of the pull requests that why names."""
why: str
def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]:
"""The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone."""
if isinstance(plan, NoItem):
return [] if running or room < 1 else [NO_ITEM]
beside = chunks_beside(plan.items, plan.first)
picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])]
details = {item.id: item.detail for item in plan.items}
# chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing.
theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details]
free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)]
return [window_name(item_id) for item_id in free][: max(room, 0)]
def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool:
"""Whether a prediction overlaps none of theirs; not where one of them is missing or unreadable, unless theirs is empty."""
return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs))
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure:
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
config = located(root, home)
if isinstance(config, Failure):
return config
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT)
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
if isinstance(ref, Failure):
return ref
held = project_plan(config, ref, root, effects.git, effects.forge(root))
return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | AwaitedMerges | Failure:
"""Starts a build-release in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started build-release. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run."""
config = located(loop_run.root, paths.home)
if isinstance(config, Failure):
return config
session = loop_session(loop_run.root, paths.home)
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
with starting(project_lock(loop_run.root, paths.home)) as unlocked:
if unlocked:
return unlocked
windows = tmux.listed(session, effects.tmux)
if refused := refusal(session, windows, loop_run.root, effects.tmux):
return refused
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects)
if isinstance(chunks, AwaitedMerges):
return chunks
for chunk in chunks:
started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux)
if isinstance(started, Failure):
return started
windows = started
return chunks
def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) -> Failure | None:
"""Why no chunk of the checkout root may start in session, whose windows are windows: another checkout's chunks run in the session, or do-epic runs chunks in root."""
if windows and (owned := tmux.owner(session, run)) != root:
return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders")
if theirs := epic_chunks(root, run):
return Failure(f"do-epic runs chunks in {root}: {', '.join(f'{placed.window.name} of {placed.session}' for placed in theirs)}; build-release doesn't start a chunk there until those chunks finish")
return None
def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges:
"""The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge."""
room = room_of(windows, loop_run.chunk, leaving, limit)
if not room.left:
return room.restart
plan = next_plan(loop_run.root, paths.home, effects)
if isinstance(plan, Failure):
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
plan = NoItem(plan.reason)
held = held_items(room.running + room.stopped, project_key(loop_run.root, paths.home), paths.claude_code_transcripts)
if isinstance(plan, NoItem) and plan.awaits_merge and not room.running + room.restart:
return AwaitedMerges(plan.why)
picked = may_start(plan, room.running + room.restart, held, room.left)
return room.restart + [chunk for chunk in picked if chunk not in room.stopped]
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
"""The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it."""
wait_for_starts(root, paths.home)
others = [window.name for window in tmux.listed(loop_session(root, paths.home), effects.tmux) if window.name != chunk]
return sorted(held_items(others, project_key(root, paths.home), paths.claude_code_transcripts))
def wait_for_starts(root: str, home: pathlib.Path) -> None:
"""Returns once no loop of the project is starting windows: start_chunks holds the lock file `claims.LOCK` names while it starts them. Where the lock cannot be taken, it returns at once."""
with starting(project_lock(root, home)):
pass
+172
View File
@@ -0,0 +1,172 @@
import dataclasses
import pathlib
import typing
from chunk_driver.cycle_start import announced_route, cycle_of, project_routing
from transcript_archive.location import archive_root, project_archive
from build_release.loop.chunk_windows import AwaitedMerges, chunk_session, item_of, start_chunks
from build_release.loop.routing_check import check_routing
from build_release.loop.checkout import checkout_root
from chunk_driver.claims import CHUNK_FLAG, loop_session
from build_release.chunk import chunk_items, fresh_prompt
from build_release.loop.chunk_start import chunk_start, plan_item, scored_plan
from chunk_driver.chunk_run import closed_cycle
from agent_cycle.run import Concluded, Cycle, run_cycle
from build_release.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from loop_effects.effects import Effects, say
from failure import Failure
from agent_cycle.verdicts import Finished
from build_release.loop.usage import HELP
from chunk_driver.this_loop import Loop
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from model_routing.ladder import ProjectRung, Rung
from chunk_driver.project.premises import read_premises
from chunk_driver.project.records import read_records
from model_routing.ladder_file import SHIPPED
from agent_cycle.stop import Stop
from agent_cycle.direct_message import tell
from agent_cycle import tmux
# Starts the chunks that may start now, as chunk_windows.start_chunks does.
StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | AwaitedMerges | Failure]
@dataclasses.dataclass(frozen=True)
class Steps:
"""The steps a loop takes, each the function of its name, which main binds."""
start_chunks: StartChunks
fingerprint: typing.Callable[[pathlib.Path], str]
exec_if_edited: typing.Callable[[Loop, str, LoopRun], Stop | None]
next_cycle: typing.Callable[[LoopRun, Loop], Cycle | Stop]
run_cycle: typing.Callable[[Cycle], Stop | Concluded]
closed_cycle: typing.Callable[[LoopRun, str, ProjectRung | None, Concluded, pathlib.Path, str, Loop], LoopRun | Stop]
check_routing: typing.Callable[[pathlib.Path, Rung, Loop], Stop | None]
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
steps = Steps(start_chunks, fingerprint, exec_if_edited, next_cycle, run_cycle, closed_cycle, check_routing)
return exit_code(lambda: run_loop(argv, env, paths, launcher, cwd, effects, steps), cwd, effects)
def exit_code(run: typing.Callable[[], Stop], cwd: pathlib.Path, effects: Effects) -> int:
"""The exit code of the loop that run runs in cwd, once its stop is said and sent as a DM."""
try:
stop = run()
except KeyboardInterrupt:
stop = Stop(130, "")
except Exception as crash:
tell(f"build-release in {cwd} crashed: {crash!r}", effects)
raise
if stop.reason:
say(stop.reason, effects, stdout=not stop.code)
# Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on.
if stop.reason not in ("", HELP):
tell(f"build-release in {cwd} stopped: {stop.reason}", effects)
return stop.code
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects, steps: Steps) -> Stop:
loop_run = loop_run_from(argv, cwd, effects)
if isinstance(loop_run, Stop):
return loop_run
# Before anything starts: a worktree, a claude session or a tmux window.
if reason := tmux.unusable(effects.tmux, fresh_prompt.DRIVER):
return Stop(1, reason)
if loop_run.chunk is None:
return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks)
pane = env.get("TMUX_PANE")
if not pane:
return Stop(1, f"{CHUNK_FLAG} is how build-release starts itself in a tmux window; run build-release <task>")
baseline = steps.fingerprint(launcher)
key = project_key(loop_run.root, paths.home)
window = tmux.Window(loop_session(loop_run.root, paths.home), loop_run.chunk, pane)
loop = Loop(root=loop_run.root, session=chunk_session(key, loop_run.chunk, paths.claude_code_transcripts), window=window, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := steps.exec_if_edited(loop, baseline, loop_run):
return stop
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
cycle = steps.next_cycle(loop_run, loop)
if isinstance(cycle, Stop):
return cycle
concluded = steps.run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = steps.closed_cycle(loop_run, cycle.task, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop)
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 := steps.check_routing(archive_root(paths.home, env), cycle.project.rung if cycle.project else cycle.route.rung, loop):
return stop
if isinstance(concluded.verdict, Finished):
return handed_on(loop_run, loop, steps.start_chunks)
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, start: StartChunks) -> Stop:
"""What the build-release the human runs does: starts, through start, each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
started = start(loop_run, False, paths, env, launcher, effects)
if isinstance(started, AwaitedMerges):
return Stop(0, started.why)
if isinstance(started, Failure):
return Stop(1, started.reason)
session = loop_session(loop_run.root, paths.home)
say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now, so `{loop_run.task}` started in no new window", effects, stdout=True)
if not effects.on_terminal():
say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True)
return Stop(0, "")
shown = tmux.show(session, "TMUX" in env)
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "")
def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop:
"""The stop of a loop whose chunk finished, once it has started, through start, each chunk that may start now. Its window closes as it exits."""
started = start(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
if isinstance(started, AwaitedMerges):
return Stop(0, f"the chunk finished; {started.why}")
if isinstance(started, Failure):
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True)
return Stop(0, "")
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
"""The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
premises = read_premises(loop.root, loop.paths.home)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
records = read_records(loop.root, loop.paths.home, loop.paths.claude_dir)
if isinstance(records, Failure):
return Stop(1, records.reason)
routing = project_routing(loop, fresh_prompt.DRIVER)
if isinstance(routing, Stop):
return routing
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
# After the reads above, so a loop that stops on one makes no worktree.
facts, default = chunk_start(loop)
route = announced_route(loop_run.cycle_number, loop_run.route, routing, archive_folder, lambda: plan_item(default, item_of(loop.window.name), loop.effects), loop)
if routing.ladder_file != SHIPPED:
say(own_ladder(routing.ladder_file, routing.models.worker, routing.project is None), loop.effects)
plan = scored_plan(default, loop.effects)
return cycle_of(loop, routing, route, archive_folder, task=loop_run.task, facts=facts, premises=premises, records=records, unfinished_evidence=loop_run.unfinished_evidence, prompts=fresh_prompt.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan))
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
"""What a cycle says of a project that runs on a ladder of its own, so that a file left in place after its reason passed doesn't go unseen, nor one that leaves out the project's model, whose work the ladder then doesn't route."""
routes = f" {model} is not on it, so the worker runs on {model} unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run." if unrouted else ""
return f"routing on the project's own ladder, {file}.{routes}"
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
if argv[:1] != [RELOAD_FLAG]:
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == CHUNK_FLAG else (None, argv)
task = " ".join(words)
if task in ("", "-h", "--help"):
return Stop(0 if task else 1, HELP)
root = checkout_root(cwd, effects)
return root if isinstance(root, Stop) else LoopRun(0, root, task, "", chunk=chunk)
loop_run = decode_handed(argv[1]) if len(argv) == 2 else None
if not (loop_run and loop_run.root and loop_run.task):
return Stop(1, f"the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. Handed: {' '.join(argv[1:])}")
return loop_run
+108
View File
@@ -0,0 +1,108 @@
import dataclasses
import hashlib
import json
import pathlib
import sys
import typing
from chunk_driver.this_loop import Loop
from model_routing.route import Route, route_of
from loop_effects.effects import say
from agent_cycle.stop import Stop
RELOAD_FLAG = "--reloaded"
# A field removed, renamed or retyped stops a running loop at its next reload: the new script rejects the old fields. A new field with a default does not.
@dataclasses.dataclass(frozen=True)
class LoopRun:
"""What a reload hands the edited script, as JSON on argv."""
cycle_number: int
root: str
task: str
unfinished_evidence: str
# Set by each unfinished verdict; None before the chunk's first one, and once it finishes.
route: Route | None = None
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
# The chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the build-release the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so starts the project's windows; its open claude session, named for its slot, is left in the session picker (docs/decisions.md → `build-release: each chunk runs in its own tmux window, …`).
chunk: str | None = None
class Unreadable(Exception):
"""The handed JSON isn't a LoopRun."""
def decode_handed(handed: str) -> LoopRun | None:
"""The LoopRun the JSON holds; None for text that isn't one. A field of LoopRun or Route with a default may be missing, so a field the sending script didn't know yet doesn't stop the loop; an effort missing from a Rung is empty."""
try:
fields = json.loads(handed)
except ValueError:
return None
# A loop started before 0.11.0 hands the items loop-inbox listed; dropping them keeps it running across its reload.
# One started before chunks ran in tmux windows hands the slot it held.
if isinstance(fields, dict):
fields.pop("items_taken_in", None)
fields.pop("slot", None)
try:
return LoopRun(**decoded_fields(fields, LOOP_RUN_FIELDS, "cycle_number", "root", "task", "unfinished_evidence"))
except Unreadable:
return None
def decoded_fields(value: object, decoders: dict[str, typing.Callable[[typing.Any], typing.Any]], *required: str) -> dict[str, typing.Any]:
"""Each field of the JSON object through its decoder. Raises Unreadable for a value that isn't an object, an object missing a required field, and an object holding a field that has no decoder."""
if not isinstance(value, dict) or not set(required) <= value.keys() <= decoders.keys():
raise Unreadable
return {name: decoders[name](field) for name, field in value.items()}
def exactly(kind: type) -> typing.Callable[[typing.Any], typing.Any]:
"""A decoder of a value of exactly this type. It checks type(), since isinstance(True, int) holds and a JSON true must not pass as an integer."""
def decode(value: object) -> object:
if type(value) is not kind:
raise Unreadable
return value
return decode
def decoded_route(value: object) -> Route | None:
"""The Route the JSON holds; None for null. dataclasses.asdict wrote it as a worker line's fields, with the rung nested and the unfinished count added. route_of reads it once the rung's model and effort are lifted to the top and the count is set aside."""
if value is None:
return None
if not isinstance(value, dict) or not isinstance(value.get("rung"), dict) or not value["rung"].keys() <= {"model", "effort"} or value.keys() & {"model", "effort"}:
raise Unreadable
route = route_of({**{name: field for name, field in value.items() if name not in ("rung", "unfinished")}, **value["rung"]})
if route is None:
raise Unreadable
return dataclasses.replace(route, unfinished=exactly(int)(value.get("unfinished", 0)))
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "chunk": lambda value: None if value is None else exactly(str)(value)}
def fingerprint(launcher: pathlib.Path) -> str:
digest = hashlib.sha256()
for path in [launcher, *sorted(launcher.parent.rglob("*.py"))]:
try:
content = path.read_bytes()
except OSError as failure:
content = str(failure).encode()
digest.update(f"{path.relative_to(launcher.parent)}\0{len(content)}\0".encode() + content)
return digest.hexdigest()
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to build-release to use without the human rerunning it.
def exec_if_edited(loop: Loop, baseline: str, loop_run: LoopRun) -> Stop | None:
if fingerprint(loop.launcher) == baseline:
return None
trial = loop.effects.python([str(loop.launcher), "--help"], loop.root)
if trial.returncode != 0:
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", loop.effects)
return None
try:
loop.effects.execv(sys.executable, [sys.executable, str(loop.launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
except OSError as failure:
return Stop(1, f"could not reload build-release: {failure.strerror}; rerun build-release <task>")
return None
+72
View File
@@ -0,0 +1,72 @@
"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: build-release measures review rounds…`."""
import pathlib
from routing_figures import archive
from routing_figures.calls import Call, calls, totals
from agent_cycle.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, say
from failure import Failure
from chunk_driver.this_loop import Loop
from loop_state.paths import Paths
from model_routing.ladder_file import read_ladder, SHIPPED
from routing_figures.render import render
from model_routing.ladder import Rung
from routing_figures import state
from agent_cycle.stop import Stop
from agent_cycle.direct_message import tell
from text_files.utc_stamp import utc
def check_routing(root: pathlib.Path, rung: Rung, loop: Loop) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. root is the archive's, and rung is the rung of the claude that puts the calls to the human."""
with archive.locked(root) as held:
new = new_calls(root, loop.paths, loop.effects) if held else []
if isinstance(new, Failure):
say(f"routing figures: {new.reason}", loop.effects)
return None
return raise_calls(root, new, rung, loop) if new else None
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
"""Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due."""
cycle = archive.cycles(root)
if isinstance(cycle, Failure):
return cycle
kept = state.read_state(root)
if isinstance(kept, Failure) or not state.due(cycle, kept.measured_at):
return kept if isinstance(kept, Failure) else []
raised = state.raised(root)
if isinstance(raised, Failure):
return raised
say(f"\n=== cycle {cycle} across build-release's archive: measuring the routing figures ===", effects, stdout=True)
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
if isinstance(measured, Failure):
return measured
# The shipped ladder, not the project's: the figures span every project.
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return ladder
figures = totals(measured.chunks, measured.skipped, measured.unread)
found = calls(ladder, figures)
if unwritten := archive.write_figures(root, render(ladder, figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
return unwritten
return [call for call in found if call not in raised.calls]
def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
bullets = "".join(f"- {call.sentence()}\n" for call in new)
question = f"build-release's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
say(f"\n{question}", loop.effects)
tell(f"build-release in {loop.root} asks:\n\n{question}", loop.effects)
if not loop.effects.on_terminal():
say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects)
return None
prompt = f"Put these calls for a routing change from build-release's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as the setup's CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
if unstarted:
return Stop(1, f"could not start claude for the routing calls in {loop.paths.config_clone}, the setup's development clone: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through docs/decisions.md → "Working rules", so it is not asked twice.
if unmarked := state.mark_raised(root, new, utc(loop.effects.now()), loop.effects.replace_file):
say(f"routing figures: {unmarked.reason}", loop.effects)
return None
+186
View File
@@ -0,0 +1,186 @@
import contextlib
import dataclasses
import io
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from chunk_driver.doubles import a_loop
from build_release.loop import chunk_start, chunk_windows, reload
from project_config.doubles import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from failure import Failure
from loop_effects.doubles import FakeEffects, ran, STAMP
from build_release.chunk import fresh_prompt
from build_release.doubles import NO_CUT, TODO
from loop_state import paths
from plan_store.todo_md import plan_of
from claude_code import session
from agent_cycle import tmux
# What git answers as `default_ref` reads the default branch in a checkout on main: the remote, the branch checked out, no chunk base, and origin's default branch.
ON_MAIN = ["origin\n", "main\n", Failure("no chunk base"), "origin/main\n"]
class RouteSources(unittest.TestCase):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects()))
def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self):
plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO]))
later = next(item.id for item in plan.plan.items if item.id != 3)
self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later)
# An item that left the plan, as once it shipped.
self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects()))
# A chunk start reads the default branch once, for routing and for scoring the items the worker names.
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
config = folder / "config.toml"
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(TODO)
opened = session.session_named("A proj build-release", pathlib.Path(root, "projects"))
transcript = pathlib.Path(root, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text("{}\n")
unread = Failure("no git")
fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread])
with contextlib.redirect_stderr(io.StringIO()) as stderr:
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1])))
self.assertEqual((facts, held.plan), ("", plan_of(TODO)))
self.assertEqual([args for args in fake.made("git") if args[0] == "remote"], [["remote"]])
# An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show.
self.assertEqual(stderr.getvalue(), "")
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects()))
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"))
for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
scored = chunk_start.scored_plan(default, FakeEffects().effects())
self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "")
self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default)
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
def git(*args, **options):
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "config": Failure("no chunk base"), "show": f"what {args[-1]} holds\n"}
return answers.get(args[0], "1\n")
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
effects = dataclasses.replace(FakeEffects().effects(), git=git)
held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1])))
self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n")
def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_as_the_loops_forge_lists_them(self):
head = "a" * 40
finished = TODO.replace("| 3 | 0.2.0 | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n", "")
def git(*args, **options):
if args[:2] == ("remote", "get-url"):
return "https://github.com/o/r\n"
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "merge-base": "base\n", "show": finished if args[-1] == f"{head}:todo.md" else TODO}
return answers.get(args[0], "1\n")
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
(folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n')
fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 3)
held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1])))
self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")])
self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"])
self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk")
window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git))
self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick")
stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git))
self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on")
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self):
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
config = folder / "config.toml"
tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(tracked)
self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release")
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(TODO)
unread = Failure("no git")
standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
held = chunk_start.fetched_plan(standing)
self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review build-release cannot call due is never skipped silently")
quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(quiet, announce=False)
self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts")
config.unlink()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason)
self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue())
self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason)
class ChunkFacts(unittest.TestCase):
# The launcher beside which chunk_start finds /b/chunk-preflight.
LAUNCHER = pathlib.Path("/b/build-release")
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")])
self.assertTrue(said.endswith("\n\n- A fact."), said)
self.assertNotIn("yourself", said)
def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4")))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self):
# The loop's own window, a stopped one and two that run, one of them waiting for the human.
fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n")
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
self.assertEqual(fresh_prompt.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.")
self.assertTrue(fresh_prompt.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9."))
# A worker whose preflight failed is told them too.
fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n")
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self):
for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")):
with self.subTest(why=why):
said = chunk_start.chunk_facts(a_loop(FakeEffects(python=[failed]).effects(), launcher=self.LAUNCHER))
self.assertIn("yourself", said)
self.assertIn(why, said)
def test_runs_the_preflight_only_where_the_session_is_not_open(self):
with tempfile.TemporaryDirectory() as home:
opened = session.session_named("A proj build-release", pathlib.Path(home, "projects"))
fresh = FakeEffects(python=[ran("- A fact.\n")])
facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER))
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True))
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text("{}\n")
resumed = FakeEffects()
facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER))
self.assertEqual((resumed.made("python"), facts), ([], ""))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,287 @@
import contextlib
import dataclasses
import io
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from loop_effects.doubles import assistant, FakeEffects
from build_release.loop import chunk_windows
from project_config.doubles import configured
from failure import Failure
from git_cli import git_repo
from test_env import isolated_env
from build_release.loop import main
from release_plan import next_chunk
from loop_state import paths
from agent_cycle import tmux
from touch_predictions.doubles import todo, plan as touch_plan
def plan_text(*touched):
"""A todo.md of items 1, 2 and on, each predicted to touch the path given for it."""
return todo(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
class ChunkWindows(unittest.TestCase):
def plan(self, *touched):
"""A plan of items 1, 2 and on, each predicted to touch the path given for it."""
items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
return next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="")
def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self):
# Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it.
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"])
def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(self):
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), [])
def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2))
def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2))
def test_leaves_no_room_where_more_chunks_run_than_the_limit(self):
windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0)
def test_starts_no_item_that_overlaps_a_running_chunks_items(self):
# Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py.
items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`"))
plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="")
self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["item-4"])
# A running chunk's item without a prediction leaves no other item free to start beside it.
unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None))
self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), [])
# A held item that left the plan, as once it merged, overlaps nothing.
self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["item-2", "item-4"])
def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self):
none = next_chunk.NoItem("release 1.0.0 has no items")
self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"])
self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), [])
def test_names_a_window_for_its_item_and_reads_the_item_back(self):
self.assertEqual(chunk_windows.window_name(372), "item-372")
self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None])
# Only ASCII digits name an item, as window_name writes them.
self.assertIsNone(chunk_windows.item_of("item-\u0663"))
def test_starts_only_the_next_item_where_the_touch_predictions_cannot_be_read(self):
items = touch_plan((1, "1.0.0", "", "- a.py"), (2, "1.0.0", "", "- `c.py`"))
self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=items, first=items[0], text="", branch_template=""), [], set(), 3), ["item-1"])
def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self):
with tempfile.TemporaryDirectory() as temp:
transcripts = pathlib.Path(temp)
folder = transcripts / "-r"
folder.mkdir()
# A folder in place of the transcript file, so reading it fails.
(folder / f"{chunk_windows.chunk_session('proj', 'item-7', transcripts).id}.jsonl").mkdir()
self.assertEqual(chunk_windows.held_items(["item-7"], "proj", transcripts), {7})
def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self):
with tempfile.TemporaryDirectory() as temp:
home = pathlib.Path(temp)
held = paths.paths_from(home)
folder = held.claude_code_transcripts / "-r"
folder.mkdir(parents=True)
lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})]
(folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
# Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item.
fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n")
self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11])
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
class StartChunks(unittest.TestCase):
"""start_chunks: the windows a loop opens for the chunks that may start now."""
LAUNCHER = pathlib.Path("/b/build-release")
def setUp(self):
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.root = pathlib.Path(made.name, "r")
self.home = configured(self, self.root).parents[1]
self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-")
# Items 1 and 2 overlap, so 2 waits; 3 runs beside 1.
self.plan = plan_text("a.py", "a.py", "c.py")
def limit(self, chunks):
config = self.home / ".claude-projects" / self.root.name / "config.toml"
config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n")
def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None):
"""start_chunks' answer, for a session whose @loop-root names owner, by default this checkout."""
fake.owner = str(self.root) if owner is None else owner
run = main.LoopRun(0, str(self.root), "ship it", "", chunk=chunk)
ran = []
effects = dataclasses.replace(fake.effects(), git=self.git_reading(self.plan if plan is None else plan, ran))
with contextlib.redirect_stderr(io.StringIO()) as said:
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects)
self.said = said.getvalue()
fetches = [args for args in ran if args[0] == "fetch"]
self.planned = len(fetches)
self.assertIn(fetches, ([], [["fetch", "--quiet", "origin"]]))
return started
def git_reading(self, plan, ran):
"""A git that notes each call in ran, and reads plan, a todo.md's text, on the checkout's default branch; a Failure answers every call instead, and an error is raised by every call."""
if isinstance(plan, str):
(self.root / "todo.md").write_text(plan)
for command in (["add", "todo.md"], ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "--quiet", "--allow-empty", "-m", "plan"]):
subprocess.run(["git", "-C", str(self.root), *command], check=True, env=isolated_env())
def git(*args, **options):
ran.append(list(args))
if isinstance(plan, BaseException):
raise plan
return plan if isinstance(plan, Failure) else git_repo.git(*args, **options, env=isolated_env())
return git
def starts(self, fake):
"""The window starts of fake's tmux calls, each as (command, window name, what it runs)."""
return [(call[0], call[call.index("-n") + 1], call[call.index("--") + 1:]) for call in fake.tmux_calls if call[0] in ("new-session", "new-window")]
def test_opens_a_window_for_each_chunk_that_may_start_the_first_making_the_session(self):
self.limit(2)
fake = FakeEffects()
self.assertEqual(self.start(fake, env={"BUILD_RELEASE_WORKER_MODEL": "m", "PATH": "/bin"}), ["item-1", "item-3"])
self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])])
first = next(call for call in fake.tmux_calls if call[0] == "new-session")
self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root)))
# Only build-release's own variables are handed on, since a window gets the tmux server's environment.
self.assertEqual([word for word in first if "=" in word], ["BUILD_RELEASE_WORKER_MODEL=m"])
self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
# The session names the checkout whose chunks it runs.
self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls)
def test_refuses_a_session_that_runs_another_checkouts_chunks(self):
for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")):
with self.subTest(owner=owner):
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders"))
self.assertEqual(self.starts(fake), [])
self.assertIn(["show-options", "-qv", "-t", f"={self.session}:", "@loop-root"], fake.tmux_calls)
def test_refuses_a_checkout_do_epic_runs_chunks_in(self):
fake = FakeEffects(windows=f"epic-ABC-12\tABC-34 ?\t0\t@4\t{self.root}\nepic-ABC-12\tABC-35\t0\t@5\t/c/other\nepic-ABC-12\tABC-36\t1\t@6\t{self.root}\nloop-x\titem-1\t0\t@7\t{self.root}\n")
self.assertEqual(self.start(fake), Failure(f"do-epic runs chunks in {self.root}: ABC-34 of epic-ABC-12; build-release doesn't start a chunk there until those chunks finish"))
self.assertEqual(self.starts(fake), [])
def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
self.assertEqual(self.start(FakeEffects(windows="item-5\t0\t@1\n")), ["item-3"])
def test_starts_one_chunk_without_parallel_chunks(self):
fake = FakeEffects()
self.assertEqual(self.start(fake), ["item-1"])
def test_starts_none_and_reads_no_plan_while_the_running_chunks_fill_the_limit(self):
self.limit(2)
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6 ?\t0\t@2\n")
self.assertEqual((self.start(fake), self.planned, self.starts(fake)), ([], 0, []))
# More chunks run than the limit allows, as after it was lowered; a stopped chunk still waits.
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6\t0\t@2\nitem-7\t0\t@3\nitem-8\t1\t@4\nitem-9\t1\t@5\n")
self.assertEqual((self.start(fake), self.planned), ([], 0))
def test_a_finishing_chunks_own_window_counts_as_no_longer_running(self):
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, chunk="item-5"), [])
fake = FakeEffects(windows="item-5\t0\t@1\n")
self.assertEqual(self.start(fake, chunk="item-5", leaving=True), ["item-1"])
# The session exists, since the finishing loop's window is still in it.
self.assertEqual(self.starts(fake)[0][0], "new-window")
def test_the_humans_build_release_starts_a_stopped_chunk_again_first_closing_its_dead_window(self):
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual((self.start(fake), self.planned), (["item-5"], 0))
self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls)
# Its dead window was the session's last, so the session is made again.
self.assertEqual(self.starts(fake)[0][0], "new-session")
self.limit(2)
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake), ["item-5", "item-1"])
def test_a_plan_with_no_item_starts_nothing_beside_a_restarted_chunk(self):
self.limit(2)
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake, plan=plan_text()), ["item-5"])
def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n")
# Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks.
self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"])
self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], [])
fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n")
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=plan_text()), [])
def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self):
fake = FakeEffects()
self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"])
self.assertIn("starting a chunk without a plan item, since the plan cannot be read: no origin/main", self.said)
def test_says_why_a_window_could_not_start(self):
fake = FakeEffects()
fake.tmux = lambda args: subprocess.CompletedProcess(args, 1, "", "no room") if args[0] == "new-session" else FakeEffects.tmux(fake, args)
self.assertEqual(self.start(fake), Failure(f"tmux could not start the window {self.session}:item-1: no room"))
def test_says_why_it_cannot_take_the_lock_on_starting_windows(self):
(self.home / ".local" / "state").mkdir(parents=True)
(self.home / ".local" / "state" / "build-release").write_text("")
started = self.start(FakeEffects())
self.assertIsInstance(started, Failure)
self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason)
def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self):
with self.assertRaisesRegex(OSError, "the plan's disk is gone"):
self.start(FakeEffects(), plan=OSError("the plan's disk is gone"))
def test_a_chunk_reads_the_other_windows_where_it_cannot_take_the_lock(self):
(self.home / ".local" / "state").mkdir(parents=True)
(self.home / ".local" / "state" / "build-release").write_text("")
fake = FakeEffects(windows="item-7\t0\t@1\nitem-9\t1\t@3\n")
self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home), fake.effects()), [9])
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
with tempfile.TemporaryDirectory() as temp:
transcripts = pathlib.Path(temp)
opened = chunk_windows.chunk_session("proj", "item-7", transcripts)
self.assertEqual(opened.name, "A proj build-release item-7")
folder = transcripts / "-r"
folder.mkdir()
lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})]
(folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9})
if __name__ == "__main__":
unittest.main()
+334
View File
@@ -0,0 +1,334 @@
import contextlib
import dataclasses
import io
import json
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from chunk_driver.doubles import a_loop
from build_release.loop import chunk_windows, main, reload, usage
from loop_effects.doubles import CWD, FakeEffects, ran, STAMP
from failure import Failure
from agent_cycle.verdicts import Finished, Unfinished
from build_release.doubles import OPUS_PROJECT
from loop_state import paths
from model_routing.route import Route
from model_routing.ladder import Rung
from claude_code import session
from agent_cycle.stop import Stop
from chunk_driver import this_loop
from agent_cycle import tmux
class LoopRuns(unittest.TestCase):
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", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]):
with self.subTest(handed=handed):
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. Handed: {' '.join(handed)}"))
def test_decodes_every_field_of_the_state_and_its_route(self):
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2)
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)})
def test_rejects_a_field_of_another_type_or_an_unknown_field(self):
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")):
with self.subTest(path=path, wrong=wrong):
handed = json.loads(json.dumps(state))
target = handed
for key in path[:-1]:
target = target[key]
target[path[-1]] = wrong
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
def test_rejects_a_state_or_rung_missing_a_required_field(self):
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"))))
for path in (("cycle_number",), ("root",), ("task",), ("unfinished_evidence",), ("route", "rung"), ("route", "rung", "model")):
with self.subTest(path=path):
handed = json.loads(json.dumps(state))
target = handed
for key in path[:-1]:
target = target[key]
del target[path[-1]]
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
def test_decodes_a_rung_without_an_effort(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("some-model")))
self.assertEqual(reload.decode_handed(json.dumps({**dataclasses.asdict(state), "route": {"rung": {"model": "some-model"}}})), state)
def test_rejects_text_that_is_not_json(self):
self.assertIsNone(reload.decode_handed("not json"))
def test_decodes_a_route_inside_the_state_or_none(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
unrouted = dataclasses.replace(state, route=None)
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted))), unrouted)
handed = dataclasses.asdict(state)
handed["route"]["rung"]["effort"] = 1
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
del handed["route"]["rung"]
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
off_scale = dataclasses.asdict(state)
off_scale["route"]["likelihood"] = 9
self.assertIsNone(reload.decode_handed(json.dumps(off_scale)))
older = dataclasses.asdict(state)
del older["route"]["escape_and_impact_taken_in"]
self.assertEqual(reload.decode_handed(json.dumps(older)), state)
taken = dataclasses.replace(state, route=dataclasses.replace(state.route, escape_and_impact_taken_in=7))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(taken))), taken)
for taken_in in (9, 5):
with self.subTest(taken_in=taken_in):
handed = dataclasses.asdict(state)
handed["route"]["escape_and_impact_taken_in"] = taken_in
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self):
self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""})), main.LoopRun(3, "/r", "do it", ""))
def test_drops_the_items_taken_in_that_a_loop_started_before_0_11_0_hands_on(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state)
def test_drops_the_slot_that_a_loop_started_before_chunks_ran_in_windows_hands_on(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(reload.decode_handed(json.dumps({key: value for key, value in dataclasses.asdict(state).items() if key != "chunk"} | {"slot": 1})), state)
def test_stops_when_the_reload_cannot_start_python(self):
with tempfile.TemporaryDirectory() as root:
launcher = pathlib.Path(root, "build-release")
launcher.write_text("")
fake = FakeEffects(python=[ran()])
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload build-release: No such file or directory; rerun build-release <task>"))
def steps(start_chunks, **others):
"""The steps of a loop that starts chunks through start_chunks, and takes each other step through the double given for it, else fails."""
def unused(*args):
raise AssertionError(args)
return main.Steps(**{"fingerprint": unused, "exec_if_edited": unused, "next_cycle": unused, "run_cycle": unused, "closed_cycle": unused, "check_routing": unused, **others}, start_chunks=start_chunks)
class WindowStarts(unittest.TestCase):
"""The build-release the human runs, which starts the windows, and the stop of a window's loop whose chunk finished."""
HOME = pathlib.Path("/h")
def run_loop(self, argv, fake, env=None, started=("item-3", "item-4")):
"""run_loop's stop and what it said on stdout, with start_chunks answering `started`; self.asked holds what start_chunks was asked."""
self.asked = []
def start(*args):
self.asked.append(args[:2])
return list(started) if isinstance(started, tuple) else started
with contextlib.redirect_stdout(io.StringIO()) as said:
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), CWD, fake.effects(), steps(start))
return stop, said.getvalue()
def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self):
fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c")
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), ""))
self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], []))
def test_prints_the_help_without_tmux(self):
fake = FakeEffects(tmux_version="")
self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP))
self.assertEqual(fake.tmux_calls, [])
def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self):
for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])):
with self.subTest(shown=shown):
fake = FakeEffects(git=["/r\n"])
stop, said = self.run_loop(["do", "it"], fake, env)
self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n"))
self.assertEqual(fake.tmux_calls, [["-V"], shown])
self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)])
def test_hands_the_window_starts_its_paths_environment_launcher_and_effects(self):
fake = FakeEffects(git=["/r\n"], on_terminal=False)
effects, env, launcher = fake.effects(), {"BUILD_RELEASE_X": "1"}, pathlib.Path("/b/build-release")
asked = []
with contextlib.redirect_stdout(io.StringIO()):
main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, steps(lambda *args: asked.append(args) or ["item-3"]))
self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects)])
def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self):
fake = FakeEffects(git=["/r\n"])
effects, env = fake.effects(), {"TMUX_PANE": "%4"}
launcher = pathlib.Path("/b/build-release")
cycle = unittest.mock.Mock(project=OPUS_PROJECT)
unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished))
closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")]
concluded, cycles, started = [unfinished, finished], [], []
taken = steps(lambda *args: started.append(args) or [], fingerprint=lambda launcher: "", exec_if_edited=lambda *args: None, next_cycle=lambda *args: cycles.append(args) or cycle,
run_cycle=lambda cycle: concluded.pop(0), closed_cycle=lambda *args: closed.pop(0), check_routing=lambda *args: None)
with contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, taken)
loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME), env=env, launcher=launcher, effects=effects)
self.assertEqual(stop, Stop(0, ""))
self.assertEqual(cycles, [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
self.assertEqual(started, [(main.LoopRun(2, "/r", "do it", "", chunk="item-3"), True, loop.paths, env, launcher, effects)])
def window_loop(self, cycles, env, **doubles):
"""run_loop's stop for item-3's window loop, and each step it took with what it handed that step. Each step answers as its double in `doubles` does, else as a cycle without a stop: next_cycle answers the next of `cycles`, run_cycle an unfinished verdict, and closed_cycle the run with one more unfinished verdict."""
fake, calls, cycles = FakeEffects(git=["/r\n"]), [], list(cycles)
effects, launcher, home = fake.effects(), pathlib.Path("/b/build-release"), paths.paths_from(self.HOME)
self.unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
answers = {"fingerprint": lambda *args: "print-1", "exec_if_edited": lambda *args: None, "next_cycle": lambda *args: cycles.pop(0), "run_cycle": lambda *args: self.unfinished,
"closed_cycle": lambda run, *args: dataclasses.replace(run, unfinished_run=run.unfinished_run + 1), "check_routing": lambda *args: None, **doubles}
def step(name):
return lambda *args: calls.append((name, *args)) or answers[name](*args)
stop = main.run_loop(["--chunk", "item-3", "do it"], env, home, launcher, CWD, effects, steps(lambda *args: self.fail(args), **{name: step(name) for name in answers}))
self.loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=home, env=env, launcher=launcher, effects=effects)
return stop, calls
def test_a_window_loop_hands_each_step_of_a_cycle_what_the_steps_before_it_made(self):
env = {"TMUX_PANE": "%4", "BUILD_RELEASE_TRANSCRIPTS": "/t"}
on_ladder = unittest.mock.Mock(task="the cycle's task", project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r"))
off_ladder = unittest.mock.Mock(task="the cycle's task", project=None, project_archive=pathlib.Path("/t/r"), route=unittest.mock.Mock(rung=Rung("my-model")))
stop, calls = self.window_loop([on_ladder, off_ladder, Stop(2, "the human is needed")], env)
self.assertEqual(stop, Stop(2, "the human is needed"))
before, first, second, third = (main.LoopRun(number, "/r", "do it", "", unfinished_run=max(number - 1, 0), chunk="item-3") for number in range(4))
self.assertEqual(calls, [
("fingerprint", pathlib.Path("/b/build-release")),
("exec_if_edited", self.loop, "print-1", before),
("next_cycle", first, self.loop),
("run_cycle", on_ladder),
("closed_cycle", first, "the cycle's task", OPUS_PROJECT, self.unfinished, pathlib.Path("/t/r"), "build-release", self.loop),
("check_routing", pathlib.Path("/t"), Rung("claude-opus-5-5", "medium"), self.loop),
("exec_if_edited", self.loop, "print-1", dataclasses.replace(first, unfinished_run=1)),
("next_cycle", second, self.loop),
("run_cycle", off_ladder),
("closed_cycle", second, "the cycle's task", None, self.unfinished, pathlib.Path("/t/r"), "build-release", self.loop),
("check_routing", pathlib.Path("/t"), Rung("my-model"), self.loop),
("exec_if_edited", self.loop, "print-1", dataclasses.replace(second, unfinished_run=2)),
("next_cycle", third, self.loop),
])
def test_a_window_loop_stops_with_the_stop_of_the_step_that_made_one(self):
cycle = unittest.mock.Mock(project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r"))
for name, taken in (("exec_if_edited", 2), ("run_cycle", 4), ("closed_cycle", 5), ("check_routing", 6)):
with self.subTest(step=name):
stop, calls = self.window_loop([cycle], {"TMUX_PANE": "%4"}, **{name: lambda *args: Stop(1, f"{name} stopped")})
self.assertEqual((stop, len(calls), calls[-1][0]), (Stop(1, f"{name} stopped"), taken, name))
def test_a_window_loop_given_no_task_prints_the_help(self):
self.assertEqual(main.loop_run_from(["--chunk", "item-3"], CWD, FakeEffects(git=["/r\n"]).effects()), Stop(1, usage.HELP))
def test_a_window_loop_outside_a_checkout_stops(self):
self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop)
def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now, so `do it` started in no new window\n")
def test_off_a_terminal_it_prints_how_to_attach(self):
fake = FakeEffects(git=["/r\n"], on_terminal=False)
stop, said = self.run_loop(["do it"], fake)
self.assertEqual(stop, Stop(0, ""))
self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said)
self.assertEqual(fake.tmux_calls, [["-V"]])
def test_stops_where_no_chunk_could_start(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan"))
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=chunk_windows.AwaitedMerges("#7 awaits a merge."))[0], Stop(0, "#7 awaits a merge."), "nothing failed, so the stop exits 0")
def test_stops_where_tmux_cannot_show_the_session(self):
fake = FakeEffects(git=["/r\n"])
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
with contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), CWD, effects, steps(lambda *args: ["item-3"]))
self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session"))
def test_a_window_loop_outside_tmux_stops(self):
fake = FakeEffects(git=["/r\n"])
self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how build-release starts itself in a tmux window; run build-release <task>"))
self.assertEqual(self.asked, [])
def test_reads_the_chunk_a_window_loop_is_started_with(self):
self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3"))
self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", ""))
def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self):
loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7")
for started, said, stop in ((["item-9", "item-12"], "the chunk finished; started item-9, item-12", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")),
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan")),
(chunk_windows.AwaitedMerges("#7 awaits a merge."), "", Stop(0, "the chunk finished; #7 awaits a merge."))):
with self.subTest(started=started), contextlib.redirect_stdout(io.StringIO()) as printed:
loop, asked = a_loop(FakeEffects().effects(), env={"BUILD_RELEASE_X": "1"}), []
self.assertEqual(main.handed_on(loop_run, loop, lambda *args: asked.append(args) or started), stop)
self.assertEqual(printed.getvalue(), f"{STAMP} {said}\n" if said else "")
self.assertEqual(asked, [(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)])
class StopDms(unittest.TestCase):
def run_main(self, argv, fake):
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "build-release"), CWD, fake.effects())
return code, said.getvalue()
def exit_code(self, run, fake):
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
code = main.exit_code(run, CWD, fake.effects())
return code, said.getvalue()
def raising(self, error):
raise error
def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self):
fake = FakeEffects()
self.assertEqual(self.exit_code(lambda: Stop(2, "the human is needed to look at the chunk, but it stayed unfinished"), fake)[0], 2)
self.assertEqual(fake.dms, [f"build-release in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
def test_skips_the_dm_of_a_stop_without_a_reason_as_once_the_windows_started(self):
fake = FakeEffects()
self.assertEqual(self.exit_code(lambda: Stop(0, ""), fake), (0, ""))
self.assertEqual(fake.dms, [])
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
fake = FakeEffects()
self.assertEqual(self.exit_code(lambda: self.raising(KeyboardInterrupt()), fake)[0], 130)
self.assertEqual(fake.dms, [])
def test_dms_a_crash_before_it_reaches_the_terminal(self):
fake = FakeEffects()
with self.assertRaises(RuntimeError):
self.exit_code(lambda: self.raising(RuntimeError("boom")), fake)
self.assertEqual(fake.dms, [f"build-release in {CWD} crashed: RuntimeError('boom')"])
def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self):
fake = FakeEffects()
code, said = self.run_main([main.RELOAD_FLAG, "3"], fake)
self.assertEqual(code, 1)
self.assertEqual(fake.dms, [f"build-release in {CWD} stopped: the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. Handed: 3"])
def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self):
fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")])
self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n"))
def test_skips_the_dm_where_it_prints_its_help(self):
for argv, code in (([], 1), (["--help"], 0)):
with self.subTest(argv=argv):
fake = FakeEffects()
self.assertEqual(self.run_main(argv, fake)[0], code)
self.assertEqual(fake.dms, [])
class OwnLadder(unittest.TestCase):
def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self):
file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json")
self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.")
self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,155 @@
import contextlib
import io
import json
import pathlib
import shutil
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from chunk_driver.doubles import a_loop
from routing_figures import archive, state
from test_env import assert_not_root
from routing_figures.calls import Call
from failure import Failure
from loop_effects.doubles import FakeEffects, NOW
from transcript_archive import outcomes
from loop_state import paths
from build_release.loop import routing_check
from model_routing.ladder import Rung
from claude_code import session
from agent_cycle.stop import Stop
from text_files.utc_stamp import utc
# How git answers in a project's checkout it cannot read, such as one that is gone.
UNREAD = Failure("not a git repository")
class RoutingCheck(unittest.TestCase):
def setUp(self):
self.home = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.home)
self.root = self.home / "archive"
self.paths = paths.paths_from(self.home)
self.session = session.session_named("A log build-release", self.paths.claude_code_transcripts)
def loop(self, fake):
"""The loop in /code/log."""
return a_loop(fake.effects(), root="/code/log", session=self.session, paths=self.paths)
def chunks(self, count, verdicts, project="log"):
"""count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches."""
for number in range(count):
folder = self.root / project / f"c{number}"
subagents = folder / "session" / "s" / "subagents"
subagents.mkdir(parents=True)
kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e', 'j', '')}\n" for verdict in range(verdicts - 1))
(folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}2026-10-14T11:00:00Z {outcomes.finished('w', 'm', 'j')}\n")
launch = {"type": "assistant", "timestamp": "2026-10-14T09:00:00Z", "message": {"id": "m", "content": [{"type": "tool_use", "id": "a", "name": "Agent", "input": {"subagent_type": "Explore"}}]}}
report = {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "a", "content": "long report"}]}}
(folder / "copy.jsonl").write_text(json.dumps(launch) + "\n" + json.dumps(report) + "\n")
(subagents / "agent-a.jsonl").write_text("")
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"}))
def check(self, fake):
"""What check_routing returns and says for a loop in /code/log."""
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.loop(fake))
return stop, said.getvalue()
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
self.chunks(5, 3)
self.assertEqual(self.check(FakeEffects()), (None, ""))
self.assertFalse((self.root / "routing-figures.md").exists())
self.chunks(6, 1, "other")
self.assertEqual(self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 6))[0], None)
self.assertIn("at cycle 21 across", (self.root / "routing-figures.md").read_text())
def test_reads_each_projects_history_through_the_loops_git_and_names_each_it_cannot_read(self):
self.chunks(5, 4)
fake = FakeEffects(on_terminal=False, git=[UNREAD] * 3)
self.check(fake)
located = ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"]
self.assertEqual(fake.made("git"), [located, located, ["remote"]], "the config is located for its title templates, then for where it keeps the plan")
self.assertIn("## Default branches unread\n\n- log: not a git repository\n", (self.root / "routing-figures.md").read_text())
def test_hands_the_terminal_over_once_for_each_new_call(self):
self.chunks(5, 4)
fake = FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3)
stop, said = self.check(fake)
self.assertIsNone(stop)
call = "Explore subagents' reports took more of the worker's context than their searches would have."
self.assertIn(f"- {call}", said)
self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text())
((args),) = fake.made("claude_on_terminal")
self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"])
self.assertIn(f"don't change anything until they answer:\n- {call}", args[6])
self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}])
self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release")
self.assertIn("Record what they decide in this checkout, the development clone", args[6])
self.assertIsNone(state.mark_measured(self.root, 0))
self.assertEqual(self.check(FakeEffects(git=[UNREAD] * 3))[0], None)
self.assertNotIn(call, self.check(FakeEffects())[1])
def test_stamps_the_figures_and_the_calls_raised_when_it_measures(self):
self.chunks(5, 4)
(self.root / "routing-calls-raised.md").write_text("# Routing calls raised\n\n- 2026-10-14T10:02:00Z Reset\n")
self.check(FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3))
figures = (self.root / "routing-figures.md").read_text()
self.assertIn(f"Measured {utc(NOW)}, at cycle 20 across", figures)
self.assertIn("that finished after the reset of 2026-10-14T10:02:00Z", figures)
self.assertIn(f"- {utc(NOW)} Explore subagents'", (self.root / "routing-calls-raised.md").read_text())
def test_says_a_figure_it_cannot_read(self):
self.chunks(5, 4)
(self.root / "routing-state.json").mkdir()
self.assertIn("routing figures: could not read", self.check(FakeEffects())[1])
def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self):
self.chunks(5, 4)
stop, said = self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3))
self.assertIsNone(stop)
self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said)
self.assertIsNone(state.mark_measured(self.root, 0))
self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3))[1])
def test_leaves_the_measuring_to_a_loop_holding_the_lock(self):
self.chunks(5, 4)
with archive.locked(self.root):
self.assertEqual(self.check(FakeEffects()), (None, ""))
def test_stops_when_claude_cannot_start_for_the_calls(self):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD] * 3))
self.assertEqual(stop, Stop(1, f"could not start claude for the routing calls in {self.home / 'code' / 'claude-config'}, the setup's development clone: No such file or directory"))
def test_says_a_figure_it_cannot_write_and_goes_on(self):
assert_not_root(self)
self.chunks(5, 4)
(self.root / "routing-figures.lock").touch()
self.root.chmod(0o555)
self.addCleanup(self.root.chmod, 0o755)
stop, said = self.check(FakeEffects(git=[UNREAD] * 3))
self.assertIsNone(stop)
self.assertIn("routing figures: could not write", said)
def test_puts_every_new_call_to_the_human_and_says_one_it_cannot_keep(self):
new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))]
fake = FakeEffects(on_terminal_claude=[0])
self.root.mkdir()
fake.replace_file = lambda path, data: Failure("full")
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertIsNone(routing_check.raise_calls(self.root, new, Rung("m", "high"), self.loop(fake)))
((args),) = fake.made("claude_on_terminal")
self.assertIn(f"don't change anything until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
self.assertIn(f"routing figures: could not write {self.root / state.RAISED}: full", said.getvalue())
[sent] = fake.dms
self.assertTrue(sent.startswith(f"build-release in {self.loop(fake).root} asks:\n\nbuild-release's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent)
if __name__ == "__main__":
unittest.main()
+123
View File
@@ -0,0 +1,123 @@
import ast
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from claude_code.output_limits import BASH_CEILING_CHARACTERS
from chunk_driver import chunk_run
from agent_cycle import judge, retry, states, worker
from build_release.loop import main, usage
from loop_effects.effects import PYTHON_TIMEOUT
from chunk_driver.project import records
from claude_code import reply
from routing_figures import state
class HelpLimits(unittest.TestCase):
def test_help_wraps_at_100_columns(self):
self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], [])
def test_help_states_the_limits_the_code_holds(self):
said = " ".join(usage.HELP.split())
self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said)
# The retry messages say these limits in words too.
self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60))
self.assertIn("fails three times running, retried a minute apart", said)
self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said)
self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said)
self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said)
self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said)
self.assertIn(f"{BASH_CEILING_CHARACTERS:,} characters", said)
self.assertIn(f"unfinished {chunk_run.UNFINISHED_LIMIT} cycles running", said)
self.assertIn(f"rerun to give it {chunk_run.UNFINISHED_LIMIT} more", said)
class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises"
models_ = "the models file cannot be read or written"
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], f"{records.HUMAN_RULE_NAMES[1]}*.md", records.HUMAN_RULE_NAMES[2])
unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
clauses = [
("agent_cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
("agent_cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
("agent_cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
("agent_cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
("agent_cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
("agent_cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
("agent_cycle/run.py", "rule", "1", "entries.reason", read),
("agent_cycle/run.py", "rule", "1", "annotation.reason", read),
("agent_cycle/run.py", "rule", "1", "failure.reason", read),
("agent_cycle/run.py", "keep_rejection", "1", "unkept.reason", read),
("agent_cycle/run.py", "close", "1", "annotation.reason", read),
("agent_cycle/run.py", "close", "1", "failure.reason", read),
("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("chunk_driver/chunk_run.py", "closed_cycle", "1", "failure.reason", read),
("chunk_driver/cycle_start.py", "project_routing", "1", "ladder_file.reason", premises_),
("chunk_driver/cycle_start.py", "routing_on", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "failure.reason", models_),
("build_release/loop/checkout.py", "checkout_root", "1", "found.reason", git),
("build_release/loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("build_release/loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how build-release starts itself", "--chunk is given outside a tmux window"),
("build_release/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("build_release/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
("build_release/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
("build_release/loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("build_release/loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("build_release/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
("build_release/loop/main.py", "loop_run_from", "1", 'f"the edited build-release cannot read the state', "a reload cannot read the state the running script handed it"),
("build_release/loop/reload.py", "exec_if_edited", "1", "f'could not reload build-release:", "python cannot start for a reload"),
("build_release/loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"),
]
root = pathlib.Path(main.__file__).parents[2]
found = []
for path in sorted(path for package in ("agent_cycle", "chunk_driver", "build_release") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")):
functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)]
stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)]
self.assertEqual(len(found), len(clauses), found)
for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses):
with self.subTest(path=path, function=function):
self.assertEqual((path, function, code), (want_path, want_function, want_code))
self.assertTrue(reason.startswith(reason_start), reason)
help_exit_1 = " ".join(usage.HELP[usage.HELP.index("Exit 1"):usage.HELP.index("Exit 2")].split())
self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], [])
class JudgeFailures(unittest.TestCase):
def test_every_failed_judge_run_has_its_clause_in_help(self):
started, exited, unparsed = "claude cannot start", "exits non-zero", "prints no json reply"
field, unasked = "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
# Every Failure the judge's run returns, in source order of judge.py, then of the claude run it calls: function, start of reason, its --help clause.
clauses = [
("verdict_from", "'the judge returned no reply'", field),
("verdict_from", 'f"the judge\'s reply has no {name}', field),
("verdict_from", "'the judge interrupted without a question'", unasked),
("verdict_from", "'the judge quoted an answer without a question'", unasked),
("run_judge", "verdict.reason", field),
("run_judge", "checked.reason", "quotes a passage that neither the task nor the transcript holds"),
("misquoted_evidence", "f'the judge quoted {verdict.evidence!r}, which is not in the task or the transcript", "quotes a passage that neither the task nor the transcript holds"),
("judge_prompt", "f\"the premises, the records, the task and the judge's rules leave", f"leave room for less than the last {judge.TRANSCRIPT_FLOOR:,} characters of the transcript, or all of a shorter one"),
("claude_reply", "f'could not start claude:", started),
("claude_reply", "proc.stderr.strip() or f'{who} exited", exited),
("claude_reply", 'f"{who} printed no json reply', unparsed),
]
found = []
for module in (judge, reply):
functions = [node for node in ast.walk(ast.parse(pathlib.Path(module.__file__).read_text())) if isinstance(node, ast.FunctionDef)]
found += sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) in ("Failure", "Rejected"))
self.assertEqual(len(found), len(clauses), found)
for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses):
with self.subTest(function=function):
self.assertEqual(function, want_function)
self.assertTrue(reason.startswith(reason_start), reason)
judge_clause = " ".join(usage.HELP[usage.HELP.index("a judge when"):usage.HELP.index("A usage limit")].split())
self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], [])
if __name__ == "__main__":
unittest.main()
+208
View File
@@ -0,0 +1,208 @@
HELP = """Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
usage: build-release <task>
Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the
premises. The goals file is the one the project's config, ~/.claude-projects/<key>/config.toml, sets
as goals-and-audience: a file, or a Jira epic's description. `project-config goals-and-audience`
prints where it is. 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 (the setup's CLAUDE.md →
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
chunk's plan 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 setup's
CLAUDE.md and rules/*.md, then the .md files in the folder of review standards
the project's config sets, 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, the plan or a 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, build-release 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. A question the human answered earlier in the chunk goes back to the
worker with that answer, unless the question quotes the words of the answer that leave it open. 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,
either of which stops that one chunk.
Words: the setup's CLAUDE.md → "Vocabulary".
build-release needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in its
own window of one tmux session per project, named loop-<key>, such as loop-claude-config. <key> is
the checkout's path relative to ~/code, or to / outside it, with a dash for each character other
than a letter, a digit, _ or -. The tmux session's @loop-root option names its checkout, and a
checkout whose key maps to a tmux session another checkout runs is refused. build-release <task>
starts the chunks that may start now, then attaches to the tmux session, or switches to it inside
tmux; detaching leaves the chunks running. Off a terminal it prints the command that attaches. Where
no chunk may start, it says so, and the task starts in no new window. At most parallel-chunks chunks
run at once, a whole number the project's config sets, 1 by default. The first starts from the
plan's next item, and each other from an item whose `Touches:` prediction overlaps neither one
before it nor an item another chunk holds (touch-predictions --help). A window is named for the item
its chunk starts from, as item-372; a chunk without a plan item, such as planning a release or its
release review, runs alone in the window no-item.
Each window runs a build-release for that one chunk, started with --chunk <window>, which nobody
types. As a chunk finishes, its loop starts each chunk that may start then, with the task it ran
itself, and exits, which closes its window. A loop that stops, by Ctrl-C, an exit below or a
failure, keeps its window, with its last lines, and its chunk keeps its items; the next build-release
<task> starts it again before any other. To stop every chunk, press Ctrl-C in each window. A chunk's
claude session is named "A <key> build-release <window>", so a rerun resumes a chunk left open, and is
deleted when the chunk finishes. A fresh worker is told the items the project's other chunks hold,
running or stopped: each one's own and those on its latest `Chunk items:` line, and leaves them out.
A question only the human can answer is an interrupt (bin/agent_cycle/interrupt.py).
build-release prints the question in the chunk's window and rings its bell. Until it is answered the
window's name ends in " ?", as in "item-372 ?", which tmux's status bar shows. The human answers it
there:
- 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 claude session with `claude --resume` on the terminal, to read the diff
or discuss first. Once that claude exits, the judge rules on what was typed there.
- Enter alone: stops the loop.
A release ready to cut opens that claude session on the terminal at once, since only the human may
cut it. While claude is open, Ctrl-C reaches it alone, and the loop goes on. Where the project's
config sets notifier, build-release also sends the human each question, naming its tmux window as
<session>:<window>, each release ready to cut and each stop as a DM, as bin/notify sends it. Four
stops are left out: Ctrl-C, printing this help, the build-release that started the windows once it
attaches or prints how to, and a loop whose chunk finished once it started the next chunks. A DM
that fails is said on stderr, and the loop goes on. Where no answer has come 10 minutes before the
worker's hour-long prompt cache expires, and the worker's context holds at least 60k tokens,
build-release compacts the worker's session with `claude -p /compact` and keeps waiting, so the resume
doesn't write the whole context again.
As a chunk starts, before it is routed, build-release runs bin/chunk-preflight --worktree, adding
--item <ID> in a window named for an item, and quotes what it prints in the first prompt
(preflight_facts in bin/build_release/chunk/fresh_prompt.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.
At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the claude session's
transcript is copied into a folder per chunk under $BUILD_RELEASE_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.
A worker's claude can print its final result and then keep waiting on a background shell that
never ends. Every 5 minutes without output from that claude after its final result, build-release
stops each of its shells and what runs below them, unless a shell has written output in the last 3
minutes, runs chunk-pr or run-heavy, or holds a heavy slot. It prints each stop and appends it, with
the UTC time, to lingering-workers.md at the project's folder in that archive
(bin/agent_cycle/lingering_workers.py).
A worker can also stall before its result, on a command that hangs. Every 5 minutes without output
from its claude, build-release looks for a shell that may be stuck: one that used no CPU since the
last check and wrote no output for 3 minutes, or one that has run over 4 hours. A shell that runs
chunk-pr or run-heavy doesn't count, but one that holds a heavy slot can. Where such a shell is
found, a headless claude on the project's rung reads every shell's command, processes and output.
The headless claude judges the worker working, waiting on a person or stuck, and names the process
the worker waits on. It judges a shell again only after the shell used CPU and went idle once more.
build-release prints the verdict and the shells that showed a sign, and appends them to
stuck-workers.md beside lingering-workers.md. It doesn't kill anything yet
(bin/agent_cycle/stuck_workers.py).
Before each worker starts, build-release 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/agent_cycle/worker.py), so each
compacts its context at about 170k tokens. They also save a Bash result of more than 6,000
characters to a file and see its path and the first 2,000 characters (BASH_MAX_OUTPUT_LENGTH,
bin/claude_code/output_limits.py).
Every claude build-release 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. BUILD_RELEASE_JUDGE_MODEL overrides
the model for the judge, BUILD_RELEASE_WORKER_MODEL for the worker and the session /talk opens; with
both set, nothing is asked.
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
project's model is on it, the worker and the session /talk opens run on
the rung that the chunk's plan 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, when the
worker names on its `Chunk items:` line an item that picks a higher rung, 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/agent_cycle/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/build_release/chunk/fresh_prompt.py, bin/chunk_driver/prompts.py and
bin/agent_cycle/worker_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 plan or an archive that cannot be read or parsed is said on stderr, and the
chunk is routed without it.
The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh
or max:
[
{"model": "claude-opus-5-5", "effort": "medium"},
{"model": "claude-fable-5-2", "effort": "low"}
]
It holds one model of each family, such as opus, since the Agent tool launches a subagent or a
review by its family's name. This setup ships one, bin/model_routing/routing-ladder.json. A project
that keeps a routing-ladder.json in its config's folder, ~/.claude-projects/<key>/, runs on that
ladder instead, whole: write there every rung the project may run on. build-release reads the
project's ladder as each cycle starts, says on stderr where the project runs on its own, and never
commits the file. subagent-rung and rule-hook read the same ladder; the routing figures,
judge-replay and review-replay, which span every project, read the shipped one.
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/). 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. Once that claude ends, the calls are listed in
routing-calls-raised.md beside the figures, kept in routing-state.json, 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/build-release or any bin/**/*.py takes effect at the next cycle boundary, once
build-release --help succeeds: the loop reloads into the edited script.
Under merge = "human", where no chunk runs and every item left awaits a person's merge, build-release
doesn't start a chunk: it names those pull requests, in a DM too, and exits 0. Its window closes,
so the next build-release <task> reads the plan again.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- tmux is missing or older than 3.2
- --chunk is given outside a tmux window
- a chunk's window cannot be started, as when the project's config cannot be read, or the tmux
session runs another checkout's chunks
- the tmux session cannot be put on the terminal
- the goals file, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
the project's review standards where they exist, cannot be read or is not UTF-8
- no config names the checkout, its config cannot be read, or the goals file holds no premises
- the models file cannot be read or written
- the project's routing ladder cannot be read or holds a fault
- 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 the premises, the records, the task and the judge's rules leave room for less than
the last 50,000 characters of the transcript, or all of a shorter one, when claude cannot start,
exits non-zero or prints no json reply, or when its reply misses or mistypes a field, interrupts
or quotes an answer without a question, or quotes a passage that neither the task nor the
transcript holds, where each fragment of an elided quote must appear in order, in the task then
the transcript.
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, or for a release ready to cut, ends without
anything typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning build-release <task> starts the chunks that may start, a stopped one first, and each
resumes its claude session where it is open."""