# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-tool-schema-after-a-registry-re-sync-the-manifest-signature-description-body-split-in-dynamically-loaded-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-tool-schema-after-a-registry-re-sync-the-manifest-signature-description-body-split-in-dynamically-loaded-agent.warrant.json
# Markdown SHA-256:   3268154e0331beffc0a63fd06973d26bd230ad9e3ce92aa9e73b89eb3083ec25
# Code AST SHA-256:   68a8c83a09cd48b9582c37ea17bbf06996013091e04738b649b9256ee896afe7
# Verified Classes:   DescriptionManifestSplitError, ToolEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptionManifestSplitError(RuntimeError):
    """Raised when a tool's description text is not bound into its signed manifest,
    or when a cached checkpoint depends on a description that no longer matches
    the live signed hash. This is the signature-theater failure: the manifest
    verifies, but the text the model reasons over is unauthenticated."""


@dataclass(frozen=True)
class ToolEntry:
    name: str
    version: str
    manifest_hash: str          # hash of signed manifest bytes
    description: str            # natural-language text the model reads
    description_hash: str       # H(description); MUST be a signed field
    signed_description_hash: str | None  # the hash committed inside the signature


def _h(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def verify_tool_load(entry: ToolEntry, cached_manifest_hash: str | None) -> None:
    """Load gate. Rejects any entry whose description is outside the signed preimage,
    and rejects description-only diffs that did not re-sign the manifest."""
    if entry.signed_description_hash is None:
        raise DescriptionManifestSplitError(
            f"tool {entry.name!r} has no signed description hash; "
            "description is outside the signature preimage and is adversarial by default"
        )
    if _h(entry.description) != entry.signed_description_hash:
        raise DescriptionManifestSplitError(
            f"tool {entry.name!r} description hash does not match signed value; "
            "description body was mutated after signing"
        )
    # description-only diff with unchanged manifest is a protocol violation
    if cached_manifest_hash is not None and cached_manifest_hash == entry.manifest_hash:
        # manifest unchanged -> description must also be unchanged, else tampered
        if entry.description_hash != entry.signed_description_hash:
            raise DescriptionManifestSplitError(
                f"tool {entry.name!r} changed description without re-signing manifest"
            )


def resume_checkpoint(entry: ToolEntry, checkpoint_description_hash: str) -> None:
    """Checkpoint gate. A checkpoint whose plan was conditioned on a now-stale
    description must be invalidated, not resumed."""
    if checkpoint_description_hash != entry.signed_description_hash:
        raise DescriptionManifestSplitError(
            f"checkpoint for {entry.name!r} depends on stale description "
            f"{checkpoint_description_hash[:12]}; live signed hash is "
            f"{entry.signed_description_hash[:12]}; checkpoint must be invalidated"
        )
