import dataclasses import hashlib import json import pathlib import sys import typing from loop_claude.effects import Effects from loop_claude.stop import Stop RELOAD_FLAG = "--reloaded" T = typing.TypeVar("T") # A field change stops a running loop at its next reload: the new script rejects the old fields. @dataclasses.dataclass(frozen=True) class LoopRun: """What a reload hands the edited script, as JSON on argv.""" cycle_number: int remaining: str root: str task: str def decode_handed(handed: str, kind: type[T]) -> T | None: try: fields = json.loads(handed) except ValueError: return None shape = typing.get_type_hints(kind) if not isinstance(fields, dict) or fields.keys() != shape.keys(): return None if any(type(fields[name]) is not type_ for name, type_ in shape.items()): return None return kind(**fields) 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 try: trial = effects.python([str(launcher), "--help"]) if trial.returncode != 0: print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) return None 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