# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-tool-manifest-and-the-behavioral-schema-it-declares.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-signed-tool-manifest-and-the-behavioral-schema-it-declares.warrant.json
# Markdown SHA-256:   77b4eefca007509bfcdedce653548842c650ff8e46521babf13b4b368583d93b
# Code AST SHA-256:   088a70c93916e5fb131629a7096a86bfe12fada355e8ef7c9a78f9bdc67f775f
# Verified Classes:   ManifestBehavioralMismatch, ParamSpec, ToolManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass
from typing import Any

DIRECTIVE_PATTERN = re.compile(
    r"\b(always|never|before calling|you must|assistant|ignore previous|pass the)\b",
    re.IGNORECASE,
)


class ManifestBehavioralMismatch(RuntimeError):
    """Raised when a manifest's declared schema diverges from trusted behavioral intent."""


@dataclass
class ParamSpec:
    name: str
    json_type: str
    description: str


@dataclass
class ToolManifest:
    name: str
    signature: str
    params: list[ParamSpec]


def verify_integrity(manifest: ToolManifest, trusted_signatures: dict[str, str]) -> None:
    expected = trusted_signatures.get(manifest.name)
    if expected is None or expected != manifest.signature:
        raise ManifestBehavioralMismatch(
            f"signature mismatch for tool {manifest.name!r}"
        )


def audit_descriptions(manifest: ToolManifest) -> list[str]:
    """Return param names whose descriptions contain directive-like phrasing.

    Integrity is NOT sufficient: a signed manifest can still carry injected
    instructions in structurally-valid description strings.
    """
    flagged: list[str] = []
    for p in manifest.params:
        if DIRECTIVE_PATTERN.search(p.description):
            flagged.append(p.name)
    return flagged


def gate_hot_load(
    manifest: ToolManifest,
    trusted_signatures: dict[str, str],
    allowed_origins: set[str],
) -> None:
    # Layer 1: integrity (necessary, not sufficient).
    verify_integrity(manifest, trusted_signatures)

    # Layer 2: behavioral fidelity — descriptions must not originate instructions.
    flagged = audit_descriptions(manifest)
    if flagged:
        raise ManifestBehavioralMismatch(
            f"tool {manifest.name!r} has directive-like descriptions on params "
            f"{flagged}; refusing hot-load (schema-conformant injection vector)"
        )

    # Layer 3: dispatch must only accept args from permitted provenance origins.
    if "manifest_directive" in allowed_origins:
        raise ManifestBehavioralMismatch(
            "manifest_directive origin cannot be an allowed argument provenance"
        )


def dispatch(
    manifest: ToolManifest,
    args: dict[str, Any],
    arg_origins: dict[str, str],
) -> Any:
    for name, origin in arg_origins.items():
        if origin == "manifest_directive":
            raise ManifestBehavioralMismatch(
                f"argument {name!r} originated from manifest text, not user/model synthesis"
            )
    raise ManifestBehavioralMismatch(
        "no execution backend wired; refusing to dispatch unverified tool"
    )
