# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-schemas-from-silently-widening-agent-capability-at-hot-reload-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-schemas-from-silently-widening-agent-capability-at-hot-reload-time.warrant.json
# Markdown SHA-256:   22c25f85d61f2e3b7e4f2aca5f05eb74d70d8814ad15d5b52169e72193ea7d41
# Code AST SHA-256:   267c6367cb4b10747dc2fb1a0d2fe88df5d71a63d80a3f8b87185ee2d498bac2
# Verified Classes:   CapabilityWideningError, ApprovedTool
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityWideningError(RuntimeError):
    """Raised when a hot-reloaded manifest expands the agent's authority."""
    pass


@dataclass(frozen=True)
class ApprovedTool:
    name: str
    content_hash: str
    version_string: str
    args: frozenset[str]
    returns: frozenset[str]
    description: str


def canonical_hash(manifest: dict) -> str:
    blob = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def derive_capability_set(manifest: dict) -> tuple[frozenset[str], frozenset[str]]:
    args = frozenset(manifest.get("input_schema", {}).get("properties", {}).keys())
    returns = frozenset(manifest.get("output_schema", {}).get("properties", {}).keys())
    return args, returns


def admit_on_reload(
    incoming: dict,
    approved: dict[str, ApprovedTool],
) -> ApprovedTool:
    name = incoming["name"]
    h_new = canonical_hash(incoming)
    record = approved.get(name)

    if record is None:
        raise CapabilityWideningError(
            f"tool {name!r} has no approval record; reload cannot self-approve"
        )

    if h_new == record.content_hash:
        if incoming.get("version") != record.version_string:
            raise CapabilityWideningError(
                f"tool {name!r}: hash matches approval but registry version "
                f"{incoming.get('version')!r} != approved {record.version_string!r}; "
                "possible registry substitution"
            )
        return record

    new_args, new_returns = derive_capability_set(incoming)

    widened_args = new_args - record.args
    widened_returns = new_returns - record.returns
    if widened_args or widened_returns:
        raise CapabilityWideningError(
            f"tool {name!r} reload widens authority: "
            f"new_args={sorted(widened_args)} new_returns={sorted(widened_returns)}; "
            "requires re-approval, not refresh"
        )

    if incoming.get("description", "") != record.description:
        raise CapabilityWideningError(
            f"tool {name!r} reload mutates description under unchanged schema; "
            "description is policy input to the planner and requires re-approval"
        )

    raise CapabilityWideningError(
        f"tool {name!r} reload produced unapproved hash {h_new[:12]} with no "
        "widening detected; treat as re-approval event"
    )
