# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-skill-manifest-s-capability-set-after-hot-swap-and-why-signature-validity-alone-is-insufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-skill-manifest-s-capability-set-after-hot-swap-and-why-signature-validity-alone-is-insufficient.warrant.json
# Markdown SHA-256:   ffec88800f5db8bfe959cb4bab9c006f59ab05ee63285d54060e0e75676a46e4
# Code AST SHA-256:   1f3d88dc8d357f12bb4b7e937c64c77ffd38c4fb3189fedd65d089b060e25a8f
# Verified Classes:   CapabilityDivergenceError, Manifest, ResolvedSkill
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CapabilityDivergenceError(RuntimeError):
    """Raised when granted capabilities do not match the verified manifest of the executed artifact."""


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    version: str
    capabilities: frozenset
    publisher_sig: str

    def digest(self) -> str:
        body = f"{self.skill_id}@{self.version}|{sorted(self.capabilities)}|{self.publisher_sig}"
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass
class ResolvedSkill:
    requested_manifest: Manifest          # what the caller named and the runtime verified
    executed_manifest: Manifest           # what the resolver actually selected
    authorized_caps: frozenset            # capabilities the caller's token actually grants
    sandbox_manifest_digest: str = ""     # digest the sandbox policy was built from


def build_sandbox_binding(skill: ResolvedSkill) -> frozenset:
    # Invariant 1: the sandbox must be built from the manifest of the executed artifact,
    # not the requested one. Building from the requested manifest while executing a
    # different artifact is the divergence bug.
    if skill.sandbox_manifest_digest != skill.executed_manifest.digest():
        raise CapabilityDivergenceError(
            f"sandbox built from manifest {skill.sandbox_manifest_digest!r} "
            f"but executing artifact with manifest {skill.executed_manifest.digest()!r}"
        )

    # Invariant 2: the executed artifact's capabilities must be a subset of what the
    # caller authorized. A valid signature on a superset is still an escalation.
    granted = skill.executed_manifest.capabilities
    escalation = granted - skill.authorized_caps
    if escalation:
        raise CapabilityDivergenceError(
            f"skill {skill.executed_manifest.skill_id}@{skill.executed_manifest.version} "
            f"requests unauthorized capabilities {sorted(escalation)}; "
            f"caller authorized {sorted(skill.authorized_caps)}"
        )

    # Invariant 3: narrowing is allowed only explicitly; here we fail closed rather
    # than silently dropping capabilities the skill will need at runtime.
    requested = skill.requested_manifest.capabilities
    if not granted <= requested:
        raise CapabilityDivergenceError(
            f"resolved capabilities {sorted(granted)} exceed requested manifest "
            f"{sorted(requested)}"
        )

    return granted


def load_skill(skill: ResolvedSkill) -> frozenset:
    # Simulate the resolver having built the sandbox from the *requested* manifest
    # (the bug), then attempting to execute a patch release with extra capabilities.
    if not skill.sandbox_manifest_digest:
        skill.sandbox_manifest_digest = skill.requested_manifest.digest()
    return build_sandbox_binding(skill)


if __name__ == "__main__":
    requested = Manifest("browser-ops", "2.x", frozenset({"net.fetch", "dom.parse"}), "sig:pub")
    executed = Manifest(
        "browser-ops", "2.7.1", frozenset({"net.fetch", "dom.parse", "fs.read", "proc.spawn"}), "sig:pub"
    )
    skill = ResolvedSkill(
        requested_manifest=requested,
        executed_manifest=executed,
        authorized_caps=frozenset({"net.fetch", "dom.parse"}),
    )
    load_skill(skill)  # raises CapabilityDivergenceError at the load boundary
