# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-fetched-at-runtime-skill-injection-via-schema-embedded-instructions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-fetched-at-runtime-skill-injection-via-schema-embedded-instructions.warrant.json
# Markdown SHA-256:   e6ffd3f8eeff297d36414a6bbe1ce7856fd81e8a1394153a4a1dc45267bec9ac
# Code AST SHA-256:   5b9cd3b5421eb3da8324c6257a3e282e07f21f3bef511a4f72f03d77e1d36640
# Verified Classes:   ManifestAdmissionError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestAdmissionError(RuntimeError):
    """Raised when a runtime-fetched tool manifest fails content admission."""


# Heuristic: second-person address + imperative verb + tool-name reference.
_INSTRUCTION_PATTERN = re.compile(
    r"\b(you|assistant|agent)\b.{0,80}\b(must|should|first|before|always|call)\b",
    re.IGNORECASE | re.DOTALL,
)


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    schema_field_descriptions: tuple[str, ...]
    declared_root: str | None  # schema-declared authority bound, if any

    def content_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.name.encode())
        h.update(self.description.encode())
        for d in self.schema_field_descriptions:
            h.update(d.encode())
        return h.hexdigest()


def admit_manifest(
    manifest: ToolManifest,
    approved_hashes: frozenset[str],
    ambient_scope_root: str,
) -> str:
    """Returns the provenance tag to splice into context, or raises."""
    strings = (manifest.description, *manifest.schema_field_descriptions)
    for s in strings:
        if _INSTRUCTION_PATTERN.search(s):
            raise ManifestAdmissionError(
                f"manifest {manifest.name!r} carries instruction-like text in a "
                f"description field; quarantine pending review: {s[:80]!r}"
            )

    if manifest.declared_root is None:
        raise ManifestAdmissionError(
            f"manifest {manifest.name!r} declares no authority bound; "
            f"cannot execute against ambient scope {ambient_scope_root!r}"
        )

    digest = manifest.content_hash()
    if digest not in approved_hashes:
        raise ManifestAdmissionError(
            f"manifest {manifest.name!r} content hash {digest[:12]} is unapproved; "
            f"hot-reload refused, requires review event"
        )

    return f"[manifest:{manifest.name}@sha256:{digest[:12]}]"
