# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-continuity-across-a-capability-sandbox-boundary-when-a-dynamically-loaded-skill-re-negotiates-its-own-manife.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-continuity-across-a-capability-sandbox-boundary-when-a-dynamically-loaded-skill-re-negotiates-its-own-manife.warrant.json
# Markdown SHA-256:   407a6c7ecc655346c4ab0abadd4afbe65c2e4e5bde7c9b0de2cb91af1d1c6b62
# Code AST SHA-256:   da055eec0caec82ec2c1b4a5177a6e63b653c53a7f5fbdd5b33c0ca92af7b95c
# Verified Classes:   ProvenanceSkewError, CapabilityGrant, SkillInstance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceSkewError(RuntimeError):
    """Raised when a tool call is authorized against a capability set
    that no live, admission-chained signature describes."""


@dataclass(frozen=True)
class CapabilityGrant:
    grant_id: str
    caps: FrozenSet[str]
    signature: bytes
    manifest_bytes: bytes

    @staticmethod
    def issue(manifest_bytes: bytes, caps: FrozenSet[str], signer) -> "CapabilityGrant":
        canonical = b"|".join(sorted(c.encode() for c in caps))
        digest = hashlib.sha256(manifest_bytes + b"\x00" + canonical).digest()
        grant_id = digest.hex()
        return CapabilityGrant(
            grant_id=grant_id,
            caps=frozenset(caps),
            signature=signer(digest),
            manifest_bytes=manifest_bytes,
        )


@dataclass
class SkillInstance:
    name: str
    admitted_grant: CapabilityGrant
    live_manifest_caps: FrozenSet[str] = field(default_factory=frozenset)
    _inflight: int = 0

    def authorize(self, capability: str, verify) -> None:
        # The dispatcher MUST authorize against the admitted grant, not the
        # live manifest object. Any divergence is a provenance-skew event.
        if capability not in self.admitted_grant.caps:
            raise ProvenanceSkewError(
                f"skill={self.name} requested cap={capability!r} "
                f"not covered by grant={self.admitted_grant.grant_id}; "
                f"live_manifest_caps={sorted(self.live_manifest_caps)}"
            )
        if not verify(self.admitted_grant.signature, self.admitted_grant.grant_id):
            raise ProvenanceSkewError(
                f"skill={self.name} grant={self.admitted_grant.grant_id} "
                f"signature failed verification at dispatch time"
            )

    def on_manifest_watch(self, new_caps: FrozenSet[str]) -> None:
        # A manifest edit is inert until re-admission. Record it, do not merge.
        self.live_manifest_caps = frozenset(new_caps)
        if self._inflight > 0:
            raise ProvenanceSkewError(
                f"skill={self.name} manifest mutated during in-flight call; "
                f"quiesce required before re-admission"
            )


def dispatch_tool_call(skill: SkillInstance, capability: str, verify) -> None:
    skill._inflight += 1
    try:
        skill.authorize(capability, verify)
        # ... perform the sandboxed call under the admitted grant ...
    finally:
        skill._inflight -= 1
