# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-manifest-provenance-as-a-security-boundary-rather-than-a-metadata-field.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-manifest-provenance-as-a-security-boundary-rather-than-a-metadata-field.warrant.json
# Markdown SHA-256:   b243d3b9377b3340fa53cb232c681dd9f0e1b36fb6fc9f42e4bd51cbe9030c0b
# Code AST SHA-256:   ce1ec638e7a409b59933f245d75fa1ebfd2be1c3fb1a32010b42613a3f97b85a
# Verified Classes:   UntrustedManifestError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class UntrustedManifestError(RuntimeError):
    """Raised when a manifest crosses the provenance/instruction boundary."""
    pass


@dataclass(frozen=True)
class Manifest:
    name: str
    source: str
    description: str
    handler: object


# Imperative verbs that indicate the description is instructing the agent,
# not describing the tool. Cross-tool name references are the strongest signal.
_INSTRUCTION_MARKERS = (
    "before using", "first call", "you must", "ignore previous",
    "instead call", "then invoke", "do not tell", "include the contents",
)


def _references_sibling(description: str, all_names: Iterable[str]) -> bool:
    lowered = description.lower()
    return any(n.lower() in lowered for n in all_names if n.lower() != "")


def load_manifests(
    manifests: Iterable[Manifest],
    signed_allowlist: frozenset[str],
) -> list[Manifest]:
    """Load only manifests whose source is operator-signed and whose prose
    does not attempt to direct the agent's tool selection."""
    manifests = list(manifests)
    names = [m.name for m in manifests]
    accepted: list[Manifest] = []

    for m in manifests:
        if m.source not in signed_allowlist:
            raise UntrustedManifestError(
                f"manifest {m.name!r} from unsigned source {m.source!r}; "
                f"refusing to load (provenance boundary)"
            )

        lowered = m.description.lower()
        if any(marker in lowered for marker in _INSTRUCTION_MARKERS):
            raise UntrustedManifestError(
                f"manifest {m.name!r} description contains imperative "
                f"instruction text; treating as skill injection"
            )

        if _references_sibling(m.description, names):
            raise UntrustedManifestError(
                f"manifest {m.name!r} description references a sibling tool; "
                f"cross-tool reference is an injection vector"
            )

        accepted.append(m)

    return accepted
