# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-dynamically-registered-skill-escape-provenance-checks-when-its-manifest-is-re-signed-during-hot-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-dynamically-registered-skill-escape-provenance-checks-when-its-manifest-is-re-signed-during-hot-reload.warrant.json
# Markdown SHA-256:   37cfb017b3918ea8a2d9be0a1ad86bb89a339079409cb963f88615b2c8e3a300
# Code AST SHA-256:   0a993cf601b3f4503a21aceb1e7e807aeb644301c824381d7867c485963c4230
# Verified Classes:   SkillProvenanceError, Manifest, AuthorizationCache
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SkillProvenanceError(RuntimeError):
    """Raised when a skill invocation's authorization context does not match
    the manifest digest of the callable actually being invoked."""
    pass


@dataclass
class Manifest:
    skill_name: str
    publisher_id: str
    capabilities: frozenset
    body: bytes

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass
class AuthorizationCache:
    # Keyed on (skill_name, manifest_digest) -- NOT on skill_name alone.
    _grants: dict = field(default_factory=dict)

    def grant(self, manifest: Manifest, allowed_caps: frozenset) -> None:
        self._grants[(manifest.skill_name, manifest.digest)] = allowed_caps

    def lookup(self, manifest: Manifest) -> frozenset:
        key = (manifest.skill_name, manifest.digest)
        if key not in self._grants:
            raise SkillProvenanceError(
                f"no authorization for {manifest.skill_name} at digest "
                f"{manifest.digest}; manifest changed under a stable name"
            )
        return self._grants[key]


def invoke_skill(manifest: Manifest, cache: AuthorizationCache,
                 requested: frozenset) -> None:
    granted = cache.lookup(manifest)
    if not requested.issubset(granted):
        raise SkillProvenanceError(
            f"skill {manifest.skill_name} requested {sorted(requested)} "
            f"but only {sorted(granted)} authorized at digest {manifest.digest}"
        )
    # proceed to invoke callable bound to manifest.digest
