Files
claude-config/bin/loop_claude/loop/reload.py
T
2026-11-18 16:21:35 +01:00

109 lines
5.4 KiB
Python

import dataclasses
import hashlib
import json
import pathlib
import sys
import typing
from loop_claude.loop.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 loop-claude 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 → `loop-claude: 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 loop-claude 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 loop-claude: {failure.strerror}; rerun loop-claude <task>")
return None