import dataclasses import hashlib import json import pathlib import sys import typing from loop_claude.effects import Effects, say from model_routing.route import Route from model_routing.ladder import Rung from loop_claude.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 IDs of the items the last unfinished verdict found the chunk takes, which loop-inbox lists until the next ruling. items_taken_in: tuple[int, ...] = () 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 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_ids(value: object) -> tuple[int, ...]: if not isinstance(value, list): raise Unreadable return tuple(exactly(int)(each) for each in value) def decoded_rung(value: object) -> Rung: return Rung(**decoded_fields(value, {"model": exactly(str), "effort": exactly(str)}, "model")) def decoded_route(value: object) -> Route | None: """The Route the JSON holds; None for null, or for a route holding a key Route.RETIRED names, so the chunk routes afresh.""" if value is None or (isinstance(value, dict) and value.keys() & Route.RETIRED): return None fields = decoded_fields(value, ROUTE_FIELDS, "rung") if not Route.fits(fields): raise Unreadable return Route(**fields) # One decoder per field of LoopRun and of Route, which tests hold to those dataclasses' 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), "items_taken_in": decoded_ids} ROUTE_FIELDS = {"rung": decoded_rung, **{name: exactly(int) for name in ("item", "likelihood", "escape_and_impact", "unfinished", "escape_and_impact_taken_in", "escalated_at")}} 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(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None: if fingerprint(launcher) == baseline: return None trial = effects.python([str(launcher), "--help"], loop_run.root) if trial.returncode != 0: say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects) return None try: effects.execv(sys.executable, [sys.executable, str(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 ") return None