# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-hot-reloads-a-tool-registry-and-a-skill-manifest-s-declared-schema-diverges-from-its-runtime-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-hot-reloads-a-tool-registry-and-a-skill-manifest-s-declared-schema-diverges-from-its-runtime-behavior.warrant.json
# Markdown SHA-256:   799979b0c907af3b0f135c3059a288a98435f84e872ff54ab45ee5343d504612
# Code AST SHA-256:   bd1c031d36e0434b0301b934970def001aefcc512b7fc5208b64816adbab6385
# Verified Classes:   SchemaRuntimeDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaRuntimeDivergence(RuntimeError):
    """Raised when a skill's runtime contract accepts inputs its declared
    manifest schema does not authorize, or when a hot-reload widens a
    write-surface field without re-authorization."""
    pass


WRITE_SURFACE_KEYS = {"path", "url", "source_url", "mode", "fetch_mode", "include"}


def validate_registry_reload(old_manifest: dict, new_manifest: dict, task_token: str) -> None:
    old_props = old_manifest.get("properties", {})
    new_props = new_manifest.get("properties", {})

    for field, spec in new_props.items():
        # Detect constraint widening on write-surface fields.
        if field in WRITE_SURFACE_KEYS or spec.get("additionalProperties") is True:
            old_spec = old_props.get(field, {})
            if spec.get("additionalProperties") is True and old_spec.get("additionalProperties") is not True:
                raise SchemaRuntimeDivergence(
                    f"field '{field}' widened to additionalProperties:true on hot-reload; "
                    f"agent-writable channel into runtime parser is now unbounded"
                )
            if spec.get("type") == "string" and "enum" not in spec and "format" not in spec:
                if old_spec.get("format") or old_spec.get("enum"):
                    raise SchemaRuntimeDivergence(
                        f"field '{field}' lost its closed constraint "
                        f"({old_spec.get('format') or old_spec.get('enum')} -> free string); "
                        f"runtime may interpret agent-authored value as directive"
                    )

    # Any widening requires an explicit re-authorization token bound to the task.
    if _write_surface_widened(old_props, new_props) and not task_token:
        raise SchemaRuntimeDivergence(
            "hot-reload widens write surface without task-bound re-authorization token"
        )


def _write_surface_widened(old_props: dict, new_props: dict) -> bool:
    for field, spec in new_props.items():
        if field not in WRITE_SURFACE_KEYS:
            continue
        old = old_props.get(field, {})
        if spec.get("additionalProperties") is True and old.get("additionalProperties") is not True:
            return True
        if spec.get("type") == "string" and not (spec.get("enum") or spec.get("format")):
            if old.get("enum") or old.get("format"):
                return True
    return False
