Files
claude-config/bin/loop_claude/loop/reload.py
T

92 lines
3.7 KiB
Python

import dataclasses
import hashlib
import json
import pathlib
import sys
import types
import typing
from loop_claude.effects import Effects
from model_routing.route import Route
from loop_claude.stop import Stop
RELOAD_FLAG = "--reloaded"
T = typing.TypeVar("T")
# 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
# None until the chunk is routed, and where the project's model is off the ladder.
route: Route | None = None
def decode_handed(handed: str, kind: type[T]) -> T | None:
try:
fields = json.loads(handed)
except ValueError:
return None
decoded = decoded_as(fields, kind)
return None if decoded in (REJECTED, RETIRED) else typing.cast(T, decoded)
REJECTED = object()
# A dataclass handed with a field its RETIRED names: where None may stand in for it, it decodes as None.
RETIRED = object()
def decoded_as(value: object, kind: typing.Any) -> typing.Any:
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
if isinstance(kind, types.UnionType):
found = [decoded_as(value, option) for option in typing.get_args(kind)]
fits = [each for each in found if each is not REJECTED and each is not RETIRED]
if fits:
return fits[0]
return None if RETIRED in found and type(None) in typing.get_args(kind) else REJECTED
if isinstance(kind, type) and dataclasses.is_dataclass(kind):
if isinstance(value, dict) and value.keys() & getattr(kind, "RETIRED", frozenset()):
return RETIRED
hints = typing.get_type_hints(kind)
shape = {field.name: hints[field.name] for field in dataclasses.fields(kind)}
# A field with a default may be missing, so a field added since the running script started does not stop the loop.
required = {field.name for field in dataclasses.fields(kind) if field.default is dataclasses.MISSING and field.default_factory is dataclasses.MISSING}
if not isinstance(value, dict) or not required <= value.keys() <= shape.keys():
return REJECTED
fields = {name: decoded_as(field, shape[name]) for name, field in value.items()}
# A dataclass that checks its fields, as Route does, does so in a static method named fits.
if any(field in (REJECTED, RETIRED) for field in fields.values()) or not getattr(kind, "fits", lambda _: True)(fields):
return REJECTED
return kind(**fields)
return value if type(value) is kind else REJECTED
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:
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
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 <task>")
return None