# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-dynamically-loaded-agent-skill-has-mutated-its-own-capability-manifest-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-dynamically-loaded-agent-skill-has-mutated-its-own-capability-manifest-mid-session.warrant.json
# Markdown SHA-256:   59cb7cd906a4129f2e226ecbdc9372cdc7a57513b50e7195e97dae1d856c78a9
# Code AST SHA-256:   343883d3116015f8e37f9eac82735bb55f8c9be725b8338cc5888a68c49e88cc
# Verified Classes:   DescriptorDriftError, CapabilityWideningError, Descriptor, TrustRecord, SkillRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DescriptorDriftError(RuntimeError):
    """Raised when the descriptor used to bind a call differs from the admitted descriptor."""
    pass


class CapabilityWideningError(RuntimeError):
    """Raised when an invoked descriptor advertises scopes not present at admission."""
    pass


@dataclass(frozen=True)
class Descriptor:
    name: str
    scopes: frozenset
    params: tuple
    raw: bytes

    def digest(self) -> str:
        return hashlib.sha256(self.raw).hexdigest()


@dataclass
class TrustRecord:
    admitted_hash: str
    admitted_scopes: frozenset


class SkillRegistry:
    def __init__(self):
        self._trust: dict[str, TrustRecord] = {}

    def admit(self, desc: Descriptor) -> None:
        self._trust[desc.name] = TrustRecord(
            admitted_hash=desc.digest(),
            admitted_scopes=desc.scopes,
        )

    def bind(self, desc: Descriptor) -> None:
        """Called at dispatch time with the descriptor actually used to bind arguments."""
        record = self._trust.get(desc.name)
        if record is None:
            raise DescriptorDriftError(f"skill {desc.name!r} invoked without admission")

        if desc.digest() != record.admitted_hash:
            raise DescriptorDriftError(
                f"descriptor drift for {desc.name!r}: "
                f"admitted={record.admitted_hash[:12]} invoked={desc.digest()[:12]}"
            )

        widened = desc.scopes - record.admitted_scopes
        if widened:
            raise CapabilityWideningError(
                f"skill {desc.name!r} widened scope at dispatch: {sorted(widened)}"
            )
