# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-signed-skill-registry-that-swaps-a-manifest-between-verification-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-signed-skill-registry-that-swaps-a-manifest-between-verification-and-invocation.warrant.json
# Markdown SHA-256:   492c1ee63e855d54181a53e3f5a98dbcea2de9e9c08ae2c6d88cdafe19f5f978
# Code AST SHA-256:   edbc2474b89ffc9180edd5a6498548ae0fe13a7a8b7a0af04fe924115b0257b3
# Verified Classes:   ManifestBindingError, Manifest, Artifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestBindingError(RuntimeError):
    """Raised when the artifact dispatched does not match the verified manifest."""


@dataclass(frozen=True)
class Manifest:
    name: str
    version: str
    payload_digest: str | None  # None == manifest makes no claim about bytes
    side_effect_class: str


@dataclass(frozen=True)
class Artifact:
    name: str
    version: str
    payload: bytes

    def digest(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


def verify_then_dispatch(manifest: Manifest, artifact: Artifact, signature_ok: bool) -> None:
    # Predicate 1: authenticity of the manifest document.
    if not signature_ok:
        raise ManifestBindingError(f"manifest signature invalid for {manifest.name}@{manifest.version}")

    # Predicate 2: binding of manifest to the bytes actually dispatched.
    # Signature validity says nothing about this; it must be checked independently.
    if manifest.payload_digest is None:
        # No byte-level claim: refuse to dispatch under declared capabilities.
        # Caller must fall back to behavioral probation, not declared profile.
        raise ManifestBindingError(
            f"manifest {manifest.name}@{manifest.version} carries no payload_digest; "
            "cannot bind verified manifest to dispatched artifact"
        )

    actual = artifact.digest()
    if actual != manifest.payload_digest:
        # The verify/use window was crossed: registry swapped the artifact
        # between verification and resolution. Abort, do not warn.
        raise ManifestBindingError(
            f"TOCTOU on {manifest.name}@{manifest.version}: "
            f"verified manifest expects {manifest.payload_digest}, "
            f"dispatch resolved {actual} — artifact swapped after verification"
        )

    # Safe to dispatch: manifest is authentic AND bound to these exact bytes.
    # Capability profile may now be derived from manifest metadata.
    return None
