# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-skill-s-provenance-signature-after-capability-manifest-mutation-but-before-sandbox-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-skill-s-provenance-signature-after-capability-manifest-mutation-but-before-sandbox-re-entry.warrant.json
# Markdown SHA-256:   89dc4e8acb8db18c833ad05a4034c5cd40f6ef829630c59f6f93646445cb2f28
# Code AST SHA-256:   7ee1a504c6c5778cf84c27dea0630a863deefc3cf59717e3a8a0909b04b7d217
# Verified Classes:   ProvenanceBindingError, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceBindingError(RuntimeError):
    """Raised when a skill's verified manifest does not bind to the bytes about to execute."""


@dataclass(frozen=True)
class SignedManifest:
    skill_id: str
    resolved_version: str
    artifact_digest: str          # H(artifact_bytes) at signing time
    declared_scopes: frozenset   # authoritative; artifact config may only narrow
    signature_valid: bool


def resolve_and_verify(
    manifest: SignedManifest,
    artifact_bytes: bytes,
    cache_key_skill_id_only: bool,
    caller_grant: frozenset,
) -> frozenset:
    # A signature over a manifest that does not content-address the artifact
    # attests to a name, not to bytes. Refuse to treat it as payload trust.
    if not manifest.signature_valid:
        raise ProvenanceBindingError(
            f"signature invalid for {manifest.skill_id}@{manifest.resolved_version}"
        )
    if cache_key_skill_id_only:
        # Cache hit keyed on skill_id alone cannot distinguish a swapped
        # artifact behind a stable name; the cached manifest is unverified.
        raise ProvenanceBindingError(
            f"cache key for {manifest.skill_id} omits digest; re-verify required"
        )
    actual = hashlib.sha256(artifact_bytes).hexdigest()
    if actual != manifest.artifact_digest:
        # The swap window: manifest signed for one artifact, different bytes
        # resolved. Sandbox policy would be derived from the wrong document.
        raise ProvenanceBindingError(
            f"artifact digest mismatch for {manifest.skill_id}: "
            f"manifest={manifest.artifact_digest} executed={actual}"
        )
    # Effective capability set is the intersection; artifact self-declared
    # config may only narrow, never union.
    effective = caller_grant & manifest.declared_scopes
    if not effective <= caller_grant:
        raise ProvenanceBindingError("capability union attempted; manifest not authoritative")
    return frozenset(effective)
