import dataclasses import hashlib import json import sys import typing from loop_claude.effects import Effects 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 LoopRun: """One loop-claude run; a reload hands it to the new script as JSON on argv.""" cycle_number: int root: str task: str def decode_handed(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, loop_run, 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