# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-tool-manifest-after-a-clean-registry-handshake-the-skill-injection-surface-in-dynamically-loaded-plugin-registr.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-tool-manifest-after-a-clean-registry-handshake-the-skill-injection-surface-in-dynamically-loaded-plugin-registr.warrant.json
# Markdown SHA-256:   83b7be7ae354fb48fc8195d7d40fda28507b707180882aa948f792cb04e53bbf
# Code AST SHA-256:   2ed534dc629231d9b965efce4fda857a11b01dea5337ad9b6426d75309f7467c
# Verified Classes:   ManifestIntegrityError, SignedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestIntegrityError(RuntimeError):
    """Raised when served manifest bytes do not match the signed content digest,
    or when a cache entry is keyed on identity rather than content."""


@dataclass(frozen=True)
class SignedManifest:
    name: str
    schema_hash: str                 # identity: parameter schema only
    signed_content_digest: str       # integrity: over RENDERED bytes the model reads
    rendered_bytes: bytes            # description, examples, usage_notes, etc.


def _content_digest(rendered: bytes) -> str:
    return hashlib.sha256(rendered).hexdigest()


def admit_manifest(manifest: SignedManifest, cache: dict[str, bytes]) -> bytes:
    """Admit a manifest to model context only if content integrity holds.

    The digest must cover the exact bytes delivered to the model. Identity
    (name/schema_hash) is necessary but never sufficient.
    """
    if not manifest.signed_content_digest:
        raise ManifestIntegrityError(
            f"{manifest.name}: no content digest over rendered bytes; "
            "manifest is unsigned prose and must be quarantined"
        )

    actual = _content_digest(manifest.rendered_bytes)
    if actual != manifest.signed_content_digest:
        # A post-signing transformation (i18n, auto-doc, summarizer) mutated
        # instruction-bearing fields. Signature still "valid"; content is not.
        raise ManifestIntegrityError(
            f"{manifest.name}: rendered content digest {actual[:12]} != "
            f"signed {manifest.signed_content_digest[:12]}; "
            "possible skill injection via descriptive fields"
        )

    # Content-addressed cache: key is the digest of the bytes the model reads.
    # Keying on (name, schema_hash) would allow silent poisoning on redeploy.
    cached = cache.get(actual)
    if cached is not None and cached != manifest.rendered_bytes:
        raise ManifestIntegrityError(
            f"{manifest.name}: cache collision under content digest {actual[:12]}"
        )
    cache[actual] = manifest.rendered_bytes
    return manifest.rendered_bytes
