# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-tool-description-injection-that-survives-registry-re-derivation-but-not-schema-validation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-tool-description-injection-that-survives-registry-re-derivation-but-not-schema-validation.warrant.json
# Markdown SHA-256:   c47738106e75eae1ff6f9089acf7d37f7270b06f39e16fc41fe1d1578318adcf
# Code AST SHA-256:   0507b2e5239905237893df4c6966d2e0c3ef98d15a78b6f9688c8324b5e70822
# Verified Classes:   UnverifiedDescriptionMutation, ToolWarrant, AdmissionCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnverifiedDescriptionMutation(RuntimeError):
    """Raised when a tool description presented for prompt assembly does not
    match the description that was validated at admission time."""


@dataclass(frozen=True)
class ToolWarrant:
    name: str
    version: str
    description: str

    @property
    def digest(self) -> str:
        return hashlib.sha256(self.description.encode("utf-8")).hexdigest()


class AdmissionCache:
    """Caches admission decisions keyed by (name, version, description digest).

    A mutation to the description produces a different digest, which is a cache
    miss and therefore a forced re-validation, never a silent bypass.
    """

    def __init__(self, validate):
        self._validate = validate
        self._decisions: dict[tuple[str, str, str], bool] = {}

    def admit(self, warrant: ToolWarrant) -> bool:
        key = (warrant.name, warrant.version, warrant.digest)
        if key not in self._decisions:
            self._decisions[key] = self._validate(warrant.description)
        return self._decisions[key]


def assemble_prompt_tool_block(
    warrant: ToolWarrant,
    admitted: ToolWarrant,
    cache: AdmissionCache,
) -> str:
    """Build the tool block for the system prompt.

    The invariant: the description injected into the prompt must be the same
    description that was validated. If the registry has mutated the description
    since admission, the digest will differ and we refuse to assemble.
    """
    if warrant.digest != admitted.digest:
        if not cache.admit(warrant):
            raise UnverifiedDescriptionMutation(
                f"tool {warrant.name}@{warrant.version} description mutated "
                f"from {admitted.digest[:12]} to {warrant.digest[:12]} and "
                f"failed re-validation; refusing to inject into prompt"
            )
    return f"<tool name={warrant.name!r}>{admitted.description}</tool>"
