# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-a-tool-after-its-server-hot-reloads-policy-version-skew-across-the-mcp-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-a-tool-after-its-server-hot-reloads-policy-version-skew-across-the-mcp-trust-boundary.warrant.json
# Markdown SHA-256:   2ae1a066b97d124243af4a2448ccdf6e181969e5faf27f89b0c9111f4d25731a
# Code AST SHA-256:   c813fd1d792e0d7fa7bfa64e43e10a46123a7bb976f2d876f21d947eaab978df
# Verified Classes:   AttestationEpochSkew, Attestation, TrustBoundary
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationEpochSkew(RuntimeError):
    """Raised when a tool call would execute under a policy epoch or schema
    that differs from the attestation the client is enforcing."""
    pass


@dataclass(frozen=True)
class Attestation:
    server_id: str
    tool_name: str
    schema_sha256: str
    granted_scopes: frozenset
    egress_ceiling: frozenset
    policy_epoch: int


def schema_hash(tool_def: dict) -> str:
    # Canonicalize: sort keys so cosmetic reordering does not force re-attestation,
    # but any semantic change (new param, changed type, changed default) does.
    import json
    canonical = json.dumps(tool_def, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


class TrustBoundary:
    def __init__(self):
        self._attestations: dict[tuple[str, str], Attestation] = {}

    def attest(self, att: Attestation) -> None:
        self._attestations[(att.server_id, att.tool_name)] = att

    def revoke_server(self, server_id: str) -> None:
        # tools/list_changed => trust-revocation, not cache hint.
        for key in [k for k in self._attestations if k[0] == server_id]:
            del self._attestations[key]

    def authorize_call(self, server_id: str, live_tool_def: dict,
                       server_epoch: int) -> Attestation:
        name = live_tool_def["name"]
        att = self._attestations.get((server_id, name))
        if att is None:
            raise AttestationEpochSkew(
                f"no active attestation for {server_id}/{name}; "
                f"re-attest before serving (fail closed)")
        live_hash = schema_hash(live_tool_def)
        if live_hash != att.schema_sha256:
            raise AttestationEpochSkew(
                f"schema drift on {server_id}/{name}: attested "
                f"{att.schema_sha256[:12]} != live {live_hash[:12]}; "
                f"capability expansion may be unguarded")
        if server_epoch != att.policy_epoch:
            raise AttestationEpochSkew(
                f"epoch skew on {server_id}/{name}: attested "
                f"{att.policy_epoch} != server {server_epoch}")
        return att

    def check_result_epoch(self, att: Attestation, result_epoch: int) -> None:
        # In-flight call dispatched under att.policy_epoch returned under a
        # newer epoch: discard, do not trust the result.
        if result_epoch > att.policy_epoch:
            raise AttestationEpochSkew(
                f"result epoch {result_epoch} exceeds attested "
                f"{att.policy_epoch}; discard and re-attest")
