# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-skill-manifest-when-its-declared-capability-hash-matches-a-stale-cache-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-skill-manifest-when-its-declared-capability-hash-matches-a-stale-cache-entry.warrant.json
# Markdown SHA-256:   afc627a6b85463d7512e1cb2853fe264de6b6e262c280d89379a8327818d81bc
# Code AST SHA-256:   b0eb26298d076835302e3446b903c1130cc4d7b3bbdd04829d116057890225da
# Verified Classes:   CapabilityBindingError, Manifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilityBindingError(RuntimeError):
    """Raised when a capability body does not bind to its manifest hash."""


@dataclass(frozen=True)
class Manifest:
    name: str
    version: str
    content_hash: str  # sha256:<hex> over the canonical body bytes
    body_uri: str


def load_capability(manifest: Manifest, body_cache: dict[str, bytes]) -> bytes:
    # Content-addressed lookup: key MUST be the hash, never the name.
    expected = manifest.content_hash.removeprefix("sha256:")
    body = body_cache.get(f"sha256:{expected}")

    if body is None:
        # Fall back to a name-keyed store only to *fetch*, never to trust.
        body = body_cache.get(f"name:{manifest.name}")

    if body is None:
        raise CapabilityBindingError(
            f"no body for {manifest.name}@{manifest.version}"
        )

    actual = hashlib.sha256(body).hexdigest()
    if actual != expected:
        # Binding gap detected: manifest trusted, body drifted.
        # Invalidate the trust record so retries cannot reuse it.
        body_cache.pop(f"name:{manifest.name}", None)
        raise CapabilityBindingError(
            f"body hash {actual} != manifest hash {expected} "
            f"for {manifest.name}@{manifest.version}; refusing execution"
        )

    return body
