# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-server-supply-chain-drift-from-silently-widening-an-agent-s-capability-envelope-across-a-re-pinned-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-server-supply-chain-drift-from-silently-widening-an-agent-s-capability-envelope-across-a-re-pinned-manifest.warrant.json
# Markdown SHA-256:   ef400f52f6dc38d13360f4a4f9fc85f15de5ae341113f6933d559f9c80e940f3
# Code AST SHA-256:   6db83450d6b365919ef23c5e5bddaaeaf3cfebdcea8ad4bcf13326f9f7ce2940
# Verified Classes:   CapabilityEnvelopeViolation, RuntimeAttestationMismatch, AuthorizationCommitment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a session would bind to a manifest whose capability set
    widens beyond the persisted authorization commitment without an explicit
    re-authorization event."""


class RuntimeAttestationMismatch(RuntimeError):
    """Raised when the running server's measured tool registry or scope does
    not match the manifest the session was authorized against."""


def canonicalize_capabilities(manifest: dict[str, Any]) -> dict[str, Any]:
    """Reduce a signed manifest to its capability-bearing structure.

    Excludes description prose, signature envelope, and field ordering so that
    re-signing or prose edits diff empty, while tool additions, schema changes,
    and scope changes diff non-empty.
    """
    tools = {}
    for tool in manifest.get("tools", []):
        tools[tool["name"]] = {
            "input_schema": _stable_hash(tool.get("inputSchema", {})),
            "output_schema": _stable_hash(tool.get("outputSchema", {})),
        }
    scope = manifest.get("resources", {})
    return {
        "tools": dict(sorted(tools.items())),
        "roots": sorted(scope.get("roots", [])),
        "network": bool(scope.get("network", False)),
    }


def _stable_hash(obj: Any) -> str:
    return hashlib.sha256(
        json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def commitment_digest(capabilities: dict[str, Any]) -> str:
    return _stable_hash(capabilities)


@dataclass
class AuthorizationCommitment:
    session_id: str
    server_name: str
    digest: str
    capabilities: dict[str, Any] = field(default_factory=dict)


def diff_capabilities(
    old: dict[str, Any], new: dict[str, Any]
) -> dict[str, list[str]]:
    """Return the widening elements between two canonical capability sets.

    Narrowing is reported separately and does not block; widening blocks.
    """
    widening: list[str] = []
    narrowing: list[str] = []

    old_tools, new_tools = set(old["tools"]), set(new["tools"])
    widening += [f"tool_added:{t}" for t in sorted(new_tools - old_tools)]
    narrowing += [f"tool_removed:{t}" for t in sorted(old_tools - new_tools)]

    for name in sorted(old_tools & new_tools):
        if old["tools"][name] != new["tools"][name]:
            widening.append(f"tool_schema_changed:{name}")

    old_roots, new_roots = set(old["roots"]), set(new["roots"])
    widening += [f"root_added:{r}" for r in sorted(new_roots - old_roots)]
    narrowing += [f"root_removed:{r}" for r in sorted(old_roots - new_roots)]

    if not old["network"] and new["network"]:
        widening.append("network_enabled")
    elif old["network"] and not new["network"]:
        narrowing.append("network_disabled")

    return {"widening": widening, "narrowing": narrowing}


def bind_session(
    *,
    manifest: dict[str, Any],
    signature_valid: bool,
    prior: AuthorizationCommitment | None,
    reauthorized_digests: set[str],
    runtime_measured: dict[str, Any],
) -> AuthorizationCommitment:
    """Bind a session to a manifest, enforcing the envelope invariant.

    Signature validity is a precondition, never a substitute for authorization.
    """
    if not signature_valid:
        raise CapabilityEnvelopeViolation(
            f"manifest for {manifest.get('name')!r} failed signature verification"
        )

    new_caps = canonicalize_capabilities(manifest)
    new_digest = commitment_digest(new_caps)

    if prior is not None:
        delta = diff_capabilities(prior.capabilities, new_caps)
        if delta["widening"] and new_digest not in reauthorized_digests:
            raise CapabilityEnvelopeViolation(
                f"capability envelope widened for {manifest['name']!r} "
                f"({', '.join(delta['widening'])}) without authorization "
                f"for digest {new_digest[:12]}"
            )

    measured_caps = canonicalize_capabilities(runtime_measured)
    if commitment_digest(measured_caps) != new_digest:
        raise RuntimeAttestationMismatch(
            f"runtime attestation for {manifest['name']!r} diverges from "
            f"authorized manifest: measured={commitment_digest(measured_caps)[:12]} "
            f"declared={new_digest[:12]}"
        )

    return AuthorizationCommitment(
        session_id=manifest["_session_id"],
        server_name=manifest["name"],
        digest=new_digest,
        capabilities=new_caps,
    )
