# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-never-re-validates-after-registry-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-never-re-validates-after-registry-resolution.warrant.json
# Markdown SHA-256:   1257120fa5c3bc7cadb7a4ef909aaee6a0f1e2b3d003b24826332189429dc4b0
# Code AST SHA-256:   ead6e9b08a97c887e3d083a10dcfe0c0347b2eb620e5752e591301d8029e9ce2
# Verified Classes:   DescriptionAttestationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib


class DescriptionAttestationError(RuntimeError):
    """Raised when a tool description is not covered by the attested manifest."""


def resolve_and_inject(tool_ref, registry, attested_manifest):
    resolved = registry.resolve(tool_ref.name)

    # Name stability is not trust continuity: mapping must still be pinned.
    if resolved.publisher != tool_ref.pinned_publisher:
        raise DescriptionAttestationError(
            f"registry re-pointed {tool_ref.name!r} from "
            f"{tool_ref.pinned_publisher!r} to {resolved.publisher!r}; re-pin required"
        )

    desc_bytes = resolved.description.encode("utf-8")
    desc_digest = hashlib.sha256(desc_bytes).hexdigest()

    attested = attested_manifest.get(tool_ref.name)
    if attested is None:
        raise DescriptionAttestationError(
            f"no attested manifest entry for {tool_ref.name!r}; refusing injection"
        )

    # Schema hash matching is insufficient; description must be attested too.
    if desc_digest != attested.description_digest:
        raise DescriptionAttestationError(
            f"description drift for {tool_ref.name!r}: "
            f"attested={attested.description_digest} got={desc_digest}"
        )

    # Wrap as untrusted data so the model does not read it as instructions.
    return f"<tool-description untrusted=\"true\" name=\"{tool_ref.name}\">\n" \
           f"{resolved.description}\n</tool-description>"
