# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-skill-provenance-before-the-first-tool-call-not-after.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-skill-provenance-before-the-first-tool-call-not-after.warrant.json
# Markdown SHA-256:   35b2d70b475cc424703069b1b06c1bb7efa3dd7de7add723d26b30f29bef6fd4
# Code AST SHA-256:   89ee24258845b188834daec7e1686ee672199f3cbf080f4e3a41b402036fd8b3
# Verified Classes:   ProvenanceDriftError, CapabilityEscalationError, SkillDescriptor, VerifiedSkill, ProvenanceGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class ProvenanceDriftError(RuntimeError):
    """Raised when a skill's binding changed between verification and invocation."""


class CapabilityEscalationError(ProvenanceDriftError):
    """Raised when a re-pointed skill adds authority under a stable identifier."""


@dataclass(frozen=True)
class SkillDescriptor:
    name: str
    version: str
    manifest_hash: str
    capabilities: frozenset[str]


@dataclass
class VerifiedSkill:
    descriptor: SkillDescriptor
    verified_at_step: int
    capabilities_at_verify: frozenset[str] = field(init=False)

    def __post_init__(self) -> None:
        self.capabilities_at_verify = self.descriptor.capabilities


class ProvenanceGate:
    """Enforces per-invocation provenance: the hash verified is the hash invoked."""

    def __init__(self, registry_head: callable, allow_list: set[str]) -> None:
        self._head = registry_head
        self._allow = allow_list
        self._verified: dict[str, VerifiedSkill] = {}

    def verify(self, name: str, step: int) -> VerifiedSkill:
        desc = self._head(name)
        if desc.manifest_hash not in self._allow:
            raise ProvenanceDriftError(
                f"skill {name!r} manifest {desc.manifest_hash} not allow-listed"
            )
        vs = VerifiedSkill(descriptor=desc, verified_at_step=step)
        self._verified[name] = vs
        return vs

    def authorize_invocation(self, name: str, step: int) -> SkillDescriptor:
        cached = self._verified.get(name)
        if cached is None:
            raise ProvenanceDriftError(
                f"skill {name!r} invoked at step {step} without prior verification"
            )
        current = self._head(name)
        if current.manifest_hash != cached.descriptor.manifest_hash:
            added = current.capabilities - cached.capabilities_at_verify
            if added:
                raise CapabilityEscalationError(
                    f"skill {name!r} re-pointed at step {step}: hash "
                    f"{cached.descriptor.manifest_hash} -> {current.manifest_hash}, "
                    f"new capabilities {sorted(added)}; re-resolve required"
                )
            raise ProvenanceDriftError(
                f"skill {name!r} hash drift at step {step}: "
                f"{cached.descriptor.manifest_hash} -> {current.manifest_hash}"
            )
        return current


def _demo() -> None:
    store = {
        "doc.ingest": SkillDescriptor(
            "doc.ingest", "1.2", hashlib.sha256(b"v1").hexdigest(), frozenset({"read"})
        )
    }
    gate = ProvenanceGate(lambda n: store[n], allow_list={store["doc.ingest"].manifest_hash})
    gate.verify("doc.ingest", step=3)

    # Routine deploy re-points the skill and adds egress under the same name.
    store["doc.ingest"] = SkillDescriptor(
        "doc.ingest", "1.3", hashlib.sha256(b"v2").hexdigest(),
        frozenset({"read", "network.egress"}),
    )
    try:
        gate.authorize_invocation("doc.ingest", step=41)
    except CapabilityEscalationError as exc:
        print(f"blocked: {exc}")


if __name__ == "__main__":
    _demo()
