# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-trust-a-dynamically-loaded-skill-s-declared-capability-surface-after-mcp-tool-descriptor-poisoning-mutates-its-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-trust-a-dynamically-loaded-skill-s-declared-capability-surface-after-mcp-tool-descriptor-poisoning-mutates-its-schema.warrant.json
# Markdown SHA-256:   5d27be1a846335f3046c463fdb6364ef288c7af06b98f30a7ec97c3d5deb723b
# Code AST SHA-256:   dbe6ce0a885d24f36c8c8bdc7941d70063321cc5a63243793be147cb969809f0
# Verified Classes:   DescriptorDigestMismatch, PinnedSkill
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class DescriptorDigestMismatch(RuntimeError):
    """Raised when a skill descriptor's content hash diverges from its pinned provisioning digest."""
    pass


@dataclass(frozen=True)
class PinnedSkill:
    name: str
    digest: str  # hex sha256 over canonical descriptor bytes, recorded at provisioning


def canonical_digest(descriptor: Mapping) -> str:
    # Canonicalize: sorted keys, no whitespace, UTF-8. Any byte change flips the hash.
    payload = json.dumps(descriptor, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def verify_and_admit(pinned: PinnedSkill, live_descriptor: Mapping) -> Mapping:
    """
    Fail-closed admission gate. Returns the descriptor only if its canonical digest
    matches the provisioning-time pin. On mismatch, quarantines: raises, and the caller
    MUST drop the cached prompt prefix and re-plan without this skill.
    """
    if live_descriptor.get("name") != pinned.name:
        raise DescriptorDigestMismatch(
            f"descriptor name {live_descriptor.get('name')!r} != pinned {pinned.name!r}"
        )
    observed = canonical_digest(live_descriptor)
    if observed != pinned.digest:
        # Do NOT re-fetch-and-accept. The registry is the untrusted party.
        raise DescriptorDigestMismatch(
            f"skill {pinned.name!r} descriptor mutated: "
            f"pinned={pinned.digest[:12]}… observed={observed[:12]}…; "
            f"quarantine and require signed re-provisioning"
        )
    return live_descriptor


def build_manifest(pinned_skills: Mapping[str, PinnedSkill],
                   live_descriptors: Mapping[str, Mapping]) -> dict:
    """
    Assemble the tool manifest from verified descriptors only. Any skill that fails
    verification is excluded from context entirely — the model never sees mutated text.
    """
    manifest = {}
    quarantined = []
    for name, pinned in pinned_skills.items():
        live = live_descriptors.get(name)
        if live is None:
            quarantined.append((name, "missing"))
            continue
        try:
            manifest[name] = verify_and_admit(pinned, live)
        except DescriptorDigestMismatch as exc:
            quarantined.append((name, str(exc)))
    if quarantined:
        # Surface to operator; invalidate cached prefix; do not silently continue.
        raise DescriptorDigestMismatch(
            f"{len(quarantined)} skill(s) quarantined; cached prefix must be dropped: {quarantined}"
        )
    return manifest
