# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-skill-whose-manifest-hash-matches-but-whose-declared-capability-surface-has-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-skill-whose-manifest-hash-matches-but-whose-declared-capability-surface-has-silently-widened.warrant.json
# Markdown SHA-256:   be84013ce38e1616e08792f101ff7647637ef4372f5552ba9b5b1a8453c72794
# Code AST SHA-256:   cc2a9f003eb6002fa0d9d73f81b34a7d5442fec808cd015488d4ec0da3df8a53
# Verified Classes:   CapabilitySurfaceDrift, ApprovedSkill
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilitySurfaceDrift(RuntimeError):
    """Raised when a skill's digest verifies but its resolved capability surface widened."""
    pass


@dataclass(frozen=True)
class ApprovedSkill:
    name: str
    content_digest: str                 # hash of manifest bytes
    capability_fingerprint: str         # hash of DEREFERENCED descriptor + transitive tools


def _dereference_and_fingerprint(manifest: dict, resolve_ref, proxied_tools: list) -> str:
    """Inline every $ref, expand proxied MCP tool lists, include description text.

    The description is part of the surface because the planner routes on it.
    """
    resolved = {
        "tool": manifest["tool"]["name"],
        "inputSchema": resolve_ref(manifest["tool"]["inputSchema"]),  # recursive deref
        "description": manifest["tool"].get("description", ""),       # routing-relevant
        "proxied": sorted(proxied_tools),                             # transitive servers
        "dialect": manifest.get("schemaDialect", "draft-2020-12"),
    }
    blob = json.dumps(resolved, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def admit_skill(manifest: dict, manifest_bytes: bytes, approved: ApprovedSkill,
                resolve_ref, proxied_tools: list) -> None:
    content_digest = "sha256:" + hashlib.sha256(manifest_bytes).hexdigest()

    # Gate 1: byte integrity.
    if content_digest != approved.content_digest:
        raise CapabilitySurfaceDrift(
            f"{approved.name}: manifest bytes changed ({content_digest} != {approved.content_digest}); "
            "full re-approval required"
        )

    # Gate 2: capability surface. THIS is the invariant the digest cannot cover.
    live_fp = _dereference_and_fingerprint(manifest, resolve_ref, proxied_tools)
    if live_fp != approved.capability_fingerprint:
        raise CapabilitySurfaceDrift(
            f"{approved.name}: digest verified but capability surface drifted "
            f"({live_fp} != {approved.capability_fingerprint}); "
            "likely $ref swap / description widening / proxied-tool expansion. Quarantine."
        )
    # Both invariants hold: admit to the reasoning loop.
