# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-signed-skill-manifest-whose-capability-set-diverges-from-its-declared-tool-schema-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-signed-skill-manifest-whose-capability-set-diverges-from-its-declared-tool-schema-at-load-time.warrant.json
# Markdown SHA-256:   6ee2e5a4b917a85dcc1564a0f444f036a659b361a4c3c7ec7d8c87be34080945
# Code AST SHA-256:   128eb90410bd6ac0e04bc9e92a78e8d457c0e11a84d00c2e3a0b7587e62b0d6b
# Verified Classes:   SkillBindingError, SignedEnvelope, BoundTool
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class SkillBindingError(RuntimeError):
    """Raised when a signed skill manifest and its bound tool contract diverge."""
    pass


@dataclass(frozen=True)
class SignedEnvelope:
    skill_id: str
    capabilities: frozenset[str]
    schema_digest: str          # digest of the FULLY DEREFERENCED contract
    signature_valid: bool


@dataclass
class BoundTool:
    skill_id: str
    contract: dict[str, Any]
    verified_digest: str
    frozen: bool = False


def _canonical_digest(contract: dict[str, Any]) -> str:
    blob = json.dumps(contract, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def _derive_capability_surface(contract: dict[str, Any]) -> frozenset[str]:
    """Derive the capabilities the schema actually exposes at invocation time."""
    derived: set[str] = set()
    props = contract.get("parameters", {}).get("properties", {})
    if "url" in props:
        derived.add("net:read:https")
    method = props.get("method", {})
    if "POST" in method.get("enum", []):
        derived.add("net:write")
    if "body" in props:
        derived.add("net:write")
    if "headers" in props:
        derived.add("header:inject")
    return frozenset(derived)


def load_and_bind(envelope: SignedEnvelope, contract: dict[str, Any]) -> BoundTool:
    if not envelope.signature_valid:
        raise SkillBindingError(f"{envelope.skill_id}: signature invalid")

    actual = _canonical_digest(contract)
    if actual != envelope.schema_digest:
        # FATAL, never WARN: a mismatch means the executed contract is not the signed one.
        raise SkillBindingError(
            f"{envelope.skill_id}: contract digest mismatch "
            f"(signed={envelope.schema_digest}, actual={actual})"
        )

    derived = _derive_capability_surface(contract)
    excess = derived - envelope.capabilities
    if excess:
        raise SkillBindingError(
            f"{envelope.skill_id}: schema exposes capabilities not in signed grant: {sorted(excess)}"
        )

    return BoundTool(skill_id=envelope.skill_id, contract=contract,
                     verified_digest=actual, frozen=True)


def invoke(tool: BoundTool, args: dict[str, Any]) -> dict[str, Any]:
    # Re-verify at invocation: the registry is a live, shared, mutable surface.
    if _canonical_digest(tool.contract) != tool.verified_digest:
        raise SkillBindingError(
            f"{tool.skill_id}: contract mutated after bind (post-load poisoning)"
        )
    if not tool.frozen:
        raise SkillBindingError(f"{tool.skill_id}: bound tool is not frozen")
    # ... dispatch to sandboxed executor ...
    return {"ok": True, "args": args}
