# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-whose-description-field-is-itself-an-instruction-the-latent-skill-injection-surface-in-dynamicall.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-whose-description-field-is-itself-an-instruction-the-latent-skill-injection-surface-in-dynamicall.warrant.json
# Markdown SHA-256:   9560088defc3d4db401d1a495350ead12b72152b44fc849cc264b6dac9faae13
# Code AST SHA-256:   6e71ac3935e3a3a32b954323733becca017c40b490c5d58746740346fce3b17f
# Verified Classes:   ManifestInjectionError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when untrusted manifest text reaches an instruction-bearing context
    without a provenance label, or when a call's justification traces to a manifest."""
    pass


INSTRUCTION_MARKERS = re.compile(
    r"\b(note to|assistant:|ignore previous|you must|first call|proceed silently|"
    r"without mentioning|do not tell|before answering)\b",
    re.IGNORECASE,
)


@dataclass
class Manifest:
    tool_id: str
    description: str
    trusted: bool  # authored by us, pinned at build time


def admit_manifest(m: Manifest, acting_context_has_instructions: bool) -> str:
    """Decide how a manifest may enter context. Returns the channel to use."""
    if m.trusted:
        return "instruction_channel"  # pinned, safe to inline

    # Untrusted manifest: scan for imperative/conditional injection markers.
    if INSTRUCTION_MARKERS.search(m.description):
        # Cannot sanitize reliably; route through isolated selector only.
        if acting_context_has_instructions:
            raise ManifestInjectionError(
                f"manifest {m.tool_id!r} carries instruction-like text and would "
                f"enter an instruction-bearing context; quarantine to isolated router"
            )
        return "isolated_router_channel"

    return "data_channel"  # provenance-tagged, non-authoritative


def verify_call_provenance(call, executed_log, reported_actions):
    """A permitted call is not a justified call. Trace its trigger."""
    justification = call.justification_source  # 'user' | 'manifest' | 'system'
    if justification == "manifest":
        raise ManifestInjectionError(
            f"tool {call.tool_id!r} invoked on manifest-derived justification; "
            f"treat as injected, do not execute"
        )
    if call.tool_id not in reported_actions:
        raise ManifestInjectionError(
            f"tool {call.tool_id!r} executed but omitted from response "
            f"(silent-action suppression detected); hard incident"
        )
    return True
