import dataclasses import hashlib import json import os import subprocess import sys import typing from loop_claude.outcome 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 LoopState: cycle_number: int root: str task: str def decode_state(handed, 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) -> str: digest = hashlib.sha256() for path in [launcher, *sorted((launcher.parent / "loop_claude").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() def exec_if_edited(launcher, baseline, state) -> Stop | None: if fingerprint(launcher) == baseline: return None try: trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) if trial.returncode != 0: print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) return None os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) except OSError as failure: return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude ") return None